repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
l0gd0g/passport-ucoz
node_modules/passport-oauth1/lib/strategy.js
13793
/** * Module dependencies. */ var passport = require('passport-strategy') , url = require('url') , util = require('util') , utils = require('./utils') , OAuth = require('oauth').OAuth , InternalOAuthError = require('./errors/internaloautherror'); /** * Creates an instance of `OAuthStrategy`. * * The OAuth authentication strategy authenticates requests using the OAuth * protocol. * * OAuth provides a facility for delegated authentication, whereby users can * authenticate using a third-party service such as Twitter. Delegating in this * manner involves a sequence of events, including redirecting the user to the * third-party service for authorization. Once authorization has been obtained, * the user is redirected back to the application and a token can be used to * obtain credentials. * * Applications must supply a `verify` callback, for which the function * signature is: * * function(token, tokenSecret, profile, done) { ... } * * The verify callback is responsible for finding or creating the user, and * invoking `done` with the following arguments: * * done(err, user, info); * * `user` should be set to `false` to indicate an authentication failure. * Additional `info` can optionally be passed as a third argument, typically * used to display informational messages. If an exception occured, `err` * should be set. * * Options: * * - `requestTokenURL` URL used to obtain an unauthorized request token * - `accessTokenURL` URL used to exchange a user-authorized request token for an access token * - `userAuthorizationURL` URL used to obtain user authorization * - `consumerKey` identifies client to service provider * - `consumerSecret` secret used to establish ownership of the consumer key * - `callbackURL` URL to which the service provider will redirect the user after obtaining authorization * - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`) * * Examples: * * passport.use(new OAuthStrategy({ * requestTokenURL: 'https://www.example.com/oauth/request_token', * accessTokenURL: 'https://www.example.com/oauth/access_token', * userAuthorizationURL: 'https://www.example.com/oauth/authorize', * consumerKey: '123-456-789', * consumerSecret: 'shhh-its-a-secret' * callbackURL: 'https://www.example.net/auth/example/callback' * }, * function(token, tokenSecret, profile, done) { * User.findOrCreate(..., function (err, user) { * done(err, user); * }); * } * )); * * @constructor * @param {Object} options * @param {Function} verify * @api public */ function OAuthStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = undefined; } options = options || {}; if (!verify) { throw new TypeError('OAuthStrategy requires a verify callback'); } if (!options.requestTokenURL) { throw new TypeError('OAuthStrategy requires a requestTokenURL option'); } if (!options.accessTokenURL) { throw new TypeError('OAuthStrategy requires a accessTokenURL option'); } if (!options.userAuthorizationURL) { throw new TypeError('OAuthStrategy requires a userAuthorizationURL option'); } if (!options.consumerKey) { throw new TypeError('OAuthStrategy requires a consumerKey option'); } if (options.consumerSecret === undefined) { throw new TypeError('OAuthStrategy requires a consumerSecret option'); } passport.Strategy.call(this); this.name = 'oauth'; this._verify = verify; // NOTE: The _oauth property is considered "protected". Subclasses are // allowed to use it when making protected resource requests to retrieve // the user profile. this._oauth = new OAuth(options.requestTokenURL, options.accessTokenURL, options.consumerKey, options.consumerSecret, '1.0', null, options.signatureMethod || 'HMAC-SHA1', null, options.customHeaders); this._userAuthorizationURL = options.userAuthorizationURL; this._callbackURL = options.callbackURL; this._key = options.sessionKey || 'oauth'; this._trustProxy = options.proxy; this._passReqToCallback = options.passReqToCallback; this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile; } /** * Inherit from `passport.Strategy`. */ util.inherits(OAuthStrategy, passport.Strategy); /** * Authenticate request by delegating to a service provider using OAuth. * * @param {Object} req * @api protected */ OAuthStrategy.prototype.authenticate = function(req, options) { options = options || {}; if (!req.session) { return this.error(new Error('OAuthStrategy requires session support. Did you forget app.use(express.session(...))?')); } var self = this; if (req.query && req.query.oauth_token) { // The request being authenticated contains an oauth_token parameter in the // query portion of the URL. This indicates that the service provider has // redirected the user back to the application, after authenticating the // user and obtaining their authorization. // // The value of the oauth_token parameter is the request token. Together // with knowledge of the token secret (stored in the session), the request // token can be exchanged for an access token and token secret. // // This access token and token secret, along with the optional ability to // fetch profile information from the service provider, is sufficient to // establish the identity of the user. // Bail if the session does not contain the request token and corresponding // secret. If this happens, it is most likely caused by initiating OAuth // from a different host than that of the callback endpoint (for example: // initiating from 127.0.0.1 but handling callbacks at localhost). if (!req.session[self._key]) { return self.error(new Error('Failed to find request token in session')); } var oauthToken = req.query.oauth_token; var oauthVerifier = req.query.oauth_verifier || null; var oauthTokenSecret = req.session[self._key].oauth_token_secret; // NOTE: The oauth_verifier parameter will be supplied in the query portion // of the redirect URL, if the server supports OAuth 1.0a. this._oauth.getOAuthAccessToken(oauthToken, oauthTokenSecret, oauthVerifier, function(err, token, tokenSecret, params) { if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); } // The request token has been exchanged for an access token. Since the // request token is a single-use token, that data can be removed from the // session. delete req.session[self._key].oauth_token; delete req.session[self._key].oauth_token_secret; if (Object.keys(req.session[self._key]).length === 0) { delete req.session[self._key]; } self._loadUserProfile(token, tokenSecret, params, function(err, profile) { if (err) { return self.error(err); } function verified(err, user, info) { if (err) { return self.error(err); } if (!user) { return self.fail(info); } self.success(user, info); } try { if (self._passReqToCallback) { var arity = self._verify.length; if (arity == 6) { self._verify(req, token, tokenSecret, params, profile, verified); } else { // arity == 5 self._verify(req, token, tokenSecret, profile, verified); } } else { var arity = self._verify.length; if (arity == 5) { self._verify(token, tokenSecret, params, profile, verified); } else { // arity == 4 self._verify(token, tokenSecret, profile, verified); } } } catch (ex) { return self.error(ex); } }); }); } else { // In order to authenticate via OAuth, the application must obtain a request // token from the service provider and redirect the user to the service // provider to obtain their authorization. After authorization has been // approved the user will be redirected back the application, at which point // the application can exchange the request token for an access token. // // In order to successfully exchange the request token, its corresponding // token secret needs to be known. The token secret will be temporarily // stored in the session, so that it can be retrieved upon the user being // redirected back to the application. var params = this.requestTokenParams(options); var callbackURL = options.callbackURL || this._callbackURL; if (callbackURL) { var parsed = url.parse(callbackURL); if (!parsed.protocol) { // The callback URL is relative, resolve a fully qualified URL from the // URL of the originating request. callbackURL = url.resolve(utils.originalURL(req, { proxy: this._trustProxy }), callbackURL); } } params.oauth_callback = callbackURL; this._oauth.getOAuthRequestToken(params, function(err, token, tokenSecret, params) { if (err) { return self.error(self._createOAuthError('Failed to obtain request token', err)); } // NOTE: params will contain an oauth_callback_confirmed property set to // true, if the server supports OAuth 1.0a. // { oauth_callback_confirmed: 'true' } if (!req.session[self._key]) { req.session[self._key] = {}; } req.session[self._key].oauth_token = token || params.oauth_token; req.session[self._key].oauth_token_secret = tokenSecret || params.oauth_token_secret; var parsed = url.parse(self._userAuthorizationURL, true); parsed.query.oauth_token = token || params.oauth_token; utils.merge(parsed.query, self.userAuthorizationParams(options)); delete parsed.search; var location = url.format(parsed); self.redirect(location); }); } }; /** * Retrieve user profile from service provider. * * OAuth-based authentication strategies can overrride this function in order to * load the user's profile from the service provider. This assists applications * (and users of those applications) in the initial registration process by * automatically submitting required information. * * @param {String} token * @param {String} tokenSecret * @param {Object} params * @param {Function} done * @api protected */ OAuthStrategy.prototype.userProfile = function(token, tokenSecret, params, done) { return done(null, {}); }; /** * Return extra parameters to be included in the request token request. * * Some OAuth providers require additional parameters to be included when * issuing a request token. Since these parameters are not standardized by the * OAuth specification, OAuth-based authentication strategies can overrride this * function in order to populate these parameters as required by the provider. * * @param {Object} options * @return {Object} * @api protected */ OAuthStrategy.prototype.requestTokenParams = function(options) { return {}; }; /** * Return extra parameters to be included in the user authorization request. * * Some OAuth providers allow additional, non-standard parameters to be included * when requesting authorization. Since these parameters are not standardized * by the OAuth specification, OAuth-based authentication strategies can * overrride this function in order to populate these parameters as required by * the provider. * * @param {Object} options * @return {Object} * @api protected */ OAuthStrategy.prototype.userAuthorizationParams = function(options) { return {}; }; /** * Parse error response from OAuth endpoint. * * OAuth-based authentication strategies can overrride this function in order to * parse error responses received from the request token and access token * endpoints, allowing the most informative message to be displayed. * * If this function is not overridden, a generic error will be thrown. * * @param {String} body * @param {Number} status * @return {Error} * @api protected */ OAuthStrategy.prototype.parseErrorResponse = function(body, status) { return null; }; /** * Load user profile, contingent upon options. * * @param {String} accessToken * @param {Function} done * @api private */ OAuthStrategy.prototype._loadUserProfile = function(token, tokenSecret, params, done) { var self = this; function loadIt() { return self.userProfile(token, tokenSecret, params, done); } function skipIt() { return done(null); } if (typeof this._skipUserProfile == 'function' && this._skipUserProfile.length > 1) { // async this._skipUserProfile(token, tokenSecret, function(err, skip) { if (err) { return done(err); } if (!skip) { return loadIt(); } return skipIt(); }); } else { var skip = (typeof this._skipUserProfile == 'function') ? this._skipUserProfile() : this._skipUserProfile; if (!skip) { return loadIt(); } return skipIt(); } }; /** * Create an OAuth error. * * @param {String} message * @param {Object|Error} err * @api private */ OAuthStrategy.prototype._createOAuthError = function(message, err) { var e; if (err.statusCode && err.data) { try { e = this.parseErrorResponse(err.data, err.statusCode); } catch (_) {} } if (!e) { e = new InternalOAuthError(message, err); } return e; }; /** * Expose `OAuthStrategy`. */ module.exports = OAuthStrategy;
mit
ordinary-developer/book_java_the_complete_reference_9_ed_h_schildt
my_code/chapter_2_OVERVIEW_OF_JAVA/02_a_second_short_program/Example2.java
343
/* Here is another short example Call this file "Example2.java" */ class Example2 { public static void main(String args[]) { int num; num = 100; System.out.println("This is num: " + num); num = num * 2; System.out.print("The value of num * 2 is "); System.out.println(num); } }
mit
MiSchroe/klf-200-api
src/KLF200-API/GW_CS_VIRGIN_STATE_CFM.ts
117
"use strict"; import { GW_FRAME_CFM } from "./common"; export class GW_CS_VIRGIN_STATE_CFM extends GW_FRAME_CFM {}
mit
angular/angular-cli-stress-test
src/app/components/comp-1157/comp-1157.component.ts
484
/** * @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 { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-comp-1157', templateUrl: './comp-1157.component.html', styleUrls: ['./comp-1157.component.css'] }) export class Comp1157Component implements OnInit { constructor() { } ngOnInit() { } }
mit
tedc/cattelani-theme
extras/setup.php
27144
<?php function ng_app($html) { $html = $html . ' class="no-js" ng-app="catellani"'; return $html; } //add_filter( 'language_attributes', 'ng_app', 100 ); function theme_setup() { add_theme_support( 'custom-logo' ); add_image_size('magazine', 1246, 700, true); add_image_size('vertical-thumb', 440, 560, true); } add_action('after_setup_theme', 'theme_setup'); // BREADCRUMB function breadcrumb_shortcode($atts) { $term_obj = ($atts['type'] == 'taxonomy') ? get_term($atts['id']) : false; $post_obj = ($atts['type'] == 'post') ? get_post($atts['id']) : false; ob_start(); include(locate_template('templates/breadcrumb.php', false, true)); return ob_get_clean(); } add_shortcode( 'breadcrumb', 'breadcrumb_shortcode'); //add_filter( 'acf/load_field/name=magazine_template', 'hide_field' ); //add_filter( 'acf/load_field/name=is_front_page', 'hide_field' ); function hide_field( $field ) { $field['conditional_logic'] = 1; return $field; } // ADD BUILDER TO CONTENT function builder_shortcode($attr) { ob_start(); if(!get_field('is_front_page')){get_template_part('templates/page', 'header');} if(get_field('magazine_template')) : get_template_part('index'); else : get_template_part('builder/init'); endif; return ob_get_clean(); } add_shortcode( 'builder', 'builder_shortcode' ); function collezioni_shortcode($atts) { $the_id = $atts['id']; // $array = array( // 'post_type' => 'lampade', // 'posts_per_page' => -1, // 'orderby' => 'menu_order', // 'order' => 'ASC', // 'tax_query' => array( // array( // 'taxonomy' => 'collezioni', // 'field' => 'term_id', // 'terms' => array($the_id) // ) // ) // ); // $lampade = get_posts($array); $collezioni = new WP_Query( array( 'post_type' => 'lampade', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'collezioni', 'field' => 'term_id', 'terms' => array($the_id) ) ) ) ); //$count = $collezioni->found_posts; if(!$collezioni->have_posts()) return; //$count = count($posts); $count = $collezioni->found_posts; $loop = $count > 2 ? 'true' : 'false'; $show = $count > 1 ? 'true' : 'false'; $bp = ($count == 3) ? ", 'breakpoints' : { 849 : {'loop' : true} }" : ''; $c = 0; $html = '<div class="collections collections--slider-h" ng-scroll-carousel current-collection="'.$the_id.'" ng-keydown="key($event)"><div class="collections__slider collections__slider--archive" scrollbar="carousel" axis-x="true">'; // foreach ($lampade as $post) { // ob_start(); // include(locate_template( 'templates/content-lampade.php', false, false )); // $item = ob_get_clean(); // $html .= $item; // $c++; // } while($collezioni->have_posts()) : $collezioni->the_post(); ob_start(); include(locate_template( 'templates/content-lampade.php', false, false )); $item = ob_get_clean(); $html .= $item; $c++; endwhile; wp_reset_query(); wp_reset_postdata(); $html .= '</div><div class="collections__loader"><div class="collections__spinner"></div></div><i class="icon-arrow icon-arrow-prev" ng-click="move(false)" ng-class="{hide : !isVisible, inactive : !isPrev}"></i><i class="icon-arrow icon-arrow-next" ng-click="move(true)" ng-class="{hide : !isVisible, inactive : !isNext}"></i></div>'; return $html; } add_shortcode( 'collezioni', 'collezioni_shortcode' ); function glossary_cat_shortcode($atts) { $the_id = $atts['id']; $current = get_term($the_id, get_option('glossary-settings')['slug-cat']); ob_start(); include(locate_template('templates/page-header.php', false, false)); include(locate_template( 'templates/'. get_option('glossary-settings')['slug-cat'] .'.php', false, false)); return ob_get_clean(); } add_shortcode( 'glossary_cat', 'glossary_cat_shortcode' ); function add_builder_shortcode($post_id) { $field = get_field_object('header_kind'); $layout = get_field_object('layout'); if(isset($_POST['acf'][$field['key']])) { $value = $_POST['acf'][$field['key']] == 0 ? 'default' : $_POST['acf'][$field['key']]; } else { return; } if( empty($value) ) { return; } $args = array( 'ID' => $post_id, 'post_content' => '[builder]' ); wp_update_post($args); } add_action( 'acf/save_post', 'add_builder_shortcode' ); // CHANGE WRAPPER add_filter('sage/wrap_base', 'my_sage_wrap'); function my_sage_wrap($templates) { array_unshift($templates, 'extras/base.php'); return $templates; } function na_remove_slug( $post_link, $post, $leavename ) { if ( ('lampade' != $post->post_type && 'progetti' != $post->post_type && 'installazioni' != $post->post_type) || 'publish' != $post->post_status ) { return $post_link; } $uri = ''; foreach ( $post->ancestors as $parent ) { $uri = get_post( $parent )->post_name . "/" . $uri; } $post_link = str_replace( $uri, '', $post_link ); $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'na_remove_slug', 10, 3 ); function gp_parse_request_trick( $query ) { // Only noop the main query if ( ! $query->is_main_query() ) return; // Only noop our very specific rewrite rule match if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'page', 'lampade', 'installazioni', 'progetti', 'glossary' ) ); } } add_action( 'pre_get_posts', 'gp_parse_request_trick' ); // add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 ); // function wpd_attachment_link( $link, $attachment_id ){ // $attachment = get_post( $attachment_id ); // // Only for attachments actually attached to a parent post // if( ! empty( $attachment->post_parent ) ) { // $parent_link = get_permalink( $attachment->post_parent ); // // make the link compatible with permalink settings with or without "/" at the end // $parent_link = rtrim( $parent_link, "/" ); // $link = $parent_link . '-gallery-' . $attachment_id; // } // return $link; // } add_filter( 'mfrh_new_filename', 'my_filter_filename', 10, 3 ); function my_filter_filename( $new, $old, $post ) { $file_name = preg_replace('/\.[^.]+$/', '', $new); $ext = preg_replace('/(.*)(\.[^.]+$)/', '$2', $new); $ext = str_replace('-media', '', $ext); return $file_name . "-media".$ext; } // add_action( 'init', function() { // // Tell WordPress how to handle the new structure // add_rewrite_rule( '(.+)-gallery-([0-9]{1,})/?$', 'index.php?attachment_id=$matches[2]', 'top' ); // } ); // Allow SVG add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) { global $wp_version; if ( $wp_version !== '4.7.1' ) { return $data; } $filetype = wp_check_filetype( $filename, $mimes ); return [ 'ext' => $filetype['ext'], 'type' => $filetype['type'], 'proper_filename' => $data['proper_filename'] ]; }, 10, 4 ); function cc_mime_types( $mimes ){ $mimes['svg'] = 'image/svg+xml'; $mimes['ogv'] = 'video/ogg'; return $mimes; } add_filter( 'upload_mimes', 'cc_mime_types' ); function fix_svg() { echo '<style type="text/css">.attachment-266x266, .thumbnail img { width: 100% !important; height: auto !important; }</style>'; } add_action( 'admin_head', 'fix_svg' ); add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo '<style> .toplevel_page_instagram img { height: 20px; } </style>'; } add_filter('deprecated_constructor_trigger_error', '__return_false'); remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); add_filter('excerpt_more','__return_false'); function my_acf_init() { acf_update_setting('google_api_key', 'AIzaSyAX6KpPbqUz3WUJL_sYlUwlIreVhf1VabM'); } add_action('acf/init', 'my_acf_init'); add_action( 'init', 'my_add_excerpts_to_pages' ); function my_add_excerpts_to_pages() { add_post_type_support( 'page', 'excerpt' ); } // Register and load the widget function wpb_load_widget() { register_widget( 'wpb_widget' ); } add_action( 'widgets_init', 'wpb_load_widget' ); // Creating the widget class wpb_widget extends WP_Widget { function __construct() { parent::__construct( // Base ID of your widget 'wpb_widget', // Widget name will appear in UI __('Icona linkabile', 'catellani'), // Widget description array( 'description' => __( 'Inserisci classe dell\'icona e link', 'catellani' ), ) ); } // Creating widget front-end public function widget( $args, $instance ) { $target = ($instance['target']) ? ' target="_blank"' : ''; echo '<a href="'.$instance['link'].'"'.$target.' class="icon-'.$instance['icon'].'"></a>'; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'icon' ] ) ) { $icon = $instance[ 'icon' ]; } else { $icon = ''; } if ( isset( $instance[ 'link' ] ) ) { $link = $instance[ 'link' ]; } else { $link = ''; } $target = isset( $instance[ 'target' ] ) ? $instance[ 'target' ] : false; // Widget admin form ?> <p> <label for="<?php echo $this->get_field_id( 'icon' ); ?>"><?php _e( 'Icona:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'icon' ); ?>" name="<?php echo $this->get_field_name( 'icon' ); ?>" type="text" value="<?php echo esc_attr( $icon ); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e( 'Link:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'link' ); ?>" name="<?php echo $this->get_field_name( 'link' ); ?>" type="text" value="<?php echo esc_attr( $icon ); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'target' ); ?>"><?php _e( 'Target:' ); ?></label> <input id="<?php echo $this->get_field_id( 'target' ); ?>" name="<?php echo $this->get_field_name( 'target' ); ?>" type="checkbox" value="<?php echo esc_attr( $target ); ?>" /> </p> <?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['icon'] = ( ! empty( $new_instance['icon'] ) ) ? strip_tags( $new_instance['icon'] ) : ''; $instance['link'] = ( ! empty( $new_instance['link'] ) ) ? strip_tags( $new_instance['link'] ) : ''; $instance['target'] = $new_instance['target']; return $instance; } } // Class wpb_widget ends here if( function_exists('acf_add_options_page') ) { // acf_add_options_sub_page(array( // 'page_title' => 'Footer', // 'menu_title' => 'Footer Settings', // 'parent_slug' => 'themes.php' // )); // acf_add_options_page(array( // 'page_title' => 'Cookie law', // 'menu_title' => 'Cookie law', // 'menu_slug' => 'cookie-law' // )); acf_add_options_page(array( 'page_title' => 'Instagram Settings', 'menu_title' => 'Instagram', 'menu_slug' => 'instagram', 'icon_url' => get_stylesheet_directory_uri() . '/assets/images/instagram.png' )); acf_add_options_sub_page(array( 'page_title' => 'Campi comuni', 'menu_title' => 'Campi comuni', 'parent_slug' => 'themes.php' )); acf_add_options_sub_page(array( 'page_title' => 'Breadcrumb', 'menu_title' => 'Breadcrumb', 'parent_slug' => 'themes.php' )); } //add_filter( 'manage_wpsl_stores_posts_columns', 'set_custom_edit_wpsl_stores_columns', 10, 1 ); add_action( 'manage_wpsl_stores_posts_custom_column' , 'custom_wpsl_stores_column', 10, 2 ); add_filter('manage_edit-wpsl_stores_columns', 'set_custom_edit_wpsl_stores_columns', 10, 1); function set_custom_edit_wpsl_stores_columns($columns) { $columns['wpsl_country'] = __( 'Nazione', 'catellani' ); $columns['wpsl_city'] = __( 'Città', 'catellani' ); $columns['wpsl_region'] = __( 'Regione', 'catellani' ); unset($columns['city']); unset($columns['state']); return $columns; } function custom_wpsl_stores_column( $column, $post_id ) { switch ( $column ) { case 'wpsl_country' : if($country = wp_get_post_terms( $post_id, 'countries' )) { echo '<a href="'.admin_url('edit.php?post_type=wpsl_stores&countries='.$country[0]->slug ).'">'.$country[0]->name.'</a>'; } //get_post_meta( $post_id, 'wpsl_country' , true ); break; case 'wpsl_city' : if($city = wp_get_post_terms( $post_id, 'cities' )) { echo '<a href="'.admin_url('edit.php?post_type=wpsl_stores&cities='.$city[0]->slug ).'">'.$city[0]->name.'</a>'; //echo $city[0]->name; } break; case 'wpsl_region' : if($region = wp_get_post_terms( $post_id, 'regioni' )) { echo '<a href="'.admin_url('edit.php?post_type=wpsl_stores&regioni='.$region[0]->slug ).'">'.$region[0]->name.'</a>'; //echo $region[0]->name; } break; } } add_filter( 'manage_aforismi_posts_columns', 'set_custom_edit_aforismi_columns' ); add_action( 'manage_aforismi_posts_custom_column' , 'custom_aforismi_column', 10, 2 ); function set_custom_edit_aforismi_columns($columns) { unset( $columns['author'] ); unset($columns['title']); unset($columns['date']); $columns['aforismi_content'] = __( 'Testo', 'catellani' ); $columns['aforismi_author'] = __( 'Autore', 'catellani' ); return $columns; } function custom_aforismi_column( $column, $post_id ) { switch ( $column ) { case 'aforismi_content' : echo get_field( 'testo_aforisma' , $post_id ); break; case 'aforismi_author' : if ( get_field( 'default_sign', $post_id ) ) echo 'Enzo Catelanni'; else echo get_field( 'firma_aforisma' , $post_id ); break; } } add_filter( 'manage_lampade_posts_columns', 'set_custom_edit_lampade_columns' ); add_action( 'manage_lampade_posts_custom_column' , 'custom_lampade_column', 10, 2 ); function set_custom_edit_lampade_columns($columns) { $columns['lampade_colors'] = __( 'Colori', 'catellani' ); return $columns; } function custom_lampade_column( $column, $post_id ) { switch ( $column ) { case 'lampade_colors' : $colors = wp_get_post_terms( $post_id, 'colori_materiali', array( '' ) ); $count = 0; foreach($colors as $color) : $comma = ($count>0) ? ', ' : ''; echo $comma.$color->name; $count++; endforeach; break; } } function my_yoats_single_link($output, $link) { $lang = (preg_match('/(en)/', $link['url'])) ? 'en' : 'it'; $url = str_replace(get_home_url(), '', $link['url']); $sref = ''; $matches = preg_match('/(category|categorie)/', $url); if($url == '' || $url == '/') { $sref = ' ui-sref="app.root({lang : \''.$lang.'\'})"'; } else { if($matches) { $sref = ' ui-sref="app.category({lang : \''.$lang.'\', name : \'\'})"'; } else { $sref = ' ui-sref="app.root({lang : \''.$lang.'\', slug : \''.$url.'\'})"'; } } $output = str_replace('<a', '<a'.$sref, $output); return $output; } add_filter('wpseo_breadcrumb_single_link', 'my_yoats_single_link', 10, 2); if (has_action('wp_head','_wp_render_title_tag') == 1) { remove_action('wp_head','_wp_render_title_tag',1); add_action('wp_head','custom_wp_render_title_tag_filtered',1); } function custom_wp_render_title_tag_filtered() { if (function_exists('_wp_render_title_tag')) { ob_start(); _wp_render_title_tag(); $titletag = ob_get_contents(); ob_end_clean(); } else {$titletag = '';} $titletag = apply_filters('wp_render_title_tag_filter',$titletag); echo $titletag; } //add_filter('wp_render_title_tag_filter','custom_wp_render_title_tag'); function custom_wp_render_title_tag($titletag) { $titletag = str_replace('<title','<title ng-bind-html="(title || \''.addslashes(wp_get_document_title()).'\')"',$titletag); return $titletag; } function collezioni_posts_per_page($query) { if($query->is_tax('collezioni') && $query->is_main_query()) { $query->set('posts_per_page', -1); } return $query; } add_filter( 'pre_get_posts', 'collezioni_posts_per_page' ); function my_gallery_shortcode( $output = '', $attrs ) { global $post; $row = str_replace(',', '', $attrs['ids']); $ids = explode(',', $attrs['ids']); $images = array(); $full = true; foreach ($ids as $id) { array_push($images, array('ID' => $id, 'url' => wp_get_attachment_image_src( $id, 'full')[0], 'alt' => get_post_meta( $id, '_wp_attachment_image_alt', true))); } ob_start(); $prepend = ($post->post_type == 'post') ? '</div>' : ''; $append = ($post->post_type == 'post') ? '<div class="container__content container__content--mw">' : ''; include(locate_template('builder/commons/gallery.php', false, false)); $output = $prepend.'<div class="container__gallery container__gallery--shrink-fw container__gallery--grow-lg-top container__gallery--grow-md-bottom" id="slider_'.$row.'">'.ob_get_clean().'</div>'.$append; return $output; } add_filter( 'post_gallery', 'my_gallery_shortcode', 10, 2 ); add_filter( 'the_excerpt', 'shortcode_unautop'); add_filter('the_excerpt', 'do_shortcode'); remove_filter('get_the_excerpt', 'wp_trim_excerpt', 10); add_filter('get_the_excerpt', 'my_custom_wp_trim_excerpt', 99, 1); function my_custom_wp_trim_excerpt($text) { if(''==$text) { $text= preg_replace('/\s/', ' ', wp_strip_all_tags(get_field('content'))); $text= explode(' ', $text, 50); array_pop($text); $text= implode(' ', $text); } return $text; } function custom_excerpt_length( $length ) { return 50; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); include_once('order_by_tax.php'); new Tax_CTP_Filter( array( 'lampade' => array('collezioni') ) ); add_filter('the_excerpt', 'do_shortcode'); /** * my_terms_clauses * * filter the terms clauses * * @param $clauses array * @param $taxonomy string * @param $args array * @return array * @link http://wordpress.stackexchange.com/a/183200/45728 **/ function my_terms_clauses( $clauses, $taxonomy, $args ) { global $wpdb; if ( !empty($args['post_types']) ) { $post_types = $args['post_types']; // allow for arrays if ( is_array($args['post_types']) ) { $post_types = implode("','", $args['post_types']); } $clauses['join'] .= " INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id"; $clauses['where'] .= " AND p.post_type IN ('". esc_sql( $post_types ). "') GROUP BY t.term_id"; } return $clauses; } add_filter('terms_clauses', 'my_terms_clauses', 99999, 3); add_filter( 'wpsl_meta_box_fields', 'custom_meta_box_fields' ); function custom_meta_box_fields( $meta_fields ) { $meta_fields[ __( 'Location', 'wpsl' )]['address']['required'] = false; $meta_fields[ __( 'Location', 'wpsl' )]['city']['required'] = false; $meta_fields[ __( 'Location', 'wpsl' )]['country']['required'] = false; return $meta_fields; } add_filter( 'wpseo_metadesc', 'fix_yoast_metadesc', 10, 1 ); function fix_yoast_metadesc( $str ) { $str = do_shortcode( $str ); $str= preg_replace('/\s/', ' ', wp_strip_all_tags($str)); //$str= explode(' ', $str, 100); // array_pop($str); // $str= implode(' ', $str); return $str; } // add_filter( 'get_next_post_where', function( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { // global $wpdb; // // Edit this custom post type to your needs // $cpt = 'lampade'; // // Current post type // $post_type = get_post_type( $post ); // // Nothing to do // if( $cpt !== $post_type ) // return $where; // $join = ''; // $where = ''; // if ( $in_same_term || ! empty( $excluded_terms ) ) { // if ( ! empty( $excluded_terms ) && ! is_array( $excluded_terms ) ) { // // back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and " // if ( false !== strpos( $excluded_terms, ' and ' ) ) { // _deprecated_argument( __FUNCTION__, '3.3.0', sprintf( __( 'Use commas instead of %s to separate excluded terms.' ), "'and'" ) ); // $excluded_terms = explode( ' and ', $excluded_terms ); // } else { // $excluded_terms = explode( ',', $excluded_terms ); // } // $excluded_terms = array_map( 'intval', $excluded_terms ); // } // if ( $in_same_term ) { // $join .= " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id"; // $where .= $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy ); // if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) ) // return ''; // $term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // // Remove any exclusions from the term array to include. // $term_array = array_diff( $term_array, (array) $excluded_terms ); // $term_array = array_map( 'intval', $term_array ); // if ( ! $term_array || is_wp_error( $term_array ) ) // return ''; // $where .= " AND tt.term_id IN (" . implode( ',', $term_array ) . ")"; // } // /** // * Filters the IDs of terms excluded from adjacent post queries. // * // * The dynamic portion of the hook name, `$adjacent`, refers to the type // * of adjacency, 'next' or 'previous'. // * // * @since 4.4.0 // * // * @param string $excluded_terms Array of excluded term IDs. // */ // //$excluded_terms = add_filter( "get_next_post_excluded_terms", function($excluded_terms){ return $excluded_terms;} ); // if ( ! empty( $excluded_terms ) ) { // $where .= " AND p.ID NOT IN ( SELECT tr.object_id FROM $wpdb->term_relationships tr LEFT JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) WHERE tt.term_id IN (" . implode( ',', array_map( 'intval', $excluded_terms ) ) . ') )'; // } // } // // // Next CPT order by last word in title // // add_filter( 'get_next_post_sort', function( $orderby ) // // { // // return "ORDER BY p.post_title ASC LIMIT 1"; // // } ); // // Next CPT order by last word in title // add_filter( 'get_next_post_sort', function( $orderby ) // { // return "ORDER BY p.menu_order ASC LIMIT 1"; // } ); // //$where .= $wpdb->prepare( "WHERE p.post_title > %s AND p.post_type = %s AND ( p.post_status = 'publish' OR p.post_status = 'private' )", $post->post_title, $post->post_type ); // $where .= $wpdb->prepare( "WHERE p.menu_order > %s AND p.post_type = %s AND ( p.post_status = 'publish' OR p.post_status = 'private' )", $post->menu_order, $post->post_type ); // // Modify Next WHERE part // return $where; // }, 10, 5 ); function my_next_post_sort() { return "ORDER BY p.post_title ASC LIMIT 1"; } function my_next_post_where() { global $post, $wpdb; return $wpdb->prepare( "WHERE p.post_title > %s AND p.post_type = %s AND p.post_status = 'publish'", $post->post_title, $post->post_type); } function ikreativ_async_scripts($url) { if ( strpos( $url, '#asyncload') === false ) return $url; else if ( is_admin() ) return str_replace( '#asyncload', '', $url ); else return str_replace( '#asyncload', '', $url )."' async='async"; } add_filter( 'clean_url', 'ikreativ_async_scripts', 11, 1 ); add_filter('apto/navigation_sort_apply', 'theme_apto_navigation_sort_apply'); function theme_apto_navigation_sort_apply($current) { global $post; if($post->post_type == 'lampade') $current = TRUE; else $current = FALSE; return $current; } function modify_post_mime_types( $post_mime_types ) { // select the mime type, here: 'application/pdf' // then we define an array with the label values $post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) ); // then we return the $post_mime_types variable return $post_mime_types; } // Add Filter Hook add_filter( 'post_mime_types', 'modify_post_mime_types' ); function add_query_vars_filter( $vars ){ $vars[] = "post_pdf"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); function collezioni_og_image($image) { global $post; global $sitepress; if(is_tax('collezioni')) { $obj = get_queried_object(); $the_id = (ICL_LANGUAGE_CODE != $sitepress->get_default_language()) ? id_by_lang($obj->term_id, 'collezioni', ICL_LANGUAGE_CODE) : $obj->term_id; $image = get_field('cover_image', 'collezioni_'.$the_id)['url']; } if(is_single() || is_page()) { if(ICL_LANGUAGE_CODE != $sitepress->get_default_language()) { $the_id = id_by_lang($post->ID, $post->post_type, ICL_LANGUAGE_CODE); $image = get_the_post_thumbnail_url($the_id, 'full'); } } return $image; } add_filter('wpseo_opengraph_image', 'collezioni_og_image'); function collezioni_og_type($type) { if(is_tax('collezioni')) { $type = __('collezione', 'catellani'); } if(is_singular('lampade')) { $type = __('lampada', 'catellani'); } return $type; } add_filter('wpseo_opengraph_type', 'collezioni_og_type'); add_filter('mod_rewrite_rules', 'fix_rewritebase'); function fix_rewritebase($rules){ $home_root = parse_url(home_url()); if ( isset( $home_root['path'] ) ) { $home_root = trailingslashit($home_root['path']); } else { $home_root = '/'; } $wpml_root = parse_url(get_option('home')); if ( isset( $wpml_root['path'] ) ) { $wpml_root = trailingslashit($wpml_root['path']); } else { $wpml_root = '/'; } $rules = str_replace("RewriteBase $home_root", "RewriteBase $wpml_root", $rules); $rules = str_replace("RewriteRule . $home_root", "RewriteRule . $wpml_root", $rules); return $rules; } function my_wpml_hreflangs_html($hreflang) { $hreflang = str_replace('/"', '"', $hreflang); return $hreflang; } add_filter( 'wpml_hreflangs_html', 'my_wpml_hreflangs_html', 10, 1 );
mit
jocoonopa/reebonz
src/Woojin/GoodsBundle/DependencyInjection/WoojinGoodsExtension.php
880
<?php namespace Woojin\GoodsBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class WoojinGoodsExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
mit
igorkulman/Kulman.WPA81.BaseRestService
Kulman.WPA81.BaseRestService/Services/Abstract/BaseRestService.cs
26008
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.Storage.Streams; using Windows.Web.Http; using Windows.Web.Http.Filters; using JetBrains.Annotations; using Kulman.WPA81.BaseRestService.Services.Exceptions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Kulman.WPA81.BaseRestService.Services.Abstract { /// <summary> /// Base class for JSON based REST services /// </summary> public abstract class BaseRestService { /// <summary> /// Http filter /// </summary> [NotNull] private readonly HttpBaseProtocolFilter _filter; /// <summary> /// Cookie manager /// </summary> [NotNull] protected HttpCookieManager CookieManager => _filter.CookieManager; /// <summary> /// Logger /// </summary> [CanBeNull] protected ILogger Logger; /// <summary> /// Ctor, creates Http filter /// </summary> protected BaseRestService() { _filter = CreateHttpFilter(); } /// <summary> /// Must be overridden to set the Base URL /// </summary> /// <returns>Base URL</returns> protected abstract string GetBaseUrl(); /// <summary> /// Executed before every request /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>Task</returns> protected virtual Task OnBeforeRequest([NotNull] string url, CancellationToken token) { return Task.FromResult(1); } /// <summary> /// Can be overriden to set the default request headers /// </summary> /// <returns>Dictionary containing default request headers</returns> protected virtual Dictionary<string, string> GetRequestHeaders([NotNull] string requestUrl) { return new Dictionary<string, string>(); } #region HTTP GET /// <summary> /// REST Get /// </summary> /// <param name="url">Url</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Get<T>([NotNull] string url) { return GetResponse<T>(url, HttpMethod.Get, null, CancellationToken.None); } /// <summary> /// REST Get /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Get<T>([NotNull] string url, CancellationToken token) { return GetResponse<T>(url, HttpMethod.Get, null, token); } /// <summary> /// REST Get (RAW) /// </summary> /// <param name="url">Url</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Get([NotNull] string url) { return GetRawResponse(url, HttpMethod.Get, null, CancellationToken.None); } /// <summary> /// REST Get (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Get([NotNull] string url, CancellationToken token) { return GetRawResponse(url, HttpMethod.Get, null, token); } #endregion #region HTTP DELETE /// <summary> /// REST Delete /// </summary> /// <param name="url">Url</param> /// <returns>Task</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task Delete([NotNull] string url) { return GetResponse(url, HttpMethod.Delete, null, CancellationToken.None); } /// <summary> /// REST Delete /// </summary> /// <param name="url">Url</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Delete<T>([NotNull] string url) { return GetResponse<T>(url, HttpMethod.Delete, null, CancellationToken.None); } /// <summary> /// REST Delete /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Delete<T>([NotNull] string url, CancellationToken token) { return GetResponse<T>(url, HttpMethod.Delete, null, token); } /// <summary> /// REST Delete /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>Task</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task Delete([NotNull] string url, CancellationToken token) { return GetResponse(url, HttpMethod.Delete, null, token); } #endregion #region HTTP PUT /// <summary> /// REST Put /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Put<T>([NotNull] string url, [CanBeNull] object request) { return GetResponse<T>(url, HttpMethod.Put, request, CancellationToken.None); } /// <summary> /// REST Put /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Put<T>([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetResponse<T>(url, HttpMethod.Put, request, token); } /// <summary> /// REST Put (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Put([NotNull] string url, [CanBeNull] object request) { return GetRawResponse(url, HttpMethod.Put, request, CancellationToken.None); } /// <summary> /// REST Put (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Put([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetRawResponse(url, HttpMethod.Put, request, CancellationToken.None); } #endregion #region HTTP POST /// <summary> /// REST Post /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Post<T>([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetResponse<T>(url, HttpMethod.Post, request, token); } /// <summary> /// REST Post /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Post<T>([NotNull] string url, [CanBeNull] object request) { return GetResponse<T>(url, HttpMethod.Post, request, CancellationToken.None); } /// <summary> /// REST Post (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Post([NotNull] string url, [CanBeNull] object request) { return GetRawResponse(url, HttpMethod.Post, request, CancellationToken.None); } /// <summary> /// REST Post (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>HttpResponseMessage</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> protected Task<HttpResponseMessage> Post([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetRawResponse(url, HttpMethod.Post, request, token); } #endregion #region HTTP PATCH /// <summary> /// REST Patch /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Patch<T>([NotNull] string url, [CanBeNull] object request) { return GetResponse<T>(url, new HttpMethod("PATCH"), request, CancellationToken.None); } /// <summary> /// REST Patch /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>Deserialized data of type T</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> protected Task<T> Patch<T>([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetResponse<T>(url, new HttpMethod("PATCH"), request, token); } /// <summary> /// REST Patch (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <returns>HttpResponseMessage</returns> protected Task<HttpResponseMessage> Patch([NotNull] string url, [CanBeNull] object request) { return GetRawResponse(url, new HttpMethod("PATCH"), request, CancellationToken.None); } /// <summary> /// REST Patch (RAW) /// </summary> /// <param name="url">Url</param> /// <param name="request">Request object (will be serialized to JSON if not string)</param> /// <param name="token">Cancellation token</param> /// <returns>HttpResponseMessage</returns> protected Task<HttpResponseMessage> Patch([NotNull] string url, [CanBeNull] object request, CancellationToken token) { return GetRawResponse(url, new HttpMethod("PATCH"), request, CancellationToken.None); } #endregion /// <summary> /// Override if you need custom HttpClientHandler /// </summary> /// <returns>HttpClientHandler</returns> protected virtual HttpBaseProtocolFilter CreateHttpFilter() { var handler = new HttpBaseProtocolFilter { AutomaticDecompression = true }; return handler; } /// <summary> /// Creates a HTTP Client instance /// </summary> /// <param name="requestUrl">Request Url</param> /// <returns>HttpClient</returns> protected HttpClient CreateHttpClient([NotNull] string requestUrl) { var client = new HttpClient(_filter); var headers = GetRequestHeaders(requestUrl); foreach (var key in headers.Keys) { client.DefaultRequestHeaders.TryAppendWithoutValidation(key, headers[key]); } return client; } /// <summary> /// Creates JSON serializer settings. Can be overridden. /// </summary> /// <returns>JSON serializer settings</returns> protected virtual JsonSerializerSettings CreateJsonSerializerSettings() { var settings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), }; settings.Converters.Add(new StringEnumConverter()); return settings; } /// <summary> /// Gets HTTP response /// </summary> /// <param name="url">Url</param> /// <param name="method">HTTP Method</param> /// <param name="request">HTTP request</param> /// <param name="token">Cancellation token</param> /// <returns>Task</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> private Task GetResponse([NotNull] string url, [NotNull] HttpMethod method, [CanBeNull] object request, CancellationToken token) { return GetResponse<Object>(url, method, request, token, true); } /// <summary> /// Gets raw HTTP response /// </summary> /// <param name="url">Url</param> /// <param name="method">HTTP Method</param> /// <param name="request">HTTP request</param> /// <param name="noOutput">Output will not be proceed when true, method return default(T)</param> /// <param name="token">Cancellation token</param> /// <returns>Task</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> private async Task<HttpResponseMessage> GetRawResponse([NotNull] string url, [NotNull] HttpMethod method, [CanBeNull] object request, CancellationToken token, bool noOutput = false) { await OnBeforeRequest(url, token).ConfigureAwait(false); HttpResponseMessage data = null; HttpStringContent requestcontent = null; string requestBody = null; var content = request as string; if (content != null) { requestcontent = new HttpStringContent(content); } else if (request != null) { requestBody = JsonConvert.SerializeObject(request, CreateJsonSerializerSettings()); requestcontent = new HttpStringContent(requestBody, UnicodeEncoding.Utf8, "application/json"); } try { var fullUrl = (new[] { "http://", "https://" }).Any(url.StartsWith) ? url : GetBaseUrl() + url; var client = CreateHttpClient(fullUrl); var requestMessage = new HttpRequestMessage { Method = method, RequestUri = new Uri(fullUrl), Content = requestcontent, }; Logger?.Info($"{method} {fullUrl}"+ (requestBody != null ? "\r\n"+ requestBody : "")); data = token == CancellationToken.None ? await client.SendRequestAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead) : await client.SendRequestAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).AsTask(token); return data; } catch (TaskCanceledException) { Logger?.Error("Requesting {url} cancelled"); throw; } catch (Exception ex) { Logger?.Error($"Error communicating with the server for {url}", ex); throw new ConnectionException("Error communicating with the server. See the inner exception for details.", ex, data?.StatusCode ?? HttpStatusCode.ExpectationFailed, null); } } /// <summary> /// Gets HTTP response /// </summary> /// <param name="url">Url</param> /// <param name="method">HTTP Method</param> /// <param name="request">HTTP request</param> /// <param name="token">Cancellation token</param> /// <param name="noOutput">Output will not be proceed when true, method return default(T)</param> /// <returns>Task</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> /// <exception cref="DeserializationException">When JSON parser cannot process the server response data</exception> private async Task<T> GetResponse<T>([NotNull] string url, [NotNull] HttpMethod method, [CanBeNull] object request, CancellationToken token, bool noOutput = false) { T result; var data = await GetRawResponse(url, method, request, token, noOutput); try { data.EnsureSuccessStatusCode(); } catch (Exception ex) { var content = await data.Content.ReadAsStringAsync(); data.Content?.Dispose(); Logger?.Error($"Error communicating with the server for {url}", ex); throw new ConnectionException("Error communicating with the server. See the inner exception for details.", ex, data.StatusCode, content); } if (token != CancellationToken.None && token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } var json = await data.Content.ReadAsStringAsync(); try { result = JsonConvert.DeserializeObject<T>(json); } catch (Exception ex) { Logger?.Error($"Error while processing response for {url}.", ex); throw new DeserializationException("Error while processing response. See the inner exception for details.", ex, json); } if (token != CancellationToken.None && token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } return result; } /// <summary> /// REST Head /// </summary> /// <param name="url">Url</param> /// <returns>Dictionary with headers</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> public Task<Dictionary<string, string>> Head([NotNull] string url) { return Head(url, CancellationToken.None); } /// <summary> /// REST Head /// </summary> /// <param name="url">Url</param> /// <param name="token">Cancellation token</param> /// <returns>Dictionary with headers</returns> /// <exception cref="TaskCanceledException">When operation cancelled</exception> /// <exception cref="ConnectionException">When response from server does not indicate success</exception> public async Task<Dictionary<string, string>> Head([NotNull] string url, CancellationToken token) { await OnBeforeRequest(url, token).ConfigureAwait(false); try { Logger?.Info($"HEAD {GetBaseUrl() + url}"); var client = CreateHttpClient(GetBaseUrl() + url); var request = new HttpRequestMessage(HttpMethod.Head, new Uri(GetBaseUrl() + url)); var response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead); if (token != CancellationToken.None && token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } return response.Headers.ToDictionary(headerItem => headerItem.Key, headerItem => headerItem.Value); } catch (TaskCanceledException) { throw; } catch (Exception ex) { Logger?.Error($"Getting head for {url} failed", ex); throw new ConnectionException("Error communicating with the server. See the inner exception for details.", ex, HttpStatusCode.ExpectationFailed, null); } } } }
mit
gdg-tangier/vue-firestore
tests/vue-firestore.spec.js
675
import { Vue, firebase, firestore, VueTick, randomString } from './TestCase'; let vm, collection; describe('vue-firestore', () => { beforeEach(async () => { collection = firestore.collection('items'); vm = new Vue({ data: () => ({ items: null }), firestore() { return { items: collection }; } }); await VueTick(); }); test('setup $firestore', () => { expect(Object.keys(vm.$firestore).sort()).toEqual(['items']); expect(vm.$firestore.items).toBe(collection); }); test('unbind $firestore on $destroy', () => { vm.$destroy(); expect(vm.$firestore).toEqual(null); }); });
mit
joshsoftware/tip4commit
config/environments/production.rb
3474
T4c::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_files = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) smtp_settings = CONFIG['smtp_settings'] domain = smtp_settings['domain'] config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = smtp_settings.to_options config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.default_url_options = { :host => domain, :protocol => 'https' } config.action_mailer.default_options = {from: 'no-reply@' + domain } # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new end
mit
jordanams/lunchr
lunchr_extranet/app/controler/compte/index.php
875
<?php include('../app/model/compte/details_user.php'); include('../app/model/compte/update_user.php'); if(isset($_GET['logout'])) { session_destroy(); header('location:index.php?module=login&action=index&logout=1'); exit; } if(isset($_POST['nom_user'])) { $verif_details = verif_details($_SESSION['user_id']); if ($_POST['new_mdp_user'] != "") { $mdp_user = md5($_POST['new_mdp_user']); } else { $mdp_user = $verif_details[0]['lup_password']; } $update = update_user( $_POST['nom_user'], $_POST['prenom_user'], $_POST['phone_user'], $_POST['mail_user'], $mdp_user, $_SESSION['user_id']); if($update = true) { header('Location:index.php?module=compte&action=index&update_user=1'); } } $verif_details = verif_details($_SESSION['user_id']); include('../app/view/compte/index.php'); ?>
mit
mitsei/dlkit
dlkit/abstract_osid/osid/search_orders.py
22990
"""Implementations of osid abstract base class search_orders.""" # pylint: disable=invalid-name # Method names comply with OSID specification. # pylint: disable=no-init # Abstract classes do not define __init__. # pylint: disable=too-few-public-methods # Some interfaces are specified as 'markers' and include no methods. # pylint: disable=too-many-public-methods # Number of methods are defined in specification # pylint: disable=too-many-ancestors # Inheritance defined in specification # pylint: disable=too-many-arguments # Argument signature defined in specification. # pylint: disable=duplicate-code # All apparent duplicates have been inspected. They aren't. import abc class OsidSearchOrder: """``OsidSearchOrder`` specifies preferred ordering of search results. An ``OsidSearchOrder`` is available from an search session and supplied to an ``OsidSearch`` interface. OsidSearch os = session.getObjectSearch(); os.limitResultSet(1, 25); OsidSearchOrder order = session.getObjectSearchOrder(); order.orderByDisplayName(); os.orderResults(order); OsidQuery queru; query = session.getObjectQuery(); query.addDescriptionMatch("*food*", wildcardStringMatchType, true); ObjectSearchResults results = session.getObjectsBySearch(query, os); ObjectList list = results.getObjectList(); """ __metaclass__ = abc.ABCMeta class OsidIdentifiableSearchOrder: """``OsidIdentifiableSearchOrder`` specifies preferred ordering of search results. An ``OsidSearchOrder`` is available from an search session and supplied to an ``OsidSearch``. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_id(self, style): """Specifies a preference for ordering the result set by the ``Id``. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidExtensibleSearchOrder: """``OsidExtensibleSearchOrder`` specifies preferred ordering of search results. An ``OsidSearchOrder`` is available from an search session and supplied to an ``OsidSearch``. """ __metaclass__ = abc.ABCMeta class OsidBrowsableSearchOrder: """``OsidBrowsableSearchOrder`` specifies preferred ordering of search results. An ``OsidSearchOrder`` is available from an search session and supplied to an ``OsidSearch``. """ __metaclass__ = abc.ABCMeta class OsidTemporalSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_effective(self, style): """Specifies a preference for ordering the result set by the effective status. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_start_date(self, style): """Specifies a preference for ordering the result set by the start date. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_end_date(self, style): """Specifies a preference for ordering the result set by the end date. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidSubjugateableSearchOrder: """An interface for specifying the ordering of dependent object search results.""" __metaclass__ = abc.ABCMeta class OsidAggregateableSearchOrder: """An interface for specifying the ordering of assemblage search results.""" __metaclass__ = abc.ABCMeta class OsidContainableSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_sequestered(self, style): """Specifies a preference for ordering the result set by the sequestered flag. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidSourceableSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_provider(self, style): """Specifies a preference for ordering the results by provider. The element of the provider to order is not specified but may be managed through the provider ordering interface. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_provider_search_order(self): """Tests if a ``ProviderSearchOrder`` interface is available. :return: ``true`` if a provider search order interface is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_provider_search_order(self): """Gets the search order interface for a provider. :return: the provider search order interface :rtype: ``osid.resource.ResourceSearchOrder`` :raise: ``Unimplemented`` -- ``supports_provider_search_order()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_provider_search_order()`` is ``true``.* """ return # osid.resource.ResourceSearchOrder provider_search_order = property(fget=get_provider_search_order) class OsidFederateableSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta class OsidOperableSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_active(self, style): """Specifies a preference for ordering the result set by the active status. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_enabled(self, style): """Specifies a preference for ordering the result set by the administratively enabled status. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_disabled(self, style): """Specifies a preference for ordering the result set by the administratively disabled status. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_operational(self, style): """Specifies a preference for ordering the results by the operational status. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidObjectSearchOrder: """``OsidObjectSearchOrder`` specifies preferred ordering of search results. An ``OsidSearchOrder`` is available from an search session and supplied to an ``OsidSearch``. OsidObjectSearch os = session.getObjectSearch(); os.limitResultSet(1, 25); OsidObjectSearchOrder order = session.getObjectSearchOrder(); order.orderByDisplayName(); os.orderResults(order); OsidObjectQuery query; query = session.getObjectQuery(); query.addDescriptionMatch("*food*", wildcardStringMatchType, true); ObjectSearchResults results = session.getObjectsBySearch(query, os); ObjectList list = results.getObjectList(); """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_display_name(self, style): """Specifies a preference for ordering the result set by the display name. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_description(self, style): """Specifies a preference for ordering the result set by the description. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_genus_type(self, style): """Specifies a preference for ordering the result set by the genus type. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_state(self, process_id, style): """Orders by the state in a given ``Process``. :param process_id: a process ``Id`` :type process_id: ``osid.id.Id`` :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``process_id`` or ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_cumulative_rating(self, book_id, style): """Orders by the cumulative rating in a given ``Book``. :param book_id: a book ``Id`` :type book_id: ``osid.id.Id`` :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``book_id`` or ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_statistic(self, meter_id, style): """Orders by a statistic for a given ``Meter``. :param meter_id: a meter ``Id`` :type meter_id: ``osid.id.Id`` :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``meter_id`` or ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_create_time(self, style): """Orders by the timestamp of the first journal entry. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_last_modified_time(self, style): """Orders by the timestamp of the last journal entry. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidRelationshipSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_end_reason(self, style): """Specifies a preference for ordering the results by the end reason state. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_end_reason_search_order(self): """Tests if a ``StateSearchOrder`` is available. :return: ``true`` if a state search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_end_reason_search_order(self): """Gets the search order for a state. :return: the state search order :rtype: ``osid.process.StateSearchOrder`` :raise: ``Unimplemented`` -- ``supports_end_reason_search_order()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_end_reason_search_order()`` is ``true``.* """ return # osid.process.StateSearchOrder end_reason_search_order = property(fget=get_end_reason_search_order) class OsidCatalogSearchOrder: """An interface for specifying the ordering of catalog search results.""" __metaclass__ = abc.ABCMeta class OsidRuleSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_rule(self, style): """Specifies a preference for ordering the results by the associated rule. The element of the rule to order is not specified but may be managed through a ``RuleSearchOrder``. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_rule_search_order(self): """Tests if a ``RuleSearchOrder`` is available. :return: ``true`` if a rule search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_rule_search_order(self): """Gets the search order for a rule. :return: the rule search order :rtype: ``osid.rules.RuleSearchOrder`` :raise: ``Unimplemented`` -- ``supports_rule_search_order()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_rule_search_order()`` is ``true``.* """ return # osid.rules.RuleSearchOrder rule_search_order = property(fget=get_rule_search_order) class OsidEnablerSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_schedule(self, style): """Specifies a preference for ordering the results by the associated schedule. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_schedule_search_order(self): """Tests if a ``ScheduleSearchOrder`` is available. :return: ``true`` if a schedule search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_schedule_search_order(self): """Gets the search order for a schedule. :return: the schedule search order :rtype: ``osid.calendaring.ScheduleSearchOrder`` :raise: ``Unimplemented`` -- ``supports_schedule_search_order() is false`` *compliance: optional -- This method must be implemented if ``supports_schedule_search_order()`` is true.* """ return # osid.calendaring.ScheduleSearchOrder schedule_search_order = property(fget=get_schedule_search_order) @abc.abstractmethod def order_by_event(self, style): """Specifies a preference for ordering the results by the associated event. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_event_search_order(self): """Tests if an ``EventSearchOrder`` is available. :return: ``true`` if an event search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_event_search_order(self): """Gets the search order for an event. :return: the event search order :rtype: ``osid.calendaring.EventSearchOrder`` :raise: ``Unimplemented`` -- ``supports_event_search_order() is false`` *compliance: optional -- This method must be implemented if ``supports_event_search_order()`` is true.* """ return # osid.calendaring.EventSearchOrder event_search_order = property(fget=get_event_search_order) @abc.abstractmethod def order_by_cyclic_event(self, style): """Orders the results by cyclic event. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_cyclic_event_search_order(self): """Tests if a cyclic event search order is available. :return: ``true`` if a cyclic event search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_cyclic_event_search_order(self): """Gets the cyclic event search order. :return: the cyclic event search order :rtype: ``osid.calendaring.cycle.CyclicEventSearchOrder`` :raise: ``IllegalState`` -- ``supports_cyclic_event_search_order()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.cycle.CyclicEventSearchOrder cyclic_event_search_order = property(fget=get_cyclic_event_search_order) @abc.abstractmethod def order_by_demographic(self, style): """Specifies a preference for ordering the results by the associated demographic resource. :param style: search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def supports_demographic_search_order(self): """Tests if a ``ResourceSearchOrder`` is available. :return: ``true`` if a resource search order is available, ``false`` otherwise :rtype: ``boolean`` *compliance: mandatory -- This method must be implemented.* """ return # boolean @abc.abstractmethod def get_demographic_search_order(self): """Gets the search order for a demographic resource. :return: the resource search order :rtype: ``osid.resource.ResourceSearchOrder`` :raise: ``Unimplemented`` -- ``supports_demographic_search_order()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_demographic_search_order()`` is ``true``.* """ return # osid.resource.ResourceSearchOrder demographic_search_order = property(fget=get_demographic_search_order) class OsidConstrainerSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta class OsidProcessorSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta class OsidGovernatorSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta class OsidCompendiumSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def order_by_start_date(self, style): """Specifies a preference for ordering the result set by the start date. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_end_date(self, style): """Specifies a preference for ordering the result set by the end date. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_interpolated(self, style): """Specifies a preference for ordering the result set by interpolated results. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass @abc.abstractmethod def order_by_extrapolated(self, style): """Specifies a preference for ordering the result set by extrapolated results. :param style: the search order style :type style: ``osid.SearchOrderStyle`` :raise: ``NullArgument`` -- ``style`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ pass class OsidCapsuleSearchOrder: """An interface for specifying the ordering of search results.""" __metaclass__ = abc.ABCMeta
mit
marielb/ebolahackathon
Step_Model.php
1335
<?php require_once('Step_DAO.php'); require_once('Option_Model.php'); class Step_Model { public $dao; public $stepID; public $message; public $options; public function __construct($db, $stepID) { $this->dao = new Step_DAO($db); $this->stepID = $stepID; } public function loadOptions() { $result = $this->dao->loadOptions($this->stepID); $this->options = []; // echo var_dump($result); if (empty($result)) { return; } foreach ($result as $option) { $this->options[] = new Option_Model( $this->dao->db, $option['OptionID'], $option['OptionText'], $option['NextStep'] ); } } public function getNextStep($input) { $input = intval($input); $this->loadOptions(); foreach ($this->options as $option) { // echo $option->optionID; if ($option->optionID == $input) { $nextStep = new Step_Model($this->dao->db, $option->nextStep); return $nextStep; } } if (!empty($this->options)) { return -1; } } public function getStepMessage() { return $this->dao->getStepMessage($this->stepID); } public function getQuestion() { $this->loadOptions(); $str = $this->getStepMessage($this->stepID) . "\n"; foreach ($this->options as $option) { $str .= "" . $option->optionID . ": " . $option->optionText . "\n"; } return $str; } } ?>
mit
Lapanti/golf-scorebook
src/components/TabBar.js
1232
import React, {PropTypes} from 'react'; import TabBarButton from '../components/TabBarButton'; import { StyleSheet, View } from 'react-native'; const TabBar = React.createClass({ displayName: 'TabBar', propTypes: { tabs: PropTypes.array.isRequired, height: PropTypes.number.isRequired, currentTabIndex: PropTypes.number.isRequired, switchTab: PropTypes.func.isRequired, selectTab: PropTypes.func.isRequired }, render() { const buttons = this.props.tabs.map((tab, index) => ( <TabBarButton key={'tab-bar-button-' + tab.title} text={tab.title} action={() => { this.props.switchTab(index); this.props.selectTab(index); }} isSelected={index === this.props.currentTabIndex} /> )); return ( <View style={[styles.navigationBar, {height: this.props.height}]}> {buttons} </View> ); } }); const styles = StyleSheet.create({ navigationBar: { position: 'absolute', bottom: 0, left: 0, right: 0, backgroundColor: '#eee', flexDirection: 'row', justifyContent: 'space-around' }, buttonWrapper: { flex: 1, position: 'relative' } }); export default TabBar;
mit
StayHungryStayFoolish/stayhungrystayfoolish.github.com
JavaSE/src/main/java/basic/FinalDemo.java
521
package basic; /** * Created by bonismo * 14/10/17 上午11:50 */ public final class FinalDemo { final String name = null; final int age; // final 修饰的域,必须初始化赋值 1、直接赋值 2、构造器赋值 public FinalDemo(int age) { this.age = 18; } public FinalDemo() { this.age = 18; } public final void method(){ System.out.println("终态方法..."); } } /* final class 不能被继承 class SubFinalClass extends FinalDemo { } */
mit
digibib/ls.ext
redef/services/src/test/java/no/deichman/services/entity/external/ContextObjectTest.java
1228
package no.deichman.services.entity.external; import com.google.gson.Gson; import org.apache.jena.system.JenaSystem; import org.junit.BeforeClass; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Responsibility: Test context object. */ public class ContextObjectTest { @BeforeClass public static void setupJena() { JenaSystem.init(); // Needed to counter sporadic nullpointerexceptions because of context is not initialized. } @Test public void default_constructor_returns_context_object() { Map<String, String> map = new HashMap<String, String>(); map.put("deichman", "http://deichman.no/ontology#"); ContextObject contextObject = new ContextObject(); assertTrue(contextObject.getContext().containsValue("http://deichman.no/ontology#")); String json = new Gson().toJson(contextObject); String comparisonJson = "{\"@Context\":{\"deichman\":\"http://deichman.no/ontology#\",\"rdfs\":\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\"duo\":\"http://deichman.no/utility#\"}}"; assertEquals(comparisonJson,json); } }
mit
nasser/syntax-canvas
public/codemirror/mode/flexible/flexible.js
1731
CodeMirror.defineMode("flexible", function(config, mode) { return { startState: function() { return { parser: mode.parser, multiTokens: [] }; }, token: function(stream, state) { var style; style = this.matchSyntax(stream, state); if(style) return style; style = this.matchMultiTokens(stream, state); if(style) return style; stream.next(); return null; }, // check any remaining multitokens matchMultiTokens: function(stream, state) { for (var i = 0; i < state.multiTokens.length; i++) { var token = state.multiTokens[i][0]; var style = state.multiTokens[i][1]; if(stream.match(token)) { state.multiTokens.splice(i,1); return style; } } return null; }, // check each syntax rule for a match. if a multi token rule matches, // populate state.multiTokens to match them on next iterations matchSyntax: function(stream, state, ignore) { var syntax = state.parser.syntax; for (var i = 0; i < syntax.length; i++) { var token = syntax[i][0]; var styles = syntax[i][1].slice(); if(token == ignore) continue; if(styles.length < 2) { // single token rule if(stream.match(token)) return styles[0]; } else { // multi token rule var match = stream.match(token, false); if(match) { match.shift(); while(match.length > 0) state.multiTokens.unshift([match.shift(), styles.shift()]); var style; style = this.matchSyntax(stream, state, token); if(style) return style; style = this.matchMultiTokens(stream, state); if(style) return style; return null; } } } return null; } } }); CodeMirror.defineMIME("text/flexible", "flexible");
mit
mrstebo/slack-emoji-importer
lib/emoji.rb
68
class Emoji < Struct.new(:category, :id, :name, :command, :url) end
mit
mennowo/TLCGen
TLCGen.Dependencies/TLCGen.Dependencies/Helpers/Base64Encoding.cs
646
using System; using System.Text; namespace TLCGen.Dependencies.Helpers { public static class Base64Encoding { public static string EncodeTo64(string toEncode) { var toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode); var returnValue = Convert.ToBase64String(toEncodeAsBytes); return returnValue; } public static string DecodeFrom64(string encodedData) { var encodedDataAsBytes = Convert.FromBase64String(encodedData); var returnValue = Encoding.ASCII.GetString(encodedDataAsBytes); return returnValue; } } }
mit
Tom-Alexander/redux-ecommerce
lib/actions/__tests__/SessionActionsTest.js
1427
import sinon from 'sinon'; import {expect} from 'chai'; import {describe, it} from 'mocha'; import {service} from '../../services'; import {getSession, removeSession, createSession} from '../sessionActions'; describe('SessionActions', () => { afterEach(() => service.setFetcher(null)); describe('Action creators', () => { it('creates an action that gets the current session', () => { const fetcher = sinon.stub().returns(Promise.resolve({})); service.setFetcher(fetcher); getSession(); expect(fetcher).to.be.calledWith('api/v1/session', { body: null, method: 'GET', credentials: 'include' }); }); it('creates an action that creates a new session', () => { const fetcher = sinon.stub().returns(Promise.resolve({})); service.setFetcher(fetcher); createSession('username', 'password'); expect(fetcher).to.be.calledWith('api/v1/session', { body: {username: 'username', password: 'password'}, method: 'POST', credentials: 'include' }); }); it('creates an action that removes the current session', () => { const fetcher = sinon.stub().returns(Promise.resolve({})); service.setFetcher(fetcher); removeSession(); expect(fetcher).to.be.calledWith('api/v1/session', { body: null, method: 'DELETE', credentials: 'include' }); }); }); });
mit
orbitaljt/LEAD
Android/Lead/app/src/main/java/com/orbital/lead/logic/Asynchronous/AsyncUploadImage.java
4766
package com.orbital.lead.logic.Asynchronous; import android.os.AsyncTask; import com.orbital.lead.Parser.Parser; import com.orbital.lead.logic.WebConnector; import com.orbital.lead.model.Constant; import com.orbital.lead.model.EnumFileType; import com.orbital.lead.model.EnumPictureServiceType; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; /** * Created by joseph on 29/6/2015. */ public class AsyncUploadImage extends AsyncTask<String, Integer, String> { Parser mParser; InputStream urlStream = null; @Override final protected String doInBackground(String... params) { this.initParser(); try{ String userID = ""; String albumID = ""; String imageUrl = ""; String fileName = ""; String fileType = ""; String fromFacebook = ""; String fromeLead = ""; //String base64value = ""; String filePath = ""; String response = ""; EnumPictureServiceType serviceType = EnumPictureServiceType.fromString(params[0]); switch(serviceType){ case UPLOAD_PROFILE_IMAGE_URL: userID = params[1]; imageUrl = params[2]; fileName = params[3]; fileType = params[4]; fromFacebook = params[5]; fromeLead = params[6]; response = this.uploadProfileImageUrl(userID, albumID, imageUrl, fileName, fileType, fromFacebook, fromeLead); System.out.println("AsyncUploadImage TYPE_UPLOAD_PROFILE_IMAGE_URL response => " + response); return response; /* case UPLOAD_IMAGE_FILE: userID = params[1]; albumID = params[2]; filePath = params[3]; response = this.uploadImage(userID, albumID, filePath); return response; */ default: return ""; } }catch(IOException e){ //print error e.printStackTrace(); }catch(Exception e){ //print error e.printStackTrace(); } return ""; } public void doProgress(int value){ System.out.println("AsyncUploadImage current progress value => " + value); publishProgress(value); } private void initParser(){ mParser = Parser.getInstance(); } private String uploadProfileImageUrl(String userID, String albumID, String imageUrl, String fileName, String fileType, String fromFacebook, String fromLead) throws IOException { String url = Constant.URL_CLIENT_SERVER; HashMap<String, String> params = new HashMap<String, String>(); params.put(Constant.URL_POST_PARAMETER_TAG_USER_ID, userID); params.put(Constant.URL_POST_PARAMETER_TAG_ALBUM_ID, albumID); params.put(Constant.URL_POST_PARAMETER_TAG_URL, imageUrl); // http://... params.put(Constant.URL_POST_PARAMETER_TAG_FILE_NAME, fileName); //xxx.ext params.put(Constant.URL_POST_PARAMETER_TAG_FILE_TYPE, fileType); //jpg, png etc params.put(Constant.URL_POST_PARAMETER_TAG_FROM_FACEBOOK, fromFacebook); // true or false params.put(Constant.URL_POST_PARAMETER_TAG_FROM_LEAD, fromLead); // true or false this.urlStream = WebConnector.downloadUrl(url, Constant.TYPE_UPLOAD_PROFILE_IMAGE_URL, params); return WebConnector.convertStreamToString(this.urlStream); } private String uploadImageBase64(String userID, String albumID, String base64value) throws IOException { String url = Constant.URL_CLIENT_SERVER; HashMap<String, String> params = new HashMap<String, String>(); //params.put(Constant.URL_POST_PARAMETER_TAG_USER_ID, userID); //params.put(Constant.URL_POST_PARAMETER_TAG_ALBUM_ID, albumID); //params.put(Constant.URL_POST_PARAMETER_TAG_BASE_64, base64value); //this.urlStream = WebConnector.downloadUrl(url, Constant.TYPE_UPLOAD_IMAGE, params); //return WebConnector.convertStreamToString(this.urlStream); return ""; } /* private String uploadImage(String userID, String albumID, String filePath) throws IOException { String url = Constant.URL_CLIENT_SERVER; //HashMap<String, String> params = new HashMap<String, String>(); String response = WebConnector.uploadFile(Constant.TYPE_UPLOAD_IMAGE, url, userID, albumID, filePath, EnumFileType.IMAGE); return response; } */ }
mit
ONSdigital/ras-frontstage
tests/integration/test_sign_in.py
14770
import os import unittest import requests_mock from config import TestingConfig from frontstage import app, create_app_object from frontstage.common.utilities import obfuscate_email from frontstage.controllers.party_controller import ( notify_party_and_respondent_account_locked, ) from frontstage.exceptions.exceptions import ApiError from tests.integration.mocked_services import ( message_count, party, token, url_auth_token, url_banner_api, url_get_conversation_count, url_get_respondent_email, url_notify_party_and_respondent_account_locked, ) respondent_party_id = "cd592e0f-8d07-407b-b75d-e01fbdae8233" encoded_jwt_token = ( "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZWZyZXNoX3Rva2VuIjoiNmY5NjM0ZGEtYTI3ZS00ZDk3LWJhZjktNjN" "jOGRjY2IyN2M2IiwiYWNjZXNzX3Rva2VuIjoiMjUwMDM4YzUtM2QxOS00OGVkLThlZWMtODFmNTQyMDRjNDE1Iiwic2NvcGU" "iOlsiIl0sImV4cGlyZXNfYXQiOjE4OTM0NTk2NjEuMCwidXNlcm5hbWUiOiJ0ZXN0dXNlckBlbWFpbC5jb20iLCJyb2xlIjo" "icmVzcG9uZGVudCIsInBhcnR5X2lkIjoiZGIwMzZmZDctY2UxNy00MGMyLWE4ZmMtOTMyZTdjMjI4Mzk3In0.hh9sFpiPA-O" "8kugpDi3_GSDnxWh5rz2e5GQuBx7kmLM" ) url_resend_verification_email = ( f"{TestingConfig.PARTY_URL}/party-api/v1/resend-verification-email" f"/{respondent_party_id}" ) url_resend_verification_expired_token = ( f"{TestingConfig.PARTY_URL}/party-api/v1" f"/resend-verification-email-expired-token/{token}" ) get_respondent_by_id_url = f"{TestingConfig.PARTY_URL}/party-api/v1/respondents/id/{respondent_party_id}" class TestSignIn(unittest.TestCase): """Test case for application endpoints and functionality""" def setUp(self): self.app = app.test_client() self.auth_response = {} self.sign_in_form = {"username": "testuser@email.com", "password": "password"} self.auth_error = {"detail": "Unauthorized user credentials"} os.environ["APP_SETTINGS"] = "TestingConfig" @requests_mock.mock() def test_view_sign_in(self, mock_request): mock_request.get(url_banner_api, status_code=404) response = self.app.get("/sign-in/", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Sign in".encode() in response.data) self.assertTrue("New to this service?".encode() in response.data) @requests_mock.mock() def test_view_sign_in_from_redirect(self, mock_request): mock_request.get(url_banner_api, status_code=404) response = self.app.get("/", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Sign in".encode() in response.data) self.assertTrue("New to this service?".encode() in response.data) @requests_mock.mock() def test_view_sign_in_account_activated(self, mock_request): mock_request.get(url_banner_api, status_code=404) response = self.app.get("/sign-in?account_activated=True", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Sign in".encode() in response.data) self.assertTrue("You've activated your account".encode() in response.data) @requests_mock.mock() def test_sign_in_no_username(self, mock_request): mock_request.get(url_banner_api, status_code=404) del self.sign_in_form["username"] response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Email Address is required".encode() in response.data) @requests_mock.mock() def test_sign_in_invalid_username(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.sign_in_form["username"] = "aaa" response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Invalid email address".encode() in response.data) @requests_mock.mock() def test_sign_in_no_password(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.sign_in_form["username"] = "testuser@email.com" del self.sign_in_form["password"] response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Password is required".encode() in response.data) @requests_mock.mock() def test_sign_in_success(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.get(url_get_respondent_email, json=party) mock_request.post(url_auth_token, status_code=200, json=self.auth_response) mock_request.get(url_get_conversation_count, json=message_count) response = self.app.post("/sign-in/", data=self.sign_in_form) self.assertEqual(response.status_code, 302) self.assertTrue("/surveys/".encode() in response.data) @requests_mock.mock() def test_sign_in_success_redirect_to_url(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.get(url_get_respondent_email, json=party) mock_request.post(url_auth_token, status_code=200, json=self.auth_response) mock_request.get(url_get_conversation_count, json=message_count) response = self.app.post( "/sign-in/", data=self.sign_in_form, query_string={"next": "http://localhost:8082/secure-message/threads"} ) self.assertEqual(response.status_code, 302) self.assertTrue("/secure-message/threads".encode() in response.data) @requests_mock.mock() def test_sign_in_expired_redirects_to_login_page(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.get(url_get_respondent_email, json=party) mock_request.post(url_auth_token, status_code=200) self.app.get("/sign-in/", data=self.sign_in_form) response = self.app.get("/surveys/todo", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("To help protect your information we have signed you out".encode() in response.data) self.assertIn(b"Sign in", response.data) @requests_mock.mock() def test_sign_in_auth_fail(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.get(url_get_respondent_email, json=party) mock_request.post(url_auth_token, status_code=500) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 500) self.assertTrue("An error has occurred".encode() in response.data) @requests_mock.mock() def test_sign_in_party_fail(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.get(url_get_respondent_email, status_code=500) mock_request.post(url_auth_token, status_code=200, json=self.auth_response) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 500) self.assertTrue("An error has occurred".encode() in response.data) @requests_mock.mock() def test_sign_in_party_404(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.post(url_auth_token, status_code=204) mock_request.get(url_get_respondent_email, status_code=404) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertTrue("Incorrect email or password".encode() in response.data) @requests_mock.mock() def test_sign_in_unauthorised_auth_credentials(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.post(url_auth_token, status_code=401, json=self.auth_error) mock_request.get(url_get_respondent_email, json=party) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Incorrect email or password".encode() in response.data) @requests_mock.mock() def test_sign_in_unverified_account(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.auth_error["detail"] = "User account not verified" mock_request.post(url_auth_token, status_code=401, json=self.auth_error) mock_request.get(url_get_respondent_email, json=party) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Please follow the link the email to confirm your email address".encode() in response.data) self.assertTrue( '<a href="/sign-in/resend-verification/f956e8ae-6e0f-4414-b0cf-a07c1aa3e37b">'.encode() in response.data ) @requests_mock.mock() def test_sign_in_unknown_response(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.auth_error["detail"] = "wat" mock_request.post(url_auth_token, status_code=401, json=self.auth_error) mock_request.get(url_get_respondent_email, json=party) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Incorrect email or password".encode() in response.data) @requests_mock.mock() def test_logout(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.app.set_cookie("localhost", "authorization", encoded_jwt_token) response = self.app.get("/sign-in/logout", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Sign in".encode() in response.data) self.assertTrue("New to this service?".encode() in response.data) self.assertFalse("Sign out".encode() in response.data) @requests_mock.mock() def test_resend_verification_email(self, mock_request): mock_request.get(url_banner_api, status_code=404) urls = ["resend_verification", "resend-verification"] for url in urls: with self.subTest(url=url): mock_request.get(get_respondent_by_id_url, json=party) mock_request.post(url_resend_verification_email, status_code=200) response = self.app.get(f"/sign-in/{url}/{respondent_party_id}", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Check your email".encode() in response.data) @requests_mock.mock() def test_fail_resent_verification_email(self, mock_request): mock_request.get(url_banner_api, status_code=404) urls = ["resend_verification", "resend-verification"] for url in urls: with self.subTest(url=url): mock_request.post(url_resend_verification_email, status_code=500) response = self.app.get(f"sign-in/{url}/{respondent_party_id}", follow_redirects=True) self.assertEqual(response.status_code, 500) self.assertTrue("An error has occurred".encode() in response.data) @requests_mock.mock() def test_sign_in_account_locked(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.auth_error["detail"] = "User account locked" mock_request.post(url_auth_token, status_code=401, json=self.auth_error) mock_request.get(url_get_respondent_email, json=party) mock_request.put( url_notify_party_and_respondent_account_locked, json={ "respondent_id": "f956e8ae-6e0f-4414-b0cf-a07c1aa3e37b", "status_change": "SUSPENDED", "email_address": "test@test.com", }, ) response = self.app.post("/sign-in/", data=self.sign_in_form, follow_redirects=True) self.assertEqual(response.status_code, 200) @requests_mock.mock() def test_notify_account_error(self, mock_request): mock_request.get(url_banner_api, status_code=404) self.app = create_app_object() self.app.testing = True mock_request.put( url_notify_party_and_respondent_account_locked, json={ "respondent_id": "f956e8ae-6e0f-4414-b0cf-a07c1aa3e37b", "status_change": "SUSPENDED", "email_address": "test@test.com", }, status_code=500, ) with self.app.app_context(): with self.assertRaises(ApiError): notify_party_and_respondent_account_locked( respondent_id="f956e8ae-6e0f-4414-b0cf-a07c1aa3e37b", email_address="test@test.com" ) @requests_mock.mock() def test_resend_verification_email_using_expired_token(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.post(url_resend_verification_expired_token, status_code=200) response = self.app.get(f"sign-in/resend-verification-expired-token/{token}", follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertTrue("Check your email".encode() in response.data) @requests_mock.mock() def test_fail_resend_verification_email_using_expired_token(self, mock_request): mock_request.get(url_banner_api, status_code=404) mock_request.post(url_resend_verification_expired_token, status_code=500) response = self.app.get(f"sign-in/resend-verification-expired-token/{token}", follow_redirects=True) self.assertEqual(response.status_code, 500) self.assertTrue("An error has occurred".encode() in response.data) def test_obfuscate_email(self): """Tests the output of obfuscate email with both valid and invalid strings""" testAddresses = { "example@example.com": "e*****e@e*********m", "prefix@domain.co.uk": "p****x@d**********k", "first.name@place.gov.uk": "f********e@p**********k", "me+addition@gmail.com": "m*********n@g*******m", "a.b.c.someone@example.com": "a***********e@e*********m", "john.smith123456@londinium.ac.co.uk": "j**************6@l****************k", "me!?@example.com": "m**?@e*********m", "m@m.com": "m@m***m", "joe.bloggs": "j********s", "joe.bloggs@": "j********s", "@gmail.com": "@g*******m", } for test in testAddresses: self.assertEqual(obfuscate_email(test), testAddresses[test])
mit
Fedcomp/active_sms
lib/any_sms/configuration.rb
2337
# :nodoc: module AnySMS # @return [AnySMS::Configuration] object with configuration options def self.config @@config ||= Configuration.new end # Allows to configure AnySMS options and register backends def self.configure yield(config) end # resets AnySMS configuration to default def self.reset! @@config = nil end # Configuration object for AnySMS class Configuration # returns key of the default sms backend attr_reader :default_backend # returns list of registered sms backends attr_reader :backends def initialize register_backend :null_sender, AnySMS::Backend::NullSender self.default_backend = :null_sender end # Specify default sms backend. It must be registered. # # @param value [Symbol] Backend key which will be used as default def default_backend=(value) raise ArgumentError, "default_backend must be a symbol!" unless value.is_a? Symbol unless @backends.keys.include? value raise ArgumentError, "Unregistered backend cannot be set as default!" end @default_backend = value end # Register sms provider backend # # @param key [Symbol] Key for acessing backend in any part of AnySMS # @param classname [Class] Real class implementation of sms backend # @param params [Hash] # Optional params for backend. Useful for passing tokens and options def register_backend(key, classname, params = {}) raise ArgumentError, "backend key must be a symbol!" unless key.is_a? Symbol unless classname.class == Class raise ArgumentError, "backend class must be class (not instance or string)" end unless classname.method_defined? :send_sms raise ArgumentError, "backend must provide method send_sms" end define_backend(key, classname, params) end # Removes registered sms backend # # @param key [Symbol] Key of already registered backend def remove_backend(key) if key == default_backend raise ArgumentError, "Removing default_backend is prohibited" end @backends.delete key true end private def define_backend(key, classname, params) @backends ||= {} @backends[key] = { class: classname, params: params } end end end
mit
tyh24647/Miami1984
Assets/UFPS/Base/Scripts/Core/Editor/vp_ShooterEditor.cs
8874
///////////////////////////////////////////////////////////////////////////////// // // vp_ShooterEditor.cs // © Opsive. All Rights Reserved. // https://twitter.com/Opsive // http://www.opsive.com // // description: custom inspector for the vp_Shooter class // ///////////////////////////////////////////////////////////////////////////////// using UnityEngine; using UnityEditor; [CustomEditor(typeof(vp_Shooter))] public class vp_ShooterEditor : Editor { // target component public vp_Shooter m_Component = null; // foldouts public static bool m_ProjectileFoldout; public static bool m_MuzzleFlashFoldout; public static bool m_ShellFoldout; public static bool m_AmmoFoldout; public static bool m_SoundFoldout; public static bool m_StateFoldout; public static bool m_PresetFoldout = true; private bool m_MuzzleFlashVisible = false; // display the muzzle flash in the editor? private static vp_ComponentPersister m_Persister = null; /// <summary> /// hooks up the object to the inspector target /// </summary> public virtual void OnEnable() { m_Component = (vp_Shooter)target; if (m_Persister == null) m_Persister = new vp_ComponentPersister(); m_Persister.Component = m_Component; m_Persister.IsActive = true; if (m_Component.DefaultState == null) m_Component.RefreshDefaultState(); } /// <summary> /// disables the persister and removes its reference /// </summary> public virtual void OnDestroy() { if (m_Persister != null) m_Persister.IsActive = false; } /// <summary> /// /// </summary> public override void OnInspectorGUI() { GUI.color = Color.white; string objectInfo = m_Component.gameObject.name; if (vp_Utility.IsActive(m_Component.gameObject)) GUI.enabled = true; else { GUI.enabled = false; objectInfo += " (INACTIVE)"; } if (!vp_Utility.IsActive(m_Component.gameObject)) { GUI.enabled = true; return; } if (Application.isPlaying || m_Component.DefaultState.TextAsset == null) { DoProjectileFoldout(); DoMuzzleFlashFoldout(); DoShellFoldout(); DoSoundFoldout(); } else vp_PresetEditorGUIUtility.DefaultStateOverrideMessage(); // state m_StateFoldout = vp_PresetEditorGUIUtility.StateFoldout(m_StateFoldout, m_Component, m_Component.States, m_Persister); // preset m_PresetFoldout = vp_PresetEditorGUIUtility.PresetFoldout(m_PresetFoldout, m_Component); // update default state and persist in order not to loose inspector tweaks // due to state switches during runtime - UNLESS a runtime state button has // been pressed (in which case user wants to toggle states as opposed to // reset / alter them) if (GUI.changed && (!vp_PresetEditorGUIUtility.RunTimeStateButtonTarget == m_Component)) { EditorUtility.SetDirty(target); if (Application.isPlaying) m_Component.RefreshDefaultState(); if (m_Component.Persist) m_Persister.Persist(); m_Component.Refresh(); } } /// <summary> /// /// </summary> public virtual void DoProjectileFoldout() { m_ProjectileFoldout = EditorGUILayout.Foldout(m_ProjectileFoldout, "Projectile"); if (m_ProjectileFoldout) { m_Component.ProjectileFiringRate = Mathf.Max(0.0f, EditorGUILayout.FloatField("Firing Rate", m_Component.ProjectileFiringRate)); if (m_Component.ProjectileFiringRate == 0.0f) { GUI.enabled = false; } GUI.enabled = true; m_Component.ProjectilePrefab = (GameObject)EditorGUILayout.ObjectField("Prefab", m_Component.ProjectilePrefab, typeof(GameObject), false); GUI.enabled = false; GUILayout.Label("Prefab should be a gameobject with a projectile\nlogic script added to it (such as vp_HitscanBullet).", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; m_Component.ProjectileScale = EditorGUILayout.Slider("Scale", m_Component.ProjectileScale, 0, 2); m_Component.ProjectileCount = EditorGUILayout.IntField("Count", m_Component.ProjectileCount); m_Component.ProjectileSpread = EditorGUILayout.Slider("Spread", m_Component.ProjectileSpread, 0, 360); m_Component.ProjectileSpawnDelay = Mathf.Abs(EditorGUILayout.FloatField("Spawn Delay", m_Component.ProjectileSpawnDelay)); m_Component.ProjectileSourceIsRoot = EditorGUILayout.Toggle("Root Obj. is Source", m_Component.ProjectileSourceIsRoot); m_Component.FireMessage = EditorGUILayout.TextField("Fire Message", m_Component.FireMessage); GUI.enabled = false; GUILayout.Label("(Optional) If this is set, a regular Unity message will be\nsent to the root gameobject every time the shooter fires.", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; vp_EditorGUIUtility.Separator(); } } /// <summary> /// /// </summary> public virtual void DoMuzzleFlashFoldout() { m_MuzzleFlashFoldout = EditorGUILayout.Foldout(m_MuzzleFlashFoldout, "Muzzle Flash"); if (m_MuzzleFlashFoldout) { m_Component.MuzzleFlashPrefab = (GameObject)EditorGUILayout.ObjectField("Prefab", m_Component.MuzzleFlashPrefab, typeof(GameObject), false); GUI.enabled = false; GUILayout.Label("Prefab should be a mesh with a Particles/Additive\nshader and a vp_MuzzleFlash script added to it.", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; Vector3 currentPosition = m_Component.MuzzleFlashPosition; m_Component.MuzzleFlashPosition = EditorGUILayout.Vector3Field("Position", m_Component.MuzzleFlashPosition); Vector3 currentScale = m_Component.MuzzleFlashScale; m_Component.MuzzleFlashScale = EditorGUILayout.Vector3Field("Scale", m_Component.MuzzleFlashScale); m_Component.MuzzleFlashFadeSpeed = EditorGUILayout.Slider("Fade Speed", m_Component.MuzzleFlashFadeSpeed, 0.001f, 0.2f); m_Component.MuzzleFlashDelay = Mathf.Abs(EditorGUILayout.FloatField("MuzzleFlash Delay", m_Component.MuzzleFlashDelay)); if (!Application.isPlaying) GUI.enabled = false; bool currentMuzzleFlashVisible = m_MuzzleFlashVisible; m_MuzzleFlashVisible = EditorGUILayout.Toggle("Show Muzzle Fl.", m_MuzzleFlashVisible); if (Application.isPlaying) { if (m_Component.MuzzleFlashPosition != currentPosition || m_Component.MuzzleFlashScale != currentScale) m_MuzzleFlashVisible = true; vp_MuzzleFlash mf = (vp_MuzzleFlash)m_Component.MuzzleFlash.GetComponent("vp_MuzzleFlash"); if (mf != null) mf.ForceShow = currentMuzzleFlashVisible; GUI.enabled = false; GUILayout.Label("Set Muzzle Flash Z to about 0.5 to bring it into view.", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; } else GUILayout.Label("Muzzle Flash can be shown when the game is playing.", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; vp_EditorGUIUtility.Separator(); } } /// <summary> /// /// </summary> public virtual void DoShellFoldout() { m_ShellFoldout = EditorGUILayout.Foldout(m_ShellFoldout, "Shell"); if (m_ShellFoldout) { m_Component.ShellPrefab = (GameObject)EditorGUILayout.ObjectField("Prefab", m_Component.ShellPrefab, typeof(GameObject), false); GUI.enabled = false; GUILayout.Label("Prefab should be a mesh with a collider, a rigidbody\nand a vp_Shell script added to it.", vp_EditorGUIUtility.NoteStyle); GUI.enabled = true; m_Component.ShellScale = EditorGUILayout.Slider("Scale", m_Component.ShellScale, 0, 2); m_Component.ShellEjectPosition = EditorGUILayout.Vector3Field("Eject Position", m_Component.ShellEjectPosition); m_Component.ShellEjectDirection = EditorGUILayout.Vector3Field("Eject Direction", m_Component.ShellEjectDirection); m_Component.ShellEjectVelocity = EditorGUILayout.Slider("Eject Velocity", m_Component.ShellEjectVelocity, 0, 0.5f); m_Component.ShellEjectSpin = EditorGUILayout.Slider("Eject Spin", m_Component.ShellEjectSpin, 0, 1.0f); m_Component.ShellEjectDelay = Mathf.Abs(EditorGUILayout.FloatField("Eject Delay", m_Component.ShellEjectDelay)); vp_EditorGUIUtility.Separator(); } } /// <summary> /// /// </summary> public virtual void DoSoundFoldout() { m_SoundFoldout = EditorGUILayout.Foldout(m_SoundFoldout, "Sound"); if (m_SoundFoldout) { m_Component.SoundFire = (AudioClip)EditorGUILayout.ObjectField("Fire", m_Component.SoundFire, typeof(AudioClip), false); m_Component.SoundFirePitch = EditorGUILayout.Vector2Field("Fire Pitch (Min:Max)", m_Component.SoundFirePitch); EditorGUILayout.MinMaxSlider(ref m_Component.SoundFirePitch.x, ref m_Component.SoundFirePitch.y, 0.5f, 1.5f); m_Component.SoundFireDelay = Mathf.Abs(EditorGUILayout.FloatField("Fire Sound Delay", m_Component.SoundFireDelay)); vp_EditorGUIUtility.Separator(); } } }
mit
cruncher/sparky
test/select.test.js
4244
import { Fn, noop, test as group, Observer } from '../../fn/module.js'; import Sparky from '../module.js'; group('select > option', function(test, log, fixture) { var select = fixture.children[0]; test("Array scope", function(equals, done) { const model = { country: 'UK' }; Sparky(select).push(model); requestAnimationFrame(function functionName() { equals(true, !!select); equals(2, select.children.length); equals('UK', select.value); Observer(model).country = 'CH'; requestAnimationFrame(function functionName() { equals('CH', select.value); Observer(model).country = '--'; requestAnimationFrame(function functionName() { equals('', select.value); Observer(model).country = 'UK'; requestAnimationFrame(function functionName() { equals('UK', select.value); done(); }); }); }); }); }, 6); }, function() {/* <select :value="{[country]}" name="country"> <option value="UK">United Kingdom</option> <option value="CH">Switzerland</option> </select> */}); /* group('select > option|each', function(test, log, fixture) { var node = fixture.children[0]; var array = Observer([ { key: '0', value: 0 }, { key: '1', value: 1 }, { key: '2', value: 2 } ]); Sparky.fn['array-scope'] = function(node, stream) { return Fn.of(array); }; var sparky = Sparky(node); test("Array scope", function(equals, done) { requestAnimationFrame(function functionName() { equals(4, node.children.length, 'Wrong number of child <option>s.'); equals('Infinity', node.children[node.children.length - 1].getAttribute('value'), 'Order of child <option>s is wrong.'); done(); }); }, 2); test("Array scope mutation", function(equals, done) { node.value = '2'; array.length = 0; array.push( { key: '2', value: 2 }, { key: '3', value: 3 }, { key: '4', value: 4 } ); requestAnimationFrame(function() { equals('2', node.value, 'Select should keep its value when items in scope replaced with items containing same value'); equals('Infinity', node.children[node.children.length - 1].getAttribute('value'), 'Order of child <option>s is wrong.'); done(); }); }, 2); }, function() {/* <select sparky-fn="array-scope" class="{[length|add:1|prepend:'length-']}" id="test-select" name="name"> <option sparky-fn="each" value="{[key]}">{[value]}</option> <option value="Infinity">Infinity</option> </select> *//*}); /* group('select > option|each', function(test, log, fixture) { var node = fixture.children[0]; var scope = Observer({ value: '1', options: [ { key: '0', value: 0 }, { key: '1', value: 1 }, { key: '2', value: 2 } ] }); Sparky.fn['array-scope-2'] = function(node, stream) { return Fn.of(scope); }; Sparky(node); test("Array scope", function(equals, done) { requestAnimationFrame(function functionName() { equals(4, node.children.length); equals('1', node.value); equals('1', scope.value); equals('Infinity', node.children[node.children.length - 1].getAttribute('value'), 'Order of child <option>s is wrong.'); done(); }); }, 4); }, function() {/* <select sparky-fn="array-scope-2" :value="{[value]}" id="test-select-2" name="name"> <option sparky-fn="get:options each" value="{[key]}">{[value]}</option> <option value="Infinity">Infinity</option> </select> *//*}); */ group('select > async options', function(test, log, fixture) { var node = fixture.children[0]; test("Array scope", function(equals, done) { const model = { country: 'GB' }; Sparky(node).push(model); requestAnimationFrame(function functionName() { var select = fixture.querySelector('select'); equals(true, !!select); // Wait countries.json to import setTimeout(function() { equals(3, select.children.length); equals('GB', select.value); done(); }, 500); }); }, 3); }, function() {/* <form> <template src="#address-editor"></template> </form> <template id="address-editor"> <label class="country-select-button select-button button"> <select :value="{[country]}" name="country"> <option fn="fetch:json/countries.json each" value="{[code]}">{[value]}</option> </select> </label> </template> */});
mit
heartshare/cmf-1
based/vendor/bower/jquery/src/sizzle/test/jquery.js
367817
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function (window, undefined) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function (selector, context) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init(selector, context, rootjQuery); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function (all, letter) { return letter.toUpperCase(); }, // The ready event handler completed = function (event) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if (document.addEventListener || event.type === "load" || document.readyState === "complete") { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function () { if (document.addEventListener) { document.removeEventListener("DOMContentLoaded", completed, false); window.removeEventListener("load", completed, false); } else { document.detachEvent("onreadystatechange", completed); window.detachEvent("onload", completed); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function (selector, context, rootjQuery) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if (!selector) { return this; } // Handle HTML strings if (typeof selector === "string") { if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec(selector); } // Match html or make sure no context is specified for #id if (match && (match[1] || !context)) { // HANDLE: $(html) -> $(array) if (match[1]) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge(this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true )); // HANDLE: $(html, props) if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) { for (match in context) { // Properties of context are called as methods if possible if (jQuery.isFunction(this[ match ])) { this[ match ](context[ match ]); // ...and otherwise set as attributes } else { this.attr(match, context[ match ]); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById(match[2]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if (elem && elem.parentNode) { // Handle the case where IE and Opera return items // by name instead of ID if (elem.id !== match[2]) { return rootjQuery.find(selector); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if (!context || context.jquery) { return ( context || rootjQuery ).find(selector); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor(context).find(selector); } // HANDLE: $(DOMElement) } else if (selector.nodeType) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if (jQuery.isFunction(selector)) { return rootjQuery.ready(selector); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray(selector, this); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function () { return this.length; }, toArray: function () { return core_slice.call(this); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function (num) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function (elems) { // Build a new jQuery matched element set var ret = jQuery.merge(this.constructor(), elems); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function (callback, args) { return jQuery.each(this, callback, args); }, ready: function (fn) { // Add the callback jQuery.ready.promise().done(fn); return this; }, slice: function () { return this.pushStack(core_slice.apply(this, arguments)); }, first: function () { return this.eq(0); }, last: function () { return this.eq(-1); }, eq: function (i) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack(j >= 0 && j < len ? [ this[j] ] : []); }, map: function (callback) { return this.pushStack(jQuery.map(this, function (elem, i) { return callback.call(elem, i, elem); })); }, end: function () { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function () { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !jQuery.isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[ i ]) != null) { // Extend the base object for (name in options) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) )) { if (copyIsArray) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function (deep) { if (window.$ === jQuery) { window.$ = _$; } if (deep && window.jQuery === jQuery) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function (hold) { if (hold) { jQuery.readyWait++; } else { jQuery.ready(true); } }, // Handle when the DOM is ready ready: function (wait) { // Abort if there are pending holds or we're already ready if (wait === true ? --jQuery.readyWait : jQuery.isReady) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if (!document.body) { return setTimeout(jQuery.ready); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if (wait !== true && --jQuery.readyWait > 0) { return; } // If there are functions bound, to execute readyList.resolveWith(document, [ jQuery ]); // Trigger any bound ready events if (jQuery.fn.trigger) { jQuery(document).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function (obj) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function (obj) { return jQuery.type(obj) === "array"; }, isWindow: function (obj) { return obj != null && obj == obj.window; }, isNumeric: function (obj) { return !isNaN(parseFloat(obj)) && isFinite(obj); }, type: function (obj) { if (obj == null) { return String(obj); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function (obj) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) { return false; } try { // Not own constructor property must be Object if (obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false; } } catch (e) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { } return key === undefined || core_hasOwn.call(obj, key); }, isEmptyObject: function (obj) { var name; for (name in obj) { return false; } return true; }, error: function (msg) { throw new Error(msg); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function (data, context, keepScripts) { if (!data || typeof data !== "string") { return null; } if (typeof context === "boolean") { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec(data), scripts = !keepScripts && []; // Single tag if (parsed) { return [ context.createElement(parsed[1]) ]; } parsed = jQuery.buildFragment([ data ], context, scripts); if (scripts) { jQuery(scripts).remove(); } return jQuery.merge([], parsed.childNodes); }, parseJSON: function (data) { // Attempt to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { return window.JSON.parse(data); } if (data === null) { return data; } if (typeof data === "string") { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim(data); if (data) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if (rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, ""))) { return ( new Function("return " + data) )(); } } } jQuery.error("Invalid JSON: " + data); }, // Cross-browser xml parsing parseXML: function (data) { var xml, tmp; if (!data || typeof data !== "string") { return null; } try { if (window.DOMParser) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } else { // IE xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = "false"; xml.loadXML(data); } } catch (e) { xml = undefined; } if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { jQuery.error("Invalid XML: " + data); } return xml; }, noop: function () { }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function (data) { if (data && jQuery.trim(data)) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function (data) { window[ "eval" ].call(window, data); } )(data); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function (string) { return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); }, nodeName: function (elem, name) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function (obj, callback, args) { var value, i = 0, length = obj.length, isArray = isArraylike(obj); if (args) { if (isArray) { for (; i < length; i++) { value = callback.apply(obj[ i ], args); if (value === false) { break; } } } else { for (i in obj) { value = callback.apply(obj[ i ], args); if (value === false) { break; } } } // A special, fast, case for the most common use of each } else { if (isArray) { for (; i < length; i++) { value = callback.call(obj[ i ], i, obj[ i ]); if (value === false) { break; } } } else { for (i in obj) { value = callback.call(obj[ i ], i, obj[ i ]); if (value === false) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function (text) { return text == null ? "" : core_trim.call(text); } : // Otherwise use our own trimming functionality function (text) { return text == null ? "" : ( text + "" ).replace(rtrim, ""); }, // results is for internal usage only makeArray: function (arr, results) { var ret = results || []; if (arr != null) { if (isArraylike(Object(arr))) { jQuery.merge(ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call(ret, arr); } } return ret; }, inArray: function (elem, arr, i) { var len; if (arr) { if (core_indexOf) { return core_indexOf.call(arr, elem, i); } len = arr.length; i = i ? i < 0 ? Math.max(0, len + i) : i : 0; for (; i < len; i++) { // Skip accessing in sparse arrays if (i in arr && arr[ i ] === elem) { return i; } } } return -1; }, merge: function (first, second) { var l = second.length, i = first.length, j = 0; if (typeof l === "number") { for (; j < l; j++) { first[ i++ ] = second[ j ]; } } else { while (second[j] !== undefined) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function (elems, callback, inv) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for (; i < length; i++) { retVal = !!callback(elems[ i ], i); if (inv !== retVal) { ret.push(elems[ i ]); } } return ret; }, // arg is for internal usage only map: function (elems, callback, arg) { var value, i = 0, length = elems.length, isArray = isArraylike(elems), ret = []; // Go through the array, translating each of the items to their if (isArray) { for (; i < length; i++) { value = callback(elems[ i ], i, arg); if (value != null) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for (i in elems) { value = callback(elems[ i ], i, arg); if (value != null) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply([], ret); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function (fn, context) { var args, proxy, tmp; if (typeof context === "string") { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if (!jQuery.isFunction(fn)) { return undefined; } // Simulated bind args = core_slice.call(arguments, 2); proxy = function () { return fn.apply(context || this, args.concat(core_slice.call(arguments))); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function (elems, fn, key, value, chainable, emptyGet, raw) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if (jQuery.type(key) === "object") { chainable = true; for (i in key) { jQuery.access(elems, fn, i, key[i], true, emptyGet, raw); } // Sets one value } else if (value !== undefined) { chainable = true; if (!jQuery.isFunction(value)) { raw = true; } if (bulk) { // Bulk operations run against the entire set if (raw) { fn.call(elems, value); fn = null; // ...except when executing function values } else { bulk = fn; fn = function (elem, key, value) { return bulk.call(jQuery(elem), value); }; } } if (fn) { for (; i < length; i++) { fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key))); } } } return chainable ? elems : // Gets bulk ? fn.call(elems) : length ? fn(elems[0], key) : emptyGet; }, now: function () { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function (obj) { if (!readyList) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if (document.readyState === "complete") { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout(jQuery.ready); // Standards-based browsers support DOMContentLoaded } else if (document.addEventListener) { // Use the handy event callback document.addEventListener("DOMContentLoaded", completed, false); // A fallback to window.onload, that will always work window.addEventListener("load", completed, false); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent("onreadystatechange", completed); // A fallback to window.onload, that will always work window.attachEvent("onload", completed); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch (e) { } if (top && top.doScroll) { (function doScrollCheck() { if (!jQuery.isReady) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch (e) { return setTimeout(doScrollCheck, 50); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise(obj); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike(obj) { var length = obj.length, type = jQuery.type(obj); if (jQuery.isWindow(obj)) { return false; } if (obj.nodeType === 1 && length) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions(options) { var object = optionsCache[ options ] = {}; jQuery.each(options.match(core_rnotwhite) || [], function (_, flag) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function (options) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions(options) ) : jQuery.extend({}, options); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function (data) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for (; list && firingIndex < firingLength; firingIndex++) { if (list[ firingIndex ].apply(data[ 0 ], data[ 1 ]) === false && options.stopOnFalse) { memory = false; // To prevent further calls using add break; } } firing = false; if (list) { if (stack) { if (stack.length) { fire(stack.shift()); } } else if (memory) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function () { if (list) { // First, we save the current length var start = list.length; (function add(args) { jQuery.each(args, function (_, arg) { var type = jQuery.type(arg); if (type === "function") { if (!options.unique || !self.has(arg)) { list.push(arg); } } else if (arg && arg.length && type !== "string") { // Inspect recursively add(arg); } }); })(arguments); // Do we need to add the callbacks to the // current firing batch? if (firing) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if (memory) { firingStart = start; fire(memory); } } return this; }, // Remove a callback from the list remove: function () { if (list) { jQuery.each(arguments, function (_, arg) { var index; while (( index = jQuery.inArray(arg, list, index) ) > -1) { list.splice(index, 1); // Handle firing indexes if (firing) { if (index <= firingLength) { firingLength--; } if (index <= firingIndex) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function (fn) { return fn ? jQuery.inArray(fn, list) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function () { list = []; return this; }, // Have the list do nothing anymore disable: function () { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function () { return !list; }, // Lock the list in its current state lock: function () { stack = undefined; if (!memory) { self.disable(); } return this; }, // Is it locked? locked: function () { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function (context, args) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if (list && ( !fired || stack )) { if (firing) { stack.push(args); } else { fire(args); } } return this; }, // Call all the callbacks with the given arguments fire: function () { self.fireWith(this, arguments); return this; }, // To know if the callbacks have already been called at least once fired: function () { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function (func) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function () { return state; }, always: function () { deferred.done(arguments).fail(arguments); return this; }, then: function (/* fnDone, fnFail, fnProgress */) { var fns = arguments; return jQuery.Deferred(function (newDefer) { jQuery.each(tuples, function (i, tuple) { var action = tuple[ 0 ], fn = jQuery.isFunction(fns[ i ]) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function () { var returned = fn && fn.apply(this, arguments); if (returned && jQuery.isFunction(returned.promise)) { returned.promise() .done(newDefer.resolve) .fail(newDefer.reject) .progress(newDefer.notify); } else { newDefer[ action + "With" ](this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function (obj) { return obj != null ? jQuery.extend(obj, promise) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each(tuples, function (i, tuple) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if (stateString) { list.add(function () { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function () { deferred[ tuple[0] + "With" ](this === deferred ? promise : this, arguments); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise(deferred); // Call given func if any if (func) { func.call(deferred, deferred); } // All done! return deferred; }, // Deferred helper when: function (subordinate /* , ..., subordinateN */) { var i = 0, resolveValues = core_slice.call(arguments), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction(subordinate.promise) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function (i, contexts, values) { return function (value) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call(arguments) : value; if (values === progressValues) { deferred.notifyWith(contexts, values); } else if (!( --remaining )) { deferred.resolveWith(contexts, values); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if (length > 1) { progressValues = new Array(length); progressContexts = new Array(length); resolveContexts = new Array(length); for (; i < length; i++) { if (resolveValues[ i ] && jQuery.isFunction(resolveValues[ i ].promise)) { resolveValues[ i ].promise() .done(updateFunc(i, resolveContexts, resolveValues)) .fail(deferred.reject) .progress(updateFunc(i, progressContexts, progressValues)); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if (!remaining) { deferred.resolveWith(resolveContexts, resolveValues); } return deferred.promise(); } }); jQuery.support = (function () { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if (!all || !a || !all.length) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild(document.createElement("option")); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test(a.getAttribute("style")), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test(a.style.opacity), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode(true).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch (e) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute("value", ""); support.input = input.getAttribute("value") === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute("checked", "t"); input.setAttribute("name", "t"); fragment = document.createDocumentFragment(); fragment.appendChild(input); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if (div.attachEvent) { div.attachEvent("onclick", function () { support.noCloneEvent = false; }); div.cloneNode(true).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for (i in { submit: true, change: true, focusin: true }) { div.setAttribute(eventName = "on" + i, "t"); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode(true).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function () { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if (!body) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild(container).appendChild(div); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if (window.getComputedStyle) { support.pixelPosition = ( window.getComputedStyle(div, null) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle(div, null) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild(document.createElement("div")); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat(( window.getComputedStyle(marginDiv, null) || {} ).marginRight); } if (typeof div.style.zoom !== core_strundefined) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if (support.inlineBlockNeedsLayout) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild(container); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData(elem, name, data, pvt /* Internal Use Only */) { if (!jQuery.acceptData(elem)) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ((!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined) { return; } if (!id) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if (isNode) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if (!cache[ id ]) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if (!isNode) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if (typeof name === "object" || typeof name === "function") { if (pvt) { cache[ id ] = jQuery.extend(cache[ id ], name); } else { cache[ id ].data = jQuery.extend(cache[ id ].data, name); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if (!pvt) { if (!thisCache.data) { thisCache.data = {}; } thisCache = thisCache.data; } if (data !== undefined) { thisCache[ jQuery.camelCase(name) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if (getByName) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if (ret == null) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase(name) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData(elem, name, pvt) { if (!jQuery.acceptData(elem)) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if (!cache[ id ]) { return; } if (name) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if (thisCache) { // Support array or space separated string names for data keys if (!jQuery.isArray(name)) { // try the string as a key before any manipulation if (name in thisCache) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase(name); if (name in thisCache) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat(jQuery.map(name, jQuery.camelCase)); } for (i = 0, l = name.length; i < l; i++) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if (!( pvt ? isEmptyDataObject : jQuery.isEmptyObject )(thisCache)) { return; } } } // See jQuery.data for more information if (!pvt) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if (!isEmptyDataObject(cache[ id ])) { return; } } // Destroy the cache if (isNode) { jQuery.cleanData([ elem ], true); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if (jQuery.support.deleteExpando || cache != cache.window) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace(/\D/g, ""), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function (elem) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject(elem); }, data: function (elem, name, data) { return internalData(elem, name, data); }, removeData: function (elem, name) { return internalRemoveData(elem, name); }, // For internal use only. _data: function (elem, name, data) { return internalData(elem, name, data, true); }, _removeData: function (elem, name) { return internalRemoveData(elem, name, true); }, // A method for determining if a DOM node can handle the data expando acceptData: function (elem) { // Do not set data on non-element because it will not be cleared (#8335). if (elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function (key, value) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if (key === undefined) { if (this.length) { data = jQuery.data(elem); if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) { attrs = elem.attributes; for (; i < attrs.length; i++) { name = attrs[i].name; if (!name.indexOf("data-")) { name = jQuery.camelCase(name.slice(5)); dataAttr(elem, name, data[ name ]); } } jQuery._data(elem, "parsedAttrs", true); } } return data; } // Sets multiple values if (typeof key === "object") { return this.each(function () { jQuery.data(this, key); }); } return jQuery.access(this, function (value) { if (value === undefined) { // Try to fetch any internally stored data first return elem ? dataAttr(elem, key, jQuery.data(elem, key)) : null; } this.each(function () { jQuery.data(this, key, value); }); }, null, value, arguments.length > 1, null, true); }, removeData: function (key) { return this.each(function () { jQuery.removeData(this, key); }); } }); function dataAttr(elem, key, data) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if (data === undefined && elem.nodeType === 1) { var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase(); data = elem.getAttribute(name); if (typeof data === "string") { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test(data) ? jQuery.parseJSON(data) : data; } catch (e) { } // Make sure we set the data so it isn't changed later jQuery.data(elem, key, data); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject(obj) { var name; for (name in obj) { // if the public data object is empty, the private is still empty if (name === "data" && jQuery.isEmptyObject(obj[name])) { continue; } if (name !== "toJSON") { return false; } } return true; } jQuery.extend({ queue: function (elem, type, data) { var queue; if (elem) { type = ( type || "fx" ) + "queue"; queue = jQuery._data(elem, type); // Speed up dequeue by getting out quickly if this is just a lookup if (data) { if (!queue || jQuery.isArray(data)) { queue = jQuery._data(elem, type, jQuery.makeArray(data)); } else { queue.push(data); } } return queue || []; } }, dequeue: function (elem, type) { type = type || "fx"; var queue = jQuery.queue(elem, type), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks(elem, type), next = function () { jQuery.dequeue(elem, type); }; // If the fx queue is dequeued, always remove the progress sentinel if (fn === "inprogress") { fn = queue.shift(); startLength--; } hooks.cur = fn; if (fn) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if (type === "fx") { queue.unshift("inprogress"); } // clear up the last queue stop function delete hooks.stop; fn.call(elem, next, hooks); } if (!startLength && hooks) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function (elem, type) { var key = type + "queueHooks"; return jQuery._data(elem, key) || jQuery._data(elem, key, { empty: jQuery.Callbacks("once memory").add(function () { jQuery._removeData(elem, type + "queue"); jQuery._removeData(elem, key); }) }); } }); jQuery.fn.extend({ queue: function (type, data) { var setter = 2; if (typeof type !== "string") { data = type; type = "fx"; setter--; } if (arguments.length < setter) { return jQuery.queue(this[0], type); } return data === undefined ? this : this.each(function () { var queue = jQuery.queue(this, type, data); // ensure a hooks for this queue jQuery._queueHooks(this, type); if (type === "fx" && queue[0] !== "inprogress") { jQuery.dequeue(this, type); } }); }, dequeue: function (type) { return this.each(function () { jQuery.dequeue(this, type); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function (time, type) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue(type, function (next, hooks) { var timeout = setTimeout(next, time); hooks.stop = function () { clearTimeout(timeout); }; }); }, clearQueue: function (type) { return this.queue(type || "fx", []); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function (type, obj) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function () { if (!( --count )) { defer.resolveWith(elements, [ elements ]); } }; if (typeof type !== "string") { obj = type; type = undefined; } type = type || "fx"; while (i--) { tmp = jQuery._data(elements[ i ], type + "queueHooks"); if (tmp && tmp.empty) { count++; tmp.empty.add(resolve); } } resolve(); return defer.promise(obj); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function (name, value) { return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1); }, removeAttr: function (name) { return this.each(function () { jQuery.removeAttr(this, name); }); }, prop: function (name, value) { return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1); }, removeProp: function (name) { name = jQuery.propFix[ name ] || name; return this.each(function () { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch (e) { } }); }, addClass: function (value) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if (jQuery.isFunction(value)) { return this.each(function (j) { jQuery(this).addClass(value.call(this, j, this.className)); }); } if (proceed) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match(core_rnotwhite) || []; for (; i < len; i++) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace(rclass, " ") : " " ); if (cur) { j = 0; while ((clazz = classes[j++])) { if (cur.indexOf(" " + clazz + " ") < 0) { cur += clazz + " "; } } elem.className = jQuery.trim(cur); } } } return this; }, removeClass: function (value) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if (jQuery.isFunction(value)) { return this.each(function (j) { jQuery(this).removeClass(value.call(this, j, this.className)); }); } if (proceed) { classes = ( value || "" ).match(core_rnotwhite) || []; for (; i < len; i++) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace(rclass, " ") : "" ); if (cur) { j = 0; while ((clazz = classes[j++])) { // Remove *all* instances while (cur.indexOf(" " + clazz + " ") >= 0) { cur = cur.replace(" " + clazz + " ", " "); } } elem.className = value ? jQuery.trim(cur) : ""; } } } return this; }, toggleClass: function (value, stateVal) { var type = typeof value, isBool = typeof stateVal === "boolean"; if (jQuery.isFunction(value)) { return this.each(function (i) { jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal); }); } return this.each(function () { if (type === "string") { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.match(core_rnotwhite) || []; while ((className = classNames[ i++ ])) { // check each className given, space separated list state = isBool ? state : !self.hasClass(className); self[ state ? "addClass" : "removeClass" ](className); } // Toggle whole class name } else if (type === core_strundefined || type === "boolean") { if (this.className) { // store className if set jQuery._data(this, "__className__", this.className); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || ""; } }); }, hasClass: function (selector) { var className = " " + selector + " ", i = 0, l = this.length; for (; i < l; i++) { if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) { return true; } } return false; }, val: function (value) { var ret, hooks, isFunction, elem = this[0]; if (!arguments.length) { if (elem) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction(value); return this.each(function (i) { var val, self = jQuery(this); if (this.nodeType !== 1) { return; } if (isFunction) { val = value.call(this, i, self.val()); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if (val == null) { val = ""; } else if (typeof val === "number") { val += ""; } else if (jQuery.isArray(val)) { val = jQuery.map(val, function (value) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function (elem) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function (elem) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for (; i < max; i++) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if (( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup") )) { // Get the specific value for the option value = jQuery(option).val(); // We don't need an array for one selects if (one) { return value; } // Multi-Selects return an array values.push(value); } } return values; }, set: function (elem, value) { var values = jQuery.makeArray(value); jQuery(elem).find("option").each(function () { this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0; }); if (!values.length) { elem.selectedIndex = -1; } return values; } } }, attr: function (elem, name, value) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if (!elem || nType === 3 || nType === 8 || nType === 2) { return; } // Fallback to prop when attributes are not supported if (typeof elem.getAttribute === core_strundefined) { return jQuery.prop(elem, name, value); } notxml = nType !== 1 || !jQuery.isXMLDoc(elem); // All attributes are lowercase // Grab necessary hook if one is defined if (notxml) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test(name) ? boolHook : nodeHook ); } if (value !== undefined) { if (value === null) { jQuery.removeAttr(elem, name); } else if (hooks && notxml && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { return ret; } else { elem.setAttribute(name, value + ""); return value; } } else if (hooks && notxml && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if (typeof elem.getAttribute !== core_strundefined) { ret = elem.getAttribute(name); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function (elem, value) { var name, propName, i = 0, attrNames = value && value.match(core_rnotwhite); if (attrNames && elem.nodeType === 1) { while ((name = attrNames[i++])) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if (rboolean.test(name)) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if (!getSetAttribute && ruseDefault.test(name)) { elem[ jQuery.camelCase("default-" + name) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr(elem, name, ""); } elem.removeAttribute(getSetAttribute ? name : propName); } } }, attrHooks: { type: { set: function (elem, value) { if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute("type", value); if (val) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function (elem, name, value) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if (!elem || nType === 3 || nType === 8 || nType === 2) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc(elem); if (notxml) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if (value !== undefined) { if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { return ret; } else { return ( elem[ name ] = value ); } } else { if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function (elem) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt(attributeNode.value, 10) : rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function (elem, name) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop(elem, name), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute(name), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test(name) ? elem[ jQuery.camelCase("default-" + name) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode(name); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function (elem, value, name) { if (value === false) { // Remove boolean attributes when set to false jQuery.removeAttr(elem, name); } else if (getSetInput && getSetAttribute || !ruseDefault.test(name)) { // IE<8 needs the *property* name elem.setAttribute(!getSetAttribute && jQuery.propFix[ name ] || name, name); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase("default-" + name) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if (!getSetInput || !getSetAttribute) { jQuery.attrHooks.value = { get: function (elem, name) { var ret = elem.getAttributeNode(name); return jQuery.nodeName(elem, "input") ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function (elem, value, name) { if (jQuery.nodeName(elem, "input")) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set(elem, value, name); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if (!getSetAttribute) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function (elem, name) { var ret = elem.getAttributeNode(name); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function (elem, value, name) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode(name); if (!ret) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute(name)) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute(name) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function (elem, value, name) { nodeHook.set(elem, value === "" ? false : value, name); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function (i, name) { jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], { set: function (elem, value) { if (value === "") { elem.setAttribute(name, "auto"); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if (!jQuery.support.hrefNormalized) { jQuery.each([ "href", "src", "width", "height" ], function (i, name) { jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], { get: function (elem) { var ret = elem.getAttribute(name, 2); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function (i, name) { jQuery.propHooks[ name ] = { get: function (elem) { return elem.getAttribute(name, 4); } }; }); } if (!jQuery.support.style) { jQuery.attrHooks.style = { get: function (elem) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function (elem, value) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if (!jQuery.support.optSelected) { jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, { get: function (elem) { var parent = elem.parentNode; if (parent) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if (parent.parentNode) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if (!jQuery.support.enctype) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if (!jQuery.support.checkOn) { jQuery.each([ "radio", "checkbox" ], function () { jQuery.valHooks[ this ] = { get: function (elem) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function () { jQuery.valHooks[ this ] = jQuery.extend(jQuery.valHooks[ this ], { set: function (elem, value) { if (jQuery.isArray(value)) { return ( elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function (elem, types, handler, data, selector) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data(elem); // Don't attach events to noData or text/comment nodes (but allow plain objects) if (!elemData) { return; } // Caller can pass in an object of custom data in lieu of the handler if (handler.handler) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if (!handler.guid) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if (!(events = elemData.events)) { events = elemData.events = {}; } if (!(eventHandle = elemData.handle)) { eventHandle = elemData.handle = function (e) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match(core_rnotwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split(".").sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test(selector), namespace: namespaces.join(".") }, handleObjIn); // Init the event handler queue if we're the first if (!(handlers = events[ type ])) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) { // Bind the global event handler to the element if (elem.addEventListener) { elem.addEventListener(type, eventHandle, false); } else if (elem.attachEvent) { elem.attachEvent("on" + type, eventHandle); } } } if (special.add) { special.add.call(elem, handleObj); if (!handleObj.handler.guid) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if (selector) { handlers.splice(handlers.delegateCount++, 0, handleObj); } else { handlers.push(handleObj); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function (elem, types, handler, selector, mappedTypes) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData(elem) && jQuery._data(elem); if (!elemData || !(events = elemData.events)) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match(core_rnotwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split(".").sort(); // Unbind all events (on this namespace, if provided) for the element if (!type) { for (type in events) { jQuery.event.remove(elem, type + types[ t ], handler, selector, true); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)"); // Remove matching events origCount = j = handlers.length; while (j--) { handleObj = handlers[ j ]; if (( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test(handleObj.namespace) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector )) { handlers.splice(j, 1); if (handleObj.selector) { handlers.delegateCount--; } if (special.remove) { special.remove.call(elem, handleObj); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if (origCount && !handlers.length) { if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) { jQuery.removeEvent(elem, type, elemData.handle); } delete events[ type ]; } } // Remove the expando if it's no longer used if (jQuery.isEmptyObject(events)) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData(elem, "events"); } }, trigger: function (event, data, elem, onlyHandlers) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call(event, "type") ? event.type : event, namespaces = core_hasOwn.call(event, "namespace") ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if (elem.nodeType === 3 || elem.nodeType === 8) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if (rfocusMorph.test(type + jQuery.event.triggered)) { return; } if (type.indexOf(".") >= 0) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event(type, typeof event === "object" && event); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Clean up the event in case it is being reused event.result = undefined; if (!event.target) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray(data, [ event ]); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) { bubbleType = special.delegateType || type; if (!rfocusMorph.test(bubbleType + type)) { cur = cur.parentNode; } for (; cur; cur = cur.parentNode) { eventPath.push(cur); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if (tmp === (elem.ownerDocument || document)) { eventPath.push(tmp.defaultView || tmp.parentWindow || window); } } // Fire handlers on the event path i = 0; while ((cur = eventPath[i++]) && !event.isPropagationStopped()) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data(cur, "events") || {} )[ event.type ] && jQuery._data(cur, "handle"); if (handle) { handle.apply(cur, data); } // Native handler handle = ontype && cur[ ontype ]; if (handle && jQuery.acceptData(cur) && handle.apply && handle.apply(cur, data) === false) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if (!onlyHandlers && !event.isDefaultPrevented()) { if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if (ontype && elem[ type ] && !jQuery.isWindow(elem)) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if (tmp) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch (e) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if (tmp) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function (event) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix(event); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call(arguments), handlers = ( jQuery._data(this, "events") || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if (special.preDispatch && special.preDispatch.call(this, event) === false) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call(this, event, handlers); // Run delegates first; they may want to stop propagation beneath us i = 0; while ((matched = handlerQueue[ i++ ]) && !event.isPropagationStopped()) { event.currentTarget = matched.elem; j = 0; while ((handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped()) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply(matched.elem, args); if (ret !== undefined) { if ((event.result = ret) === false) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if (special.postDispatch) { special.postDispatch.call(this, event); } return event.result; }, handlers: function (event, handlers) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) { for (; cur != this; cur = cur.parentNode || this) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if (cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click")) { matches = []; for (i = 0; i < delegateCount; i++) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if (matches[ sel ] === undefined) { matches[ sel ] = handleObj.needsContext ? jQuery(sel, this).index(cur) >= 0 : jQuery.find(sel, this, null, [ cur ]).length; } if (matches[ sel ]) { matches.push(handleObj); } } if (matches.length) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if (delegateCount < handlers.length) { handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) }); } return handlerQueue; }, fix: function (event) { if (event[ jQuery.expando ]) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if (!fixHook) { this.fixHooks[ type ] = fixHook = rmouseEvent.test(type) ? this.mouseHooks : rkeyEvent.test(type) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat(fixHook.props) : this.props; event = new jQuery.Event(originalEvent); i = copy.length; while (i--) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if (!event.target) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if (event.target.nodeType === 3) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter(event, originalEvent) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function (event, original) { // Add which for key events if (event.which == null) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (event, original) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if (event.pageX == null && original.clientX != null) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if (!event.relatedTarget && fromElement) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if (!event.which && button !== undefined) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function () { if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function () { if (this !== document.activeElement && this.focus) { try { this.focus(); return false; } catch (e) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function () { if (this === document.activeElement && this.blur) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function (event) { // Even when returnValue equals to undefined Firefox will still show alert if (event.result !== undefined) { event.originalEvent.returnValue = event.result; } } } }, simulate: function (type, elem, event, bubble) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if (bubble) { jQuery.event.trigger(e, null, elem); } else { jQuery.event.dispatch.call(elem, e); } if (e.isDefaultPrevented()) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function (elem, type, handle) { if (elem.removeEventListener) { elem.removeEventListener(type, handle, false); } } : function (elem, type, handle) { var name = "on" + type; if (elem.detachEvent) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if (typeof elem[ name ] === core_strundefined) { elem[ name ] = null; } elem.detachEvent(name, handle); } }; jQuery.Event = function (src, props) { // Allow instantiation without the 'new' keyword if (!(this instanceof jQuery.Event)) { return new jQuery.Event(src, props); } // Event object if (src && src.type) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if (props) { jQuery.extend(this, props); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function () { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if (!e) { return; } // If preventDefault exists, run it on the original event if (e.preventDefault) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function () { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if (!e) { return; } // If stopPropagation exists, run it on the original event if (e.stopPropagation) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function () { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function (orig, fix) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function (event) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if (!related || (related !== target && !jQuery.contains(target, related))) { event.type = handleObj.origType; ret = handleObj.handler.apply(this, arguments); event.type = fix; } return ret; } }; }); // IE submit delegation if (!jQuery.support.submitBubbles) { jQuery.event.special.submit = { setup: function () { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add(this, "click._submit keypress._submit", function (e) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined; if (form && !jQuery._data(form, "submitBubbles")) { jQuery.event.add(form, "submit._submit", function (event) { event._submit_bubble = true; }); jQuery._data(form, "submitBubbles", true); } }); // return undefined since we don't need an event listener }, postDispatch: function (event) { // If form was submitted by the user, bubble the event up the tree if (event._submit_bubble) { delete event._submit_bubble; if (this.parentNode && !event.isTrigger) { jQuery.event.simulate("submit", this.parentNode, event, true); } } }, teardown: function () { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove(this, "._submit"); } }; } // IE change delegation and checkbox/radio fix if (!jQuery.support.changeBubbles) { jQuery.event.special.change = { setup: function () { if (rformElems.test(this.nodeName)) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if (this.type === "checkbox" || this.type === "radio") { jQuery.event.add(this, "propertychange._change", function (event) { if (event.originalEvent.propertyName === "checked") { this._just_changed = true; } }); jQuery.event.add(this, "click._change", function (event) { if (this._just_changed && !event.isTrigger) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate("change", this, event, true); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add(this, "beforeactivate._change", function (e) { var elem = e.target; if (rformElems.test(elem.nodeName) && !jQuery._data(elem, "changeBubbles")) { jQuery.event.add(elem, "change._change", function (event) { if (this.parentNode && !event.isSimulated && !event.isTrigger) { jQuery.event.simulate("change", this.parentNode, event, true); } }); jQuery._data(elem, "changeBubbles", true); } }); }, handle: function (event) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) { return event.handleObj.handler.apply(this, arguments); } }, teardown: function () { jQuery.event.remove(this, "._change"); return !rformElems.test(this.nodeName); } }; } // Create "bubbling" focus and blur events if (!jQuery.support.focusinBubbles) { jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function (event) { jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true); }; jQuery.event.special[ fix ] = { setup: function () { if (attaches++ === 0) { document.addEventListener(orig, handler, true); } }, teardown: function () { if (--attaches === 0) { document.removeEventListener(orig, handler, true); } } }; }); } jQuery.fn.extend({ on: function (types, selector, data, fn, /*INTERNAL*/ one) { var type, origFn; // Types can be a map of types/handlers if (typeof types === "object") { // ( types-Object, selector, data ) if (typeof selector !== "string") { // ( types-Object, data ) data = data || selector; selector = undefined; } for (type in types) { this.on(type, selector, data, types[ type ], one); } return this; } if (data == null && fn == null) { // ( types, fn ) fn = selector; data = selector = undefined; } else if (fn == null) { if (typeof selector === "string") { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if (fn === false) { fn = returnFalse; } else if (!fn) { return this; } if (one === 1) { origFn = fn; fn = function (event) { // Can use an empty set, since event contains the info jQuery().off(event); return origFn.apply(this, arguments); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each(function () { jQuery.event.add(this, types, fn, data, selector); }); }, one: function (types, selector, data, fn) { return this.on(types, selector, data, fn, 1); }, off: function (types, selector, fn) { var handleObj, type; if (types && types.preventDefault && types.handleObj) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery(types.delegateTarget).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if (typeof types === "object") { // ( types-object [, selector] ) for (type in types) { this.off(type, selector, types[ type ]); } return this; } if (selector === false || typeof selector === "function") { // ( types [, fn] ) fn = selector; selector = undefined; } if (fn === false) { fn = returnFalse; } return this.each(function () { jQuery.event.remove(this, types, fn, selector); }); }, bind: function (types, data, fn) { return this.on(types, null, data, fn); }, unbind: function (types, fn) { return this.off(types, null, fn); }, delegate: function (selector, types, data, fn) { return this.on(types, selector, data, fn); }, undelegate: function (selector, types, fn) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn); }, trigger: function (type, data) { return this.each(function () { jQuery.event.trigger(type, data, this); }); }, triggerHandler: function (type, data) { var elem = this[0]; if (elem) { return jQuery.event.trigger(type, data, elem, true); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function (window, undefined) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function (elem) { var i = 0, len = this.length; for (; i < len; i++) { if (this[i] === elem) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace("w", "w#"), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace(3, 8) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = { "ID": new RegExp("^#(" + characterEncoding + ")"), "CLASS": new RegExp("^\\.(" + characterEncoding + ")"), "NAME": new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"), "TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"), "ATTR": new RegExp("^" + attributes), "PSEUDO": new RegExp("^" + pseudos), "CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i") }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function (_, escaped) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00); }; // Use a stripped-down slice if we can't use a native one try { slice.call(preferredDoc.documentElement.childNodes, 0)[0].nodeType; } catch (e) { slice = function (i) { var elem, results = []; while ((elem = this[i++])) { results.push(elem); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative(fn) { return rnative.test(fn + ""); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function (key, value) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if (keys.push(key += " ") > Expr.cacheLength) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction(fn) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert(fn) { var div = document.createElement("div"); try { return fn(div); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle(selector, context, results, seed) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if (( context ? context.ownerDocument || context : preferredDoc ) !== document) { setDocument(context); } context = context || document; results = results || []; if (!selector || typeof selector !== "string") { return results; } if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) { return []; } if (!documentIsXML && !seed) { // Shortcuts if ((match = rquickExpr.exec(selector))) { // Speed-up: Sizzle("#ID") if ((m = match[1])) { if (nodeType === 9) { elem = context.getElementById(m); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if (elem && elem.parentNode) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if (elem.id === m) { results.push(elem); return results; } } else { return results; } } else { // Context is not a document if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) { results.push(elem); return results; } } // Speed-up: Sizzle("TAG") } else if (match[2]) { push.apply(results, slice.call(context.getElementsByTagName(selector), 0)); return results; // Speed-up: Sizzle(".CLASS") } else if ((m = match[3]) && support.getByClassName && context.getElementsByClassName) { push.apply(results, slice.call(context.getElementsByClassName(m), 0)); return results; } } // QSA path if (support.qsa && !rbuggyQSA.test(selector)) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") { groups = tokenize(selector); if ((old = context.getAttribute("id"))) { nid = old.replace(rescape, "\\$&"); } else { context.setAttribute("id", nid); } nid = "[id='" + nid + "'] "; i = groups.length; while (i--) { groups[i] = nid + toSelector(groups[i]); } newContext = rsibling.test(selector) && context.parentNode || context; newSelector = groups.join(","); } if (newSelector) { try { push.apply(results, slice.call(newContext.querySelectorAll( newSelector ), 0)); return results; } catch (qsaError) { } finally { if (!old) { context.removeAttribute("id"); } } } } } // All others return select(selector.replace(rtrim, "$1"), context, results, seed); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function (elem) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function (node) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if (doc === document || doc.nodeType !== 9 || !doc.documentElement) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML(doc); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function (div) { div.appendChild(doc.createComment("")); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function (div) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function (div) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if (!div.getElementsByClassName || !div.getElementsByClassName("e").length) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function (div) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore(div, docElem.firstChild); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName(expando).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName(expando + 0).length; support.getIdNotName = !doc.getElementById(expando); // Cleanup docElem.removeChild(div); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function (div) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function (elem) { return elem.getAttribute("href", 2); }, "type": function (elem) { return elem.getAttribute("type"); } }; // ID find and filter if (support.getIdNotName) { Expr.find["ID"] = function (id, context) { if (typeof context.getElementById !== strundefined && !documentIsXML) { var m = context.getElementById(id); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function (id) { var attrId = id.replace(runescape, funescape); return function (elem) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function (id, context) { if (typeof context.getElementById !== strundefined && !documentIsXML) { var m = context.getElementById(id); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function (id) { var attrId = id.replace(runescape, funescape); return function (elem) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function (tag, context) { if (typeof context.getElementsByTagName !== strundefined) { return context.getElementsByTagName(tag); } } : function (tag, context) { var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag); // Filter out possible comments if (tag === "*") { while ((elem = results[i++])) { if (elem.nodeType === 1) { tmp.push(elem); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function (tag, context) { if (typeof context.getElementsByName !== strundefined) { return context.getElementsByName(name); } }; // Class Expr.find["CLASS"] = support.getByClassName && function (className, context) { if (typeof context.getElementsByClassName !== strundefined && !documentIsXML) { return context.getElementsByClassName(className); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ((support.qsa = isNative(doc.querySelectorAll))) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function (div) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if (!div.querySelectorAll("[selected]").length) { rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if (!div.querySelectorAll(":checked").length) { rbuggyQSA.push(":checked"); } }); assert(function (div) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if (div.querySelectorAll("[i^='']").length) { rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')"); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if (!div.querySelectorAll(":enabled").length) { rbuggyQSA.push(":enabled", ":disabled"); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ((support.matchesSelector = isNative((matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)))) { assert(function (div) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead matches.call(div, "[s!='']:x"); rbuggyMatches.push("!=", pseudos); }); } rbuggyQSA = new RegExp(rbuggyQSA.join("|")); rbuggyMatches = new RegExp(rbuggyMatches.join("|")); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function (a, b) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16 )); } : function (a, b) { if (b) { while ((b = b.parentNode)) { if (b === a) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function (a, b) { var compare; if (a === b) { hasDuplicate = true; return 0; } if ((compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition(b))) { if (compare & 1 || a.parentNode && a.parentNode.nodeType === 11) { if (a === doc || contains(preferredDoc, a)) { return -1; } if (b === doc || contains(preferredDoc, b)) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function (a, b) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if (a === b) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if (!aup || !bup) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if (aup === bup) { return siblingCheck(a, b); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ((cur = cur.parentNode)) { ap.unshift(cur); } cur = b; while ((cur = cur.parentNode)) { bp.unshift(cur); } // Walk down the tree looking for a discrepancy while (ap[i] === bp[i]) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck(ap[i], bp[i]) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort(sortOrder); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function (expr, elements) { return Sizzle(expr, null, null, elements); }; Sizzle.matchesSelector = function (elem, expr) { // Set document vars if needed if (( elem.ownerDocument || elem ) !== document) { setDocument(elem); } // Make sure that attribute selectors are quoted expr = expr.replace(rattributeQuotes, "='$1']"); // rbuggyQSA always contains :focus, so no need for an existence check if (support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr)) { try { var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes if (ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11) { return ret; } } catch (e) { } } return Sizzle(expr, document, null, [elem]).length > 0; }; Sizzle.contains = function (context, elem) { // Set document vars if needed if (( context.ownerDocument || context ) !== document) { setDocument(context); } return contains(context, elem); }; Sizzle.attr = function (elem, name) { var val; // Set document vars if needed if (( elem.ownerDocument || elem ) !== document) { setDocument(elem); } if (!documentIsXML) { name = name.toLowerCase(); } if ((val = Expr.attrHandle[ name ])) { return val(elem); } if (documentIsXML || support.attributes) { return elem.getAttribute(name); } return ( (val = elem.getAttributeNode(name)) || elem.getAttribute(name) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function (msg) { throw new Error("Syntax error, unrecognized expression: " + msg); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function (results) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort(sortOrder); if (hasDuplicate) { for (; (elem = results[i]); i++) { if (elem === results[ i - 1 ]) { j = duplicates.push(i); } } while (j--) { results.splice(duplicates[ j ], 1); } } return results; }; function siblingCheck(a, b) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if (diff) { return diff; } // Check if b follows a if (cur) { while ((cur = cur.nextSibling)) { if (cur === b) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo(type) { return function (elem) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo(type) { return function (elem) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo(fn) { return markFunction(function (argument) { argument = +argument; return markFunction(function (seed, matches) { var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length; // Match elements found at the specified indexes while (i--) { if (seed[ (j = matchIndexes[i]) ]) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function (elem) { var node, ret = "", i = 0, nodeType = elem.nodeType; if (!nodeType) { // If no nodeType, this is expected to be an array for (; (node = elem[i]); i++) { // Do not traverse comment nodes ret += getText(node); } } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if (typeof elem.textContent === "string") { return elem.textContent; } else { // Traverse its children for (elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText(elem); } } } else if (nodeType === 3 || nodeType === 4) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function (match) { match[1] = match[1].replace(runescape, funescape); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace(runescape, funescape); if (match[2] === "~=") { match[3] = " " + match[3] + " "; } return match.slice(0, 4); }, "CHILD": function (match) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if (match[1].slice(0, 3) === "nth") { // nth-* requires argument if (!match[3]) { Sizzle.error(match[0]); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if (match[3]) { Sizzle.error(match[0]); } return match; }, "PSEUDO": function (match) { var excess, unquoted = !match[5] && match[2]; if (matchExpr["CHILD"].test(match[0])) { return null; } // Accept quoted arguments as-is if (match[4]) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if (unquoted && rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize(unquoted, true)) && // advance to the next closing parenthesis (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) { // excess is a negative index match[0] = match[0].slice(0, excess); match[2] = unquoted.slice(0, excess); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice(0, 3); } }, filter: { "TAG": function (nodeName) { if (nodeName === "*") { return function () { return true; }; } nodeName = nodeName.replace(runescape, funescape).toLowerCase(); return function (elem) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function (className) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function (elem) { return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || ""); }); }, "ATTR": function (name, operator, check) { return function (elem) { var result = Sizzle.attr(elem, name); if (result == null) { return operator === "!="; } if (!operator) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? ( " " + result + " " ).indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false; }; }, "CHILD": function (type, what, argument, first, last) { var simple = type.slice(0, 3) !== "nth", forward = type.slice(-4) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function (elem) { return !!elem.parentNode; } : function (elem, context, xml) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if (parent) { // :(first|last|only)-(child|of-type) if (simple) { while (dir) { node = elem; while ((node = node[ dir ])) { if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if (forward && useCache) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ((node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop())) { // When found, cache indexes on `parent` and break if (node.nodeType === 1 && ++diff && node === elem) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if (useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ((node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop())) { if (( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff) { // Cache the index of each encountered element if (useCache) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if (node === elem) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function (pseudo, argument) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if (fn[ expando ]) { return fn(argument); } // But maintain support for old signatures if (fn.length > 1) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) { var idx, matched = fn(seed, argument), i = matched.length; while (i--) { idx = indexOf.call(seed, matched[i]); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function (elem) { return fn(elem, 0, args); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function (selector) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1")); return matcher[ expando ] ? markFunction(function (seed, matches, context, xml) { var elem, unmatched = matcher(seed, null, xml, []), i = seed.length; // Match elements unmatched by `matcher` while (i--) { if ((elem = unmatched[i])) { seed[i] = !(matches[i] = elem); } } }) : function (elem, context, xml) { input[0] = elem; matcher(input, null, xml, results); return !results.pop(); }; }), "has": markFunction(function (selector) { return function (elem) { return Sizzle(selector, elem).length > 0; }; }), "contains": markFunction(function (text) { return function (elem) { return ( elem.textContent || elem.innerText || getText(elem) ).indexOf(text) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction(function (lang) { // lang value must be a valid identifider if (!ridentifier.test(lang || "")) { Sizzle.error("unsupported lang: " + lang); } lang = lang.replace(runescape, funescape).toLowerCase(); return function (elem) { var elemLang; do { if ((elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang)) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf(lang + "-") === 0; } } while ((elem = elem.parentNode) && elem.nodeType === 1); return false; }; }), // Miscellaneous "target": function (elem) { var hash = window.location && window.location.hash; return hash && hash.slice(1) === elem.id; }, "root": function (elem) { return elem === docElem; }, "focus": function (elem) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function (elem) { return elem.disabled === false; }, "disabled": function (elem) { return elem.disabled === true; }, "checked": function (elem) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function (elem) { // Accessing this property makes selected-by-default // options in Safari work properly if (elem.parentNode) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function (elem) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for (elem = elem.firstChild; elem; elem = elem.nextSibling) { if (elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4) { return false; } } return true; }, "parent": function (elem) { return !Expr.pseudos["empty"](elem); }, // Element/input types "header": function (elem) { return rheader.test(elem.nodeName); }, "input": function (elem) { return rinputs.test(elem.nodeName); }, "button": function (elem) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function (elem) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function () { return [ 0 ]; }), "last": createPositionalPseudo(function (matchIndexes, length) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function (matchIndexes, length, argument) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function (matchIndexes, length) { var i = 0; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "odd": createPositionalPseudo(function (matchIndexes, length) { var i = 1; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "lt": createPositionalPseudo(function (matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; --i >= 0;) { matchIndexes.push(i); } return matchIndexes; }), "gt": createPositionalPseudo(function (matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; ++i < length;) { matchIndexes.push(i); } return matchIndexes; }) } }; // Add button/input type pseudos for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) { Expr.pseudos[ i ] = createInputPseudo(i); } for (i in { submit: true, reset: true }) { Expr.pseudos[ i ] = createButtonPseudo(i); } function tokenize(selector, parseOnly) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if (cached) { return parseOnly ? 0 : cached.slice(0); } soFar = selector; groups = []; preFilters = Expr.preFilter; while (soFar) { // Comma and first run if (!matched || (match = rcomma.exec(soFar))) { if (match) { // Don't consume trailing commas as valid soFar = soFar.slice(match[0].length) || soFar; } groups.push(tokens = []); } matched = false; // Combinators if ((match = rcombinators.exec(soFar))) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace(rtrim, " ") }); soFar = soFar.slice(matched.length); } // Filters for (type in Expr.filter) { if ((match = matchExpr[ type ].exec(soFar)) && (!preFilters[ type ] || (match = preFilters[ type ](match)))) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice(matched.length); } } if (!matched) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); } function toSelector(tokens) { var i = 0, len = tokens.length, selector = ""; for (; i < len; i++) { selector += tokens[i].value; } return selector; } function addCombinator(matcher, combinator, base) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function (elem, context, xml) { while ((elem = elem[ dir ])) { if (elem.nodeType === 1 || checkNonElements) { return matcher(elem, context, xml); } } } : // Check against all ancestor/preceding elements function (elem, context, xml) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if (xml) { while ((elem = elem[ dir ])) { if (elem.nodeType === 1 || checkNonElements) { if (matcher(elem, context, xml)) { return true; } } } } else { while ((elem = elem[ dir ])) { if (elem.nodeType === 1 || checkNonElements) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ((cache = outerCache[ dir ]) && cache[0] === dirkey) { if ((data = cache[1]) === true || data === cachedruns) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher(elem, context, xml) || cachedruns; if (cache[1] === true) { return true; } } } } } }; } function elementMatcher(matchers) { return matchers.length > 1 ? function (elem, context, xml) { var i = matchers.length; while (i--) { if (!matchers[i](elem, context, xml)) { return false; } } return true; } : matchers[0]; } function condense(unmatched, map, filter, context, xml) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for (; i < len; i++) { if ((elem = unmatched[i])) { if (!filter || filter(elem, context, xml)) { newUnmatched.push(elem); if (mapped) { map.push(i); } } } } return newUnmatched; } function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) { if (postFilter && !postFilter[ expando ]) { postFilter = setMatcher(postFilter); } if (postFinder && !postFinder[ expando ]) { postFinder = setMatcher(postFinder, postSelector); } return markFunction(function (seed, results, context, xml) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [ context ] : context, []), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if (matcher) { matcher(matcherIn, matcherOut, context, xml); } // Apply postFilter if (postFilter) { temp = condense(matcherOut, postMap); postFilter(temp, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = temp.length; while (i--) { if ((elem = temp[i])) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if (seed) { if (postFinder || preFilter) { if (postFinder) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while (i--) { if ((elem = matcherOut[i])) { // Restore matcherIn since elem is not yet a final match temp.push((matcherIn[i] = elem)); } } postFinder(null, (matcherOut = []), temp, xml); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while (i--) { if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut ); if (postFinder) { postFinder(null, results, matcherOut, xml); } else { push.apply(results, matcherOut); } } }); } function matcherFromTokens(tokens) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator(function (elem) { return elem === checkContext; }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) { return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true), matchers = [ function (elem, context, xml) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml) ); } ]; for (; i < len; i++) { if ((matcher = Expr.relative[ tokens[i].type ])) { matchers = [ addCombinator(elementMatcher(matchers), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher if (matcher[ expando ]) { // Find the next relative operator (if any) for proper handling j = ++i; for (; j < len; j++) { if (Expr.relative[ tokens[j].type ]) { break; } } return setMatcher( i > 1 && elementMatcher(matchers), i > 1 && toSelector(tokens.slice(0, i - 1)).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && toSelector(tokens) ); } matchers.push(matcher); } } return elementMatcher(matchers); } function matcherFromGroupMatchers(elementMatchers, setMatchers) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, expandContext) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if (outermost) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for (; (elem = elems[i]) != null; i++) { if (byElement && elem) { j = 0; while ((matcher = elementMatchers[j++])) { if (matcher(elem, context, xml)) { results.push(elem); break; } } if (outermost) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if (bySet) { // They will have gone through all possible matchers if ((elem = !matcher && elem)) { matchedCount--; } // Lengthen the array for every element, matched or not if (seed) { unmatched.push(elem); } } } // Apply set filters to unmatched elements matchedCount += i; if (bySet && i !== matchedCount) { j = 0; while ((matcher = setMatchers[j++])) { matcher(unmatched, setMatched, context, xml); } if (seed) { // Reintegrate element matches to eliminate the need for sorting if (matchedCount > 0) { while (i--) { if (!(unmatched[i] || setMatched[i])) { setMatched[i] = pop.call(results); } } } // Discard index placeholder values to get only actual matches setMatched = condense(setMatched); } // Add matches to results push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting if (outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1) { Sizzle.uniqueSort(results); } } // Override manipulation of globals by nested matchers if (outermost) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction(superMatcher) : superMatcher; } compile = Sizzle.compile = function (selector, group /* Internal Use Only */) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if (!cached) { // Generate a function of recursive functions that can be used to check each element if (!group) { group = tokenize(selector); } i = group.length; while (i--) { cached = matcherFromTokens(group[i]); if (cached[ expando ]) { setMatchers.push(cached); } else { elementMatchers.push(cached); } } // Cache the compiled function cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); } return cached; }; function multipleContexts(selector, contexts, results) { var i = 0, len = contexts.length; for (; i < len; i++) { Sizzle(selector, contexts[i], results); } return results; } function select(selector, context, results, seed) { var i, tokens, token, type, find, match = tokenize(selector); if (!seed) { // Try to minimize operations if there is only one group if (match.length === 1) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice(0); if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ]) { context = Expr.find["ID"](token.matches[0].replace(runescape, funescape), context)[0]; if (!context) { return results; } selector = selector.slice(tokens.shift().value.length); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length; while (i--) { token = tokens[i]; // Abort if we hit a combinator if (Expr.relative[ (type = token.type) ]) { break; } if ((find = Expr.find[ type ])) { // Search, expanding context for leading sibling combinators if ((seed = find( token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && context.parentNode || context ))) { // If seed is empty or no tokens remain, we can return early tokens.splice(i, 1); selector = seed.length && toSelector(tokens); if (!selector) { push.apply(results, slice.call(seed, 0)); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile(selector, match)( seed, context, documentIsXML, results, rsibling.test(selector) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() { } Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(window); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function (selector) { var i, ret, self, len = this.length; if (typeof selector !== "string") { self = this; return this.pushStack(jQuery(selector).filter(function () { for (i = 0; i < len; i++) { if (jQuery.contains(self[ i ], this)) { return true; } } })); } ret = []; for (i = 0; i < len; i++) { jQuery.find(selector, this[ i ], ret); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function (target) { var i, targets = jQuery(target, this), len = targets.length; return this.filter(function () { for (i = 0; i < len; i++) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, not: function (selector) { return this.pushStack(winnow(this, selector, false)); }, filter: function (selector) { return this.pushStack(winnow(this, selector, true)); }, is: function (selector) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test(selector) ? jQuery(selector, this.context).index(this[0]) >= 0 : jQuery.filter(selector, this).length > 0 : this.filter(selector).length > 0 ); }, closest: function (selectors, context) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0; for (; i < l; i++) { cur = this[i]; while (cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11) { if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) { ret.push(cur); break; } cur = cur.parentNode; } } return this.pushStack(ret.length > 1 ? jQuery.unique(ret) : ret); }, // Determine the position of an element within // the matched set of elements index: function (elem) { // No argument, return index in parent if (!elem) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if (typeof elem === "string") { return jQuery.inArray(this[0], jQuery(elem)); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this); }, add: function (selector, context) { var set = typeof selector === "string" ? jQuery(selector, context) : jQuery.makeArray(selector && selector.nodeType ? [ selector ] : selector), all = jQuery.merge(this.get(), set); return this.pushStack(jQuery.unique(all)); }, addBack: function (selector) { return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling(cur, dir) { do { cur = cur[ dir ]; } while (cur && cur.nodeType !== 1); return cur; } jQuery.each({ parent: function (elem) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function (elem) { return jQuery.dir(elem, "parentNode"); }, parentsUntil: function (elem, i, until) { return jQuery.dir(elem, "parentNode", until); }, next: function (elem) { return sibling(elem, "nextSibling"); }, prev: function (elem) { return sibling(elem, "previousSibling"); }, nextAll: function (elem) { return jQuery.dir(elem, "nextSibling"); }, prevAll: function (elem) { return jQuery.dir(elem, "previousSibling"); }, nextUntil: function (elem, i, until) { return jQuery.dir(elem, "nextSibling", until); }, prevUntil: function (elem, i, until) { return jQuery.dir(elem, "previousSibling", until); }, siblings: function (elem) { return jQuery.sibling(( elem.parentNode || {} ).firstChild, elem); }, children: function (elem) { return jQuery.sibling(elem.firstChild); }, contents: function (elem) { return jQuery.nodeName(elem, "iframe") ? elem.contentDocument || elem.contentWindow.document : jQuery.merge([], elem.childNodes); } }, function (name, fn) { jQuery.fn[ name ] = function (until, selector) { var ret = jQuery.map(this, fn, until); if (!runtil.test(name)) { selector = until; } if (selector && typeof selector === "string") { ret = jQuery.filter(selector, ret); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique(ret) : ret; if (this.length > 1 && rparentsprev.test(name)) { ret = ret.reverse(); } return this.pushStack(ret); }; }); jQuery.extend({ filter: function (expr, elems, not) { if (not) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function (elem, dir, until) { var matched = [], cur = elem[ dir ]; while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) { if (cur.nodeType === 1) { matched.push(cur); } cur = cur[dir]; } return matched; }, sibling: function (n, elem) { var r = []; for (; n; n = n.nextSibling) { if (n.nodeType === 1 && n !== elem) { r.push(n); } } return r; } }); // Implement the identical functionality for filter and not function winnow(elements, qualifier, keep) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function (elem, i) { var retVal = !!qualifier.call(elem, i, elem); return retVal === keep; }); } else if (qualifier.nodeType) { return jQuery.grep(elements, function (elem) { return ( elem === qualifier ) === keep; }); } else if (typeof qualifier === "string") { var filtered = jQuery.grep(elements, function (elem) { return elem.nodeType === 1; }); if (isSimple.test(qualifier)) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter(qualifier, filtered); } } return jQuery.grep(elements, function (elem) { return ( jQuery.inArray(elem, qualifier) >= 0 ) === keep; }); } function createSafeFragment(document) { var list = nodeNames.split("|"), safeFrag = document.createDocumentFragment(); if (safeFrag.createElement) { while (list.length) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment(document), fragmentDiv = safeFragment.appendChild(document.createElement("div")); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function (value) { return jQuery.access(this, function (value) { return value === undefined ? jQuery.text(this) : this.empty().append(( this[0] && this[0].ownerDocument || document ).createTextNode(value)); }, null, value, arguments.length); }, wrapAll: function (html) { if (jQuery.isFunction(html)) { return this.each(function (i) { jQuery(this).wrapAll(html.call(this, i)); }); } if (this[0]) { // The elements to wrap the target around var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true); if (this[0].parentNode) { wrap.insertBefore(this[0]); } wrap.map(function () { var elem = this; while (elem.firstChild && elem.firstChild.nodeType === 1) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function (html) { if (jQuery.isFunction(html)) { return this.each(function (i) { jQuery(this).wrapInner(html.call(this, i)); }); } return this.each(function () { var self = jQuery(this), contents = self.contents(); if (contents.length) { contents.wrapAll(html); } else { self.append(html); } }); }, wrap: function (html) { var isFunction = jQuery.isFunction(html); return this.each(function (i) { jQuery(this).wrapAll(isFunction ? html.call(this, i) : html); }); }, unwrap: function () { return this.parent().each(function () { if (!jQuery.nodeName(this, "body")) { jQuery(this).replaceWith(this.childNodes); } }).end(); }, append: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { this.appendChild(elem); } }); }, prepend: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { this.insertBefore(elem, this.firstChild); } }); }, before: function () { return this.domManip(arguments, false, function (elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this); } }); }, after: function () { return this.domManip(arguments, false, function (elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this.nextSibling); } }); }, // keepData is for internal use only--do not document remove: function (selector, keepData) { var elem, i = 0; for (; (elem = this[i]) != null; i++) { if (!selector || jQuery.filter(selector, [ elem ]).length > 0) { if (!keepData && elem.nodeType === 1) { jQuery.cleanData(getAll(elem)); } if (elem.parentNode) { if (keepData && jQuery.contains(elem.ownerDocument, elem)) { setGlobalEval(getAll(elem, "script")); } elem.parentNode.removeChild(elem); } } } return this; }, empty: function () { var elem, i = 0; for (; (elem = this[i]) != null; i++) { // Remove element nodes and prevent memory leaks if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); } // Remove any remaining nodes while (elem.firstChild) { elem.removeChild(elem.firstChild); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if (elem.options && jQuery.nodeName(elem, "select")) { elem.options.length = 0; } } return this; }, clone: function (dataAndEvents, deepDataAndEvents) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function () { return jQuery.clone(this, dataAndEvents, deepDataAndEvents); }); }, html: function (value) { return jQuery.access(this, function (value) { var elem = this[0] || {}, i = 0, l = this.length; if (value === undefined) { return elem.nodeType === 1 ? elem.innerHTML.replace(rinlinejQuery, "") : undefined; } // See if we can take a shortcut and just use innerHTML if (typeof value === "string" && !rnoInnerhtml.test(value) && ( jQuery.support.htmlSerialize || !rnoshimcache.test(value) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value) ) && !wrapMap[ ( rtagName.exec(value) || ["", ""] )[1].toLowerCase() ]) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for (; i < l; i++) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch (e) { } } if (elem) { this.empty().append(value); } }, null, value, arguments.length); }, replaceWith: function (value) { var isFunc = jQuery.isFunction(value); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if (!isFunc && typeof value !== "string") { value = jQuery(value).not(this).detach(); } return this.domManip([ value ], true, function (elem) { var next = this.nextSibling, parent = this.parentNode; if (parent) { jQuery(this).remove(); parent.insertBefore(elem, next); } }); }, detach: function (selector) { return this.remove(selector, true); }, domManip: function (args, table, callback) { // Flatten any nested arrays args = core_concat.apply([], args); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction(value); // We can't cloneNode fragments that contain checked, in WebKit if (isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test(value) )) { return this.each(function (index) { var self = set.eq(index); if (isFunction) { args[0] = value.call(this, index, table ? self.html() : undefined); } self.domManip(args, table, callback); }); } if (l) { fragment = jQuery.buildFragment(args, this[ 0 ].ownerDocument, false, this); first = fragment.firstChild; if (fragment.childNodes.length === 1) { fragment = first; } if (first) { table = table && jQuery.nodeName(first, "tr"); scripts = jQuery.map(getAll(fragment, "script"), disableScript); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for (; i < l; i++) { node = fragment; if (i !== iNoClone) { node = jQuery.clone(node, true, true); // Keep references to cloned scripts for later restoration if (hasScripts) { jQuery.merge(scripts, getAll(node, "script")); } } callback.call( table && jQuery.nodeName(this[i], "table") ? findOrAppend(this[i], "tbody") : this[i], node, i ); } if (hasScripts) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map(scripts, restoreScript); // Evaluate executable scripts on first document insertion for (i = 0; i < hasScripts; i++) { node = scripts[ i ]; if (rscriptType.test(node.type || "") && !jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) { if (node.src) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval(( node.text || node.textContent || node.innerHTML || "" ).replace(rcleanScript, "")); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend(elem, tag) { return elem.getElementsByTagName(tag)[0] || elem.appendChild(elem.ownerDocument.createElement(tag)); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript(elem) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript(elem) { var match = rscriptTypeMasked.exec(elem.type); if (match) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval(elems, refElements) { var elem, i = 0; for (; (elem = elems[i]) != null; i++) { jQuery._data(elem, "globalEval", !refElements || jQuery._data(refElements[i], "globalEval")); } } function cloneCopyEvent(src, dest) { if (dest.nodeType !== 1 || !jQuery.hasData(src)) { return; } var type, i, l, oldData = jQuery._data(src), curData = jQuery._data(dest, oldData), events = oldData.events; if (events) { delete curData.handle; curData.events = {}; for (type in events) { for (i = 0, l = events[ type ].length; i < l; i++) { jQuery.event.add(dest, type, events[ type ][ i ]); } } } // make the cloned public data object a copy from the original if (curData.data) { curData.data = jQuery.extend({}, curData.data); } } function fixCloneNodeIssues(src, dest) { var nodeName, e, data; // We do not need to do anything for non-Elements if (dest.nodeType !== 1) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if (!jQuery.support.noCloneEvent && dest[ jQuery.expando ]) { data = jQuery._data(dest); for (e in data.events) { jQuery.removeEvent(dest, e, data.handle); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute(jQuery.expando); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if (nodeName === "script" && dest.text !== src.text) { disableScript(dest).text = src.text; restoreScript(dest); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if (nodeName === "object") { if (dest.parentNode) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if (jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) )) { dest.innerHTML = src.innerHTML; } } else if (nodeName === "input" && manipulation_rcheckableType.test(src.type)) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if (dest.value !== src.value) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if (nodeName === "option") { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if (nodeName === "input" || nodeName === "textarea") { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function (name, original) { jQuery.fn[ name ] = function (selector) { var elems, i = 0, ret = [], insert = jQuery(selector), last = insert.length - 1; for (; i <= last; i++) { elems = i === last ? this : this.clone(true); jQuery(insert[i])[ original ](elems); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply(ret, elems.get()); } return this.pushStack(ret); }; }); function getAll(context, tag) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName(tag || "*") : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll(tag || "*") : undefined; if (!found) { for (found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++) { if (!tag || jQuery.nodeName(elem, tag)) { found.push(elem); } else { jQuery.merge(found, getAll(elem, tag)); } } } return tag === undefined || tag && jQuery.nodeName(context, tag) ? jQuery.merge([ context ], found) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked(elem) { if (manipulation_rcheckableType.test(elem.type)) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function (elem, dataAndEvents, deepDataAndEvents) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains(elem.ownerDocument, elem); if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) { clone = elem.cloneNode(true); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild(clone = fragmentDiv.firstChild); } if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll(clone); srcElements = getAll(elem); // Fix all IE cloning issues for (i = 0; (node = srcElements[i]) != null; ++i) { // Ensure that the destination node is not null; Fixes #9587 if (destElements[i]) { fixCloneNodeIssues(node, destElements[i]); } } } // Copy the events from the original to the clone if (dataAndEvents) { if (deepDataAndEvents) { srcElements = srcElements || getAll(elem); destElements = destElements || getAll(clone); for (i = 0; (node = srcElements[i]) != null; i++) { cloneCopyEvent(node, destElements[i]); } } else { cloneCopyEvent(elem, clone); } } // Preserve script evaluation history destElements = getAll(clone, "script"); if (destElements.length > 0) { setGlobalEval(destElements, !inPage && getAll(elem, "script")); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function (elems, context, scripts, selection) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment(context), nodes = [], i = 0; for (; i < l; i++) { elem = elems[ i ]; if (elem || elem === 0) { // Add nodes directly if (jQuery.type(elem) === "object") { jQuery.merge(nodes, elem.nodeType ? [ elem ] : elem); // Convert non-html into a text node } else if (!rhtml.test(elem)) { nodes.push(context.createTextNode(elem)); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild(context.createElement("div")); // Deserialize a standard representation tag = ( rtagName.exec(elem) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while (j--) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) { nodes.push(context.createTextNode(rleadingWhitespace.exec(elem)[0])); } // Remove IE's autoinserted <tbody> from table fragments if (!jQuery.support.tbody) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test(elem) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test(elem) ? tmp : 0; j = elem && elem.childNodes.length; while (j--) { if (jQuery.nodeName((tbody = elem.childNodes[j]), "tbody") && !tbody.childNodes.length) { elem.removeChild(tbody); } } } jQuery.merge(nodes, tmp.childNodes); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while (tmp.firstChild) { tmp.removeChild(tmp.firstChild); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if (tmp) { safe.removeChild(tmp); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if (!jQuery.support.appendChecked) { jQuery.grep(getAll(nodes, "input"), fixDefaultChecked); } i = 0; while ((elem = nodes[ i++ ])) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if (selection && jQuery.inArray(elem, selection) !== -1) { continue; } contains = jQuery.contains(elem.ownerDocument, elem); // Append to fragment tmp = getAll(safe.appendChild(elem), "script"); // Preserve script evaluation history if (contains) { setGlobalEval(tmp); } // Capture executables if (scripts) { j = 0; while ((elem = tmp[ j++ ])) { if (rscriptType.test(elem.type || "")) { scripts.push(elem); } } } } tmp = null; return safe; }, cleanData: function (elems, /* internal */ acceptData) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for (; (elem = elems[i]) != null; i++) { if (acceptData || jQuery.acceptData(elem)) { id = elem[ internalKey ]; data = id && cache[ id ]; if (data) { if (data.events) { for (type in data.events) { if (special[ type ]) { jQuery.event.remove(elem, type); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent(elem, type, data.handle); } } } // Remove cache only if it was not already removed by jQuery.event.remove if (cache[ id ]) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if (deleteExpando) { delete elem[ internalKey ]; } else if (typeof elem.removeAttribute !== core_strundefined) { elem.removeAttribute(internalKey); } else { elem[ internalKey ] = null; } core_deletedIds.push(id); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp("^(" + core_pnum + ")(.*)$", "i"), rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i"), rrelNum = new RegExp("^([+-])=(" + core_pnum + ")", "i"), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName(style, name) { // shortcut for names that are not vendor prefixed if (name in style) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while (i--) { name = cssPrefixes[ i ] + capName; if (name in style) { return name; } } return origName; } function isHidden(elem, el) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem); } function showHide(elements, show) { var display, elem, hidden, values = [], index = 0, length = elements.length; for (; index < length; index++) { elem = elements[ index ]; if (!elem.style) { continue; } values[ index ] = jQuery._data(elem, "olddisplay"); display = elem.style.display; if (show) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if (!values[ index ] && display === "none") { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if (elem.style.display === "" && isHidden(elem)) { values[ index ] = jQuery._data(elem, "olddisplay", css_defaultDisplay(elem.nodeName)); } } else { if (!values[ index ]) { hidden = isHidden(elem); if (display && display !== "none" || !hidden) { jQuery._data(elem, "olddisplay", hidden ? display : jQuery.css(elem, "display")); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for (index = 0; index < length; index++) { elem = elements[ index ]; if (!elem.style) { continue; } if (!show || elem.style.display === "none" || elem.style.display === "") { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function (name, value) { return jQuery.access(this, function (elem, name, value) { var len, styles, map = {}, i = 0; if (jQuery.isArray(name)) { styles = getStyles(elem); len = name.length; for (; i < len; i++) { map[ name[ i ] ] = jQuery.css(elem, name[ i ], false, styles); } return map; } return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name); }, name, value, arguments.length > 1); }, show: function () { return showHide(this, true); }, hide: function () { return showHide(this); }, toggle: function (state) { var bool = typeof state === "boolean"; return this.each(function () { if (bool ? state : isHidden(this)) { jQuery(this).show(); } else { jQuery(this).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function (elem, computed) { if (computed) { // We should always get a number back from opacity var ret = curCSS(elem, "opacity"); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function (elem, name, value, extra) { // Don't set styles on text and comment nodes if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase(name), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName(style, origName) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if (value !== undefined) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if (type === "string" && (ret = rrelNum.exec(value))) { value = ( ret[1] + 1 ) * ret[2] + parseFloat(jQuery.css(elem, name)); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if (value == null || type === "number" && isNaN(value)) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if (type === "number" && !jQuery.cssNumber[ origName ]) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if (!jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch (e) { } } } else { // If a hook was provided get the non-computed value from there if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function (elem, name, extra, styles) { var num, val, hooks, origName = jQuery.camelCase(name); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName(elem.style, origName) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if (hooks && "get" in hooks) { val = hooks.get(elem, true, extra); } // Otherwise, if a way to get the computed value exists, use that if (val === undefined) { val = curCSS(elem, name, styles); } //convert "normal" to computed value if (val === "normal" && name in cssNormalTransform) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if (extra === "" || extra) { num = parseFloat(val); return extra === true || jQuery.isNumeric(num) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function (elem, options, callback, args) { var ret, name, old = {}; // Remember the old values, and insert the new ones for (name in options) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply(elem, args || []); // Revert the old values for (name in options) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if (window.getComputedStyle) { getStyles = function (elem) { return window.getComputedStyle(elem, null); }; curCSS = function (elem, name, _computed) { var width, minWidth, maxWidth, computed = _computed || getStyles(elem), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue(name) || computed[ name ] : undefined, style = elem.style; if (computed) { if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) { ret = jQuery.style(elem, name); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if (rnumnonpx.test(ret) && rmargin.test(name)) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if (document.documentElement.currentStyle) { getStyles = function (elem) { return elem.currentStyle; }; curCSS = function (elem, name, _computed) { var left, rs, rsLeft, computed = _computed || getStyles(elem), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if (ret == null && style && style[ name ]) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if (rnumnonpx.test(ret) && !rposition.test(name)) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if (rsLeft) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if (rsLeft) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber(elem, value, subtract) { var matches = rnumsplit.exec(value); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max(0, matches[ 1 ] - ( subtract || 0 )) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for (; i < 4; i += 2) { // both box models exclude margin, so add it if we want it if (extra === "margin") { val += jQuery.css(elem, extra + cssExpand[ i ], true, styles); } if (isBorderBox) { // border-box includes padding, so remove it if we want content if (extra === "content") { val -= jQuery.css(elem, "padding" + cssExpand[ i ], true, styles); } // at this point, extra isn't border nor margin, so remove border if (extra !== "margin") { val -= jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles); } } else { // at this point, extra isn't content, so add padding val += jQuery.css(elem, "padding" + cssExpand[ i ], true, styles); // at this point, extra isn't content nor padding, so add border if (extra !== "padding") { val += jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles); } } } return val; } function getWidthOrHeight(elem, name, extra) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles(elem), isBorderBox = jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if (val <= 0 || val == null) { // Fall back to computed then uncomputed css if necessary val = curCSS(elem, name, styles); if (val < 0 || val == null) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if (rnumnonpx.test(val)) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat(val) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay(nodeName) { var doc = document, display = elemdisplay[ nodeName ]; if (!display) { display = actualDisplay(nodeName, doc); // If the simple way fails, read from inside an iframe if (display === "none" || !display) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css("cssText", "display:block !important") ).appendTo(doc.documentElement); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay(nodeName, doc); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay(name, doc) { var elem = jQuery(doc.createElement(name)).appendTo(doc.body), display = jQuery.css(elem[0], "display"); elem.remove(); return display; } jQuery.each([ "height", "width" ], function (i, name) { jQuery.cssHooks[ name ] = { get: function (elem, computed, extra) { if (computed) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test(jQuery.css(elem, "display")) ? jQuery.swap(elem, cssShow, function () { return getWidthOrHeight(elem, name, extra); }) : getWidthOrHeight(elem, name, extra); } }, set: function (elem, value, extra) { var styles = extra && getStyles(elem); return setPositiveNumber(elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box", styles ) : 0 ); } }; }); if (!jQuery.support.opacity) { jQuery.cssHooks.opacity = { get: function (elem, computed) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? ( 0.01 * parseFloat(RegExp.$1) ) + "" : computed ? "1" : ""; }, set: function (elem, value) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if (( value >= 1 || value === "" ) && jQuery.trim(filter.replace(ralpha, "")) === "" && style.removeAttribute) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute("filter"); // if there is no filter style applied in a css rule or unset inline opacity, we are done if (value === "" || currentStyle && !currentStyle.filter) { return; } } // otherwise, set new filter values style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function () { if (!jQuery.support.reliableMarginRight) { jQuery.cssHooks.marginRight = { get: function (elem, computed) { if (computed) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap(elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ]); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if (!jQuery.support.pixelPosition && jQuery.fn.position) { jQuery.each([ "top", "left" ], function (i, prop) { jQuery.cssHooks[ prop ] = { get: function (elem, computed) { if (computed) { computed = curCSS(elem, prop); // if curCSS returns percentage, fallback to offset return rnumnonpx.test(computed) ? jQuery(elem).position()[ prop ] + "px" : computed; } } }; }); } }); if (jQuery.expr && jQuery.expr.filters) { jQuery.expr.filters.hidden = function (elem) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none"); }; jQuery.expr.filters.visible = function (elem) { return !jQuery.expr.filters.hidden(elem); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function (prefix, suffix) { jQuery.cssHooks[ prefix + suffix ] = { expand: function (value) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for (; i < 4; i++) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if (!rmargin.test(prefix)) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function () { return jQuery.param(this.serializeArray()); }, serializeArray: function () { return this.map(function () { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop(this, "elements"); return elements ? jQuery.makeArray(elements) : this; }) .filter(function () { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && ( this.checked || !manipulation_rcheckableType.test(type) ); }) .map(function (i, elem) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map(val, function (val) { return { name: elem.name, value: val.replace(rCRLF, "\r\n") }; }) : { name: elem.name, value: val.replace(rCRLF, "\r\n") }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function (a, traditional) { var prefix, s = [], add = function (key, value) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if (traditional === undefined) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if (jQuery.isArray(a) || ( a.jquery && !jQuery.isPlainObject(a) )) { // Serialize the form elements jQuery.each(a, function () { add(this.name, this.value); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for (prefix in a) { buildParams(prefix, a[ prefix ], traditional, add); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); }; function buildParams(prefix, obj, traditional, add) { var name; if (jQuery.isArray(obj)) { // Serialize array item. jQuery.each(obj, function (i, v) { if (traditional || rbracket.test(prefix)) { // Treat each array item as a scalar. add(prefix, v); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams(prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add); } }); } else if (!traditional && jQuery.type(obj) === "object") { // Serialize object item. for (name in obj) { buildParams(prefix + "[" + name + "]", obj[ name ], traditional, add); } } else { // Serialize scalar item. add(prefix, obj); } } jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function (i, name) { // Handle event binding jQuery.fn[ name ] = function (data, fn) { return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name); }; }); jQuery.fn.hover = function (fnOver, fnOut) { return this.mouseenter(fnOver).mouseleave(fnOut || fnOver); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch (e) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement("a"); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports(structure) { // dataTypeExpression is optional and defaults to "*" return function (dataTypeExpression, func) { if (typeof dataTypeExpression !== "string") { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || []; if (jQuery.isFunction(func)) { // For each dataType in the dataTypeExpression while ((dataType = dataTypes[i++])) { // Prepend if requested if (dataType[0] === "+") { dataType = dataType.slice(1) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift(func); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push(func); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect(dataType) { var selected; inspected[ dataType ] = true; jQuery.each(structure[ dataType ] || [], function (_, prefilterOrFactory) { var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR); if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ]) { options.dataTypes.unshift(dataTypeOrTransport); inspect(dataTypeOrTransport); return false; } else if (seekingTransport) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect(options.dataTypes[ 0 ]) || !inspected[ "*" ] && inspect("*"); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend(target, src) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for (key in src) { if (src[ key ] !== undefined) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if (deep) { jQuery.extend(true, target, deep); } return target; } jQuery.fn.load = function (url, params, callback) { if (typeof url !== "string" && _load) { return _load.apply(this, arguments); } var selector, response, type, self = this, off = url.indexOf(" "); if (off >= 0) { selector = url.slice(off, url.length); url = url.slice(0, off); } // If it's a function if (jQuery.isFunction(params)) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if (params && typeof params === "object") { type = "POST"; } // If we have elements to modify, make the request if (self.length > 0) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function (responseText) { // Save response for use in complete callback response = arguments; self.html(selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) : // Otherwise use the full result responseText); }).complete(callback && function (jqXHR, status) { self.each(callback, response || [ jqXHR.responseText, status, jqXHR ]); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each([ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function (i, type) { jQuery.fn[ type ] = function (fn) { return this.on(type, fn); }; }); jQuery.each([ "get", "post" ], function (i, method) { jQuery[ method ] = function (url, data, callback, type) { // shift arguments if data argument was omitted if (jQuery.isFunction(data)) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test(ajaxLocParts[ 1 ]), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function (target, settings) { return settings ? // Building a settings object ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) : // Extending ajaxSettings ajaxExtend(jQuery.ajaxSettings, target); }, ajaxPrefilter: addToPrefiltersOrTransports(prefilters), ajaxTransport: addToPrefiltersOrTransports(transports), // Main method ajax: function (url, options) { // If url is an object, simulate pre-1.5 signature if (typeof url === "object") { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup({}, options), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery(callbackContext) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function (key) { var match; if (state === 2) { if (!responseHeaders) { responseHeaders = {}; while ((match = rheaders.exec(responseHeadersString))) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function () { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function (name, value) { var lname = name.toLowerCase(); if (!state) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function (type) { if (!state) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function (map) { var code; if (map) { if (state < 2) { for (code in map) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always(map[ jqXHR.status ]); } } return this; }, // Cancel the request abort: function (statusText) { var finalText = statusText || strAbort; if (transport) { transport.abort(finalText); } done(0, finalText); return this; } }; // Attach deferreds deferred.promise(jqXHR).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace(rhash, "").replace(rprotocol, ajaxLocParts[ 1 ] + "//"); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(core_rnotwhite) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if (s.crossDomain == null) { parts = rurl.exec(s.url.toLowerCase()); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if (s.data && s.processData && typeof s.data !== "string") { s.data = jQuery.param(s.data, s.traditional); } // Apply prefilters inspectPrefiltersOrTransports(prefilters, s, options, jqXHR); // If request was aborted inside a prefilter, stop there if (state === 2) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if (fireGlobals && jQuery.active++ === 0) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test(s.type); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if (!s.hasContent) { // If data is available, append data to url if (s.data) { cacheURL = ( s.url += ( ajax_rquery.test(cacheURL) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if (s.cache === false) { s.url = rts.test(cacheURL) ? // If there is already a '_' parameter, set its value cacheURL.replace(rts, "$1_=" + ajax_nonce++) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test(cacheURL) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { if (jQuery.lastModified[ cacheURL ]) { jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[ cacheURL ]); } if (jQuery.etag[ cacheURL ]) { jqXHR.setRequestHeader("If-None-Match", jQuery.etag[ cacheURL ]); } } // Set the correct header, if data is being sent if (s.data && s.hasContent && s.contentType !== false || options.contentType) { jqXHR.setRequestHeader("Content-Type", s.contentType); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for (i in s.headers) { jqXHR.setRequestHeader(i, s.headers[ i ]); } // Allow custom headers/mimetypes and early abort if (s.beforeSend && ( s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2 )) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for (i in { success: 1, error: 1, complete: 1 }) { jqXHR[ i ](s[ i ]); } // Get transport transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR); // If no transport, we auto-abort if (!transport) { done(-1, "No Transport"); } else { jqXHR.readyState = 1; // Send global event if (fireGlobals) { globalEventContext.trigger("ajaxSend", [ jqXHR, s ]); } // Timeout if (s.async && s.timeout > 0) { timeoutTimer = setTimeout(function () { jqXHR.abort("timeout"); }, s.timeout); } try { state = 1; transport.send(requestHeaders, done); } catch (e) { // Propagate exception as error if not done if (state < 2) { done(-1, e); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done(status, nativeStatusText, responses, headers) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if (state === 2) { return; } // State is "done" now state = 2; // Clear timeout if it exists if (timeoutTimer) { clearTimeout(timeoutTimer); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } // If successful, handle type chaining if (status >= 200 && status < 300 || status === 304) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { modified = jqXHR.getResponseHeader("Last-Modified"); if (modified) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if (modified) { jQuery.etag[ cacheURL ] = modified; } } // if no content if (status === 204) { isSuccess = true; statusText = "nocontent"; // if not modified } else if (status === 304) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert(s, response); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if (status || !statusText) { statusText = "error"; if (status < 0) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if (isSuccess) { deferred.resolveWith(callbackContext, [ success, statusText, jqXHR ]); } else { deferred.rejectWith(callbackContext, [ jqXHR, statusText, error ]); } // Status-dependent callbacks jqXHR.statusCode(statusCode); statusCode = undefined; if (fireGlobals) { globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ]); } // Complete completeDeferred.fireWith(callbackContext, [ jqXHR, statusText ]); if (fireGlobals) { globalEventContext.trigger("ajaxComplete", [ jqXHR, s ]); // Handle the global AJAX counter if (!( --jQuery.active )) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function (url, callback) { return jQuery.get(url, undefined, callback, "script"); }, getJSON: function (url, data, callback) { return jQuery.get(url, data, callback, "json"); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses(s, jqXHR, responses) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for (type in responseFields) { if (type in responses) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while (dataTypes[ 0 ] === "*") { dataTypes.shift(); if (ct === undefined) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if (ct) { for (type in contents) { if (contents[ type ] && contents[ type ].test(ct)) { dataTypes.unshift(type); break; } } } // Check to see if we have a response for the expected dataType if (dataTypes[ 0 ] in responses) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for (type in responses) { if (!dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ]) { finalDataType = type; break; } if (!firstDataType) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if (finalDataType) { if (finalDataType !== dataTypes[ 0 ]) { dataTypes.unshift(finalDataType); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert(s, response) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if (s.dataFilter) { response = s.dataFilter(response, s.dataType); } // Create converters map with lowercased keys if (dataTypes[ 1 ]) { for (conv in s.converters) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for (; (current = dataTypes[++i]);) { // There's only work to do if current dataType is non-auto if (current !== "*") { // Convert response if prev dataType is non-auto and differs from current if (prev !== "*" && prev !== current) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if (!conv) { for (conv2 in converters) { // If conv2 outputs current tmp = conv2.split(" "); if (tmp[ 1 ] === current) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if (conv) { // Condense equivalence converters if (conv === true) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if (converters[ conv2 ] !== true) { current = tmp[ 0 ]; dataTypes.splice(i--, 0, current); } break; } } } } // Apply converter (if not an equivalence) if (conv !== true) { // Unless errors are allowed to bubble, catch and return them if (conv && s["throws"]) { response = conv(response); } else { try { response = conv(response); } catch (e) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function (text) { jQuery.globalEval(text); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter("script", function (s) { if (s.cache === undefined) { s.cache = false; } if (s.crossDomain) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport("script", function (s) { // This transport only deals with cross domain requests if (s.crossDomain) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function (_, callback) { script = document.createElement("script"); script.async = true; if (s.scriptCharset) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function (_, isAbort) { if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if (script.parentNode) { script.parentNode.removeChild(script); } // Dereference the script script = null; // Callback if not abort if (!isAbort) { callback(200, "success"); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore(script, head.firstChild); }, abort: function () { if (script) { script.onload(undefined, true); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function () { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test(s.url) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if (jsonProp || s.dataTypes[ 0 ] === "jsonp") { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if (jsonProp) { s[ jsonProp ] = s[ jsonProp ].replace(rjsonp, "$1" + callbackName); } else if (s.jsonp !== false) { s.url += ( ajax_rquery.test(s.url) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function () { if (!responseContainer) { jQuery.error(callbackName + " was not called"); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function () { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function () { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if (s[ callbackName ]) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push(callbackName); } // Call if it was a function and we have a response if (responseContainer && jQuery.isFunction(overwritten)) { overwritten(responseContainer[ 0 ]); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function () { // Abort all pending requests var key; for (key in xhrCallbacks) { xhrCallbacks[ key ](undefined, true); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch (e) { } } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function () { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if (xhrSupported) { jQuery.ajaxTransport(function (s) { // Cross domain only allowed if supported through XMLHttpRequest if (!s.crossDomain || jQuery.support.cors) { var callback; return { send: function (headers, complete) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if (s.username) { xhr.open(s.type, s.url, s.async, s.username, s.password); } else { xhr.open(s.type, s.url, s.async); } // Apply custom fields if provided if (s.xhrFields) { for (i in s.xhrFields) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if (s.mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(s.mimeType); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if (!s.crossDomain && !headers["X-Requested-With"]) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for (i in headers) { xhr.setRequestHeader(i, headers[ i ]); } } catch (err) { } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send(( s.hasContent && s.data ) || null); // Listener callback = function (_, isAbort) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if (callback && ( isAbort || xhr.readyState === 4 )) { // Only called once callback = undefined; // Do not keep as active anymore if (handle) { xhr.onreadystatechange = jQuery.noop; if (xhrOnUnloadAbort) { delete xhrCallbacks[ handle ]; } } // If it's an abort if (isAbort) { // Abort it manually if needed if (xhr.readyState !== 4) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if (typeof xhr.responseText === "string") { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch (e) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if (!status && s.isLocal && !s.crossDomain) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if (status === 1223) { status = 204; } } } } catch (firefoxAccessException) { if (!isAbort) { complete(-1, firefoxAccessException); } } // Call complete if needed if (responses) { complete(status, statusText, responses, responseHeaders); } }; if (!s.async) { // if we're in sync mode we fire the callback callback(); } else if (xhr.readyState === 4) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout(callback); } else { handle = ++xhrId; if (xhrOnUnloadAbort) { // Create the active xhrs callbacks list if needed // and attach the unload handler if (!xhrCallbacks) { xhrCallbacks = {}; jQuery(window).unload(xhrOnUnloadAbort); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function () { if (callback) { callback(undefined, true); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp("^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i"), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function (prop, value) { var end, unit, tween = this.createTween(prop, value), parts = rfxnum.exec(value), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if (parts) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if (unit !== "px" && start) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css(tween.elem, prop, true) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style(tween.elem, prop, start + unit); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while (scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function () { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens(animation, props) { jQuery.each(props, function (prop, value) { var collection = ( tweeners[ prop ] || [] ).concat(tweeners[ "*" ]), index = 0, length = collection.length; for (; index < length; index++) { if (collection[ index ].call(animation, prop, value)) { // we're done with this property return; } } }); } function Animation(elem, properties, options) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always(function () { // don't match elem in the :animated selector delete tick.elem; }), tick = function () { if (stopped) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max(0, animation.startTime + animation.duration - currentTime), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for (; index < length; index++) { animation.tweens[ index ].run(percent); } deferred.notifyWith(elem, [ animation, percent, remaining ]); if (percent < 1 && length) { return remaining; } else { deferred.resolveWith(elem, [ animation ]); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend({}, properties), opts: jQuery.extend(true, { specialEasing: {} }, options), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function (prop, end) { var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing); animation.tweens.push(tween); return tween; }, stop: function (gotoEnd) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if (stopped) { return this; } stopped = true; for (; index < length; index++) { animation.tweens[ index ].run(1); } // resolve when we played the last frame // otherwise, reject if (gotoEnd) { deferred.resolveWith(elem, [ animation, gotoEnd ]); } else { deferred.rejectWith(elem, [ animation, gotoEnd ]); } return this; } }), props = animation.props; propFilter(props, animation.opts.specialEasing); for (; index < length; index++) { result = animationPrefilters[ index ].call(animation, elem, props, animation.opts); if (result) { return result; } } createTweens(animation, props); if (jQuery.isFunction(animation.opts.start)) { animation.opts.start.call(elem, animation); } jQuery.fx.timer( jQuery.extend(tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress(animation.opts.progress) .done(animation.opts.done, animation.opts.complete) .fail(animation.opts.fail) .always(animation.opts.always); } function propFilter(props, specialEasing) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for (index in props) { name = jQuery.camelCase(index); easing = specialEasing[ name ]; value = props[ index ]; if (jQuery.isArray(value)) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if (index !== name) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if (hooks && "expand" in hooks) { value = hooks.expand(value); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for (index in value) { if (!( index in props )) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend(Animation, { tweener: function (props, callback) { if (jQuery.isFunction(props)) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for (; index < length; index++) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift(callback); } }, prefilter: function (callback, prepend) { if (prepend) { animationPrefilters.unshift(callback); } else { animationPrefilters.push(callback); } } }); function defaultPrefilter(elem, props, opts) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden(elem); // handle queue: false promises if (!opts.queue) { hooks = jQuery._queueHooks(elem, "fx"); if (hooks.unqueued == null) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function () { if (!hooks.unqueued) { oldfire(); } }; } hooks.unqueued++; anim.always(function () { // doing this makes sure that the complete handler will be called // before this completes anim.always(function () { hooks.unqueued--; if (!jQuery.queue(elem, "fx").length) { hooks.empty.fire(); } }); }); } // height/width overflow pass if (elem.nodeType === 1 && ( "height" in props || "width" in props )) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if (jQuery.css(elem, "display") === "inline" && jQuery.css(elem, "float") === "none") { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if (!jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay(elem.nodeName) === "inline") { style.display = "inline-block"; } else { style.zoom = 1; } } } if (opts.overflow) { style.overflow = "hidden"; if (!jQuery.support.shrinkWrapBlocks) { anim.always(function () { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for (index in props) { value = props[ index ]; if (rfxtypes.exec(value)) { delete props[ index ]; toggle = toggle || value === "toggle"; if (value === ( hidden ? "hide" : "show" )) { continue; } handled.push(index); } } length = handled.length; if (length) { dataShow = jQuery._data(elem, "fxshow") || jQuery._data(elem, "fxshow", {}); if ("hidden" in dataShow) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if (toggle) { dataShow.hidden = !hidden; } if (hidden) { jQuery(elem).show(); } else { anim.done(function () { jQuery(elem).hide(); }); } anim.done(function () { var prop; jQuery._removeData(elem, "fxshow"); for (prop in orig) { jQuery.style(elem, prop, orig[ prop ]); } }); for (index = 0; index < length; index++) { prop = handled[ index ]; tween = anim.createTween(prop, hidden ? dataShow[ prop ] : 0); orig[ prop ] = dataShow[ prop ] || jQuery.style(elem, prop); if (!( prop in dataShow )) { dataShow[ prop ] = tween.start; if (hidden) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween(elem, options, prop, end, easing) { return new Tween.prototype.init(elem, options, prop, end, easing); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function (elem, options, prop, end, easing, unit) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function () { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this); }, run: function (percent) { var eased, hooks = Tween.propHooks[ this.prop ]; if (this.options.duration) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if (this.options.step) { this.options.step.call(this.elem, this.now, this); } if (hooks && hooks.set) { hooks.set(this); } else { Tween.propHooks._default.set(this); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function (tween) { var result; if (tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null)) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css(tween.elem, tween.prop, ""); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function (tween) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if (jQuery.fx.step[ tween.prop ]) { jQuery.fx.step[ tween.prop ](tween); } else if (tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] )) { jQuery.style(tween.elem, tween.prop, tween.now + tween.unit); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function (tween) { if (tween.elem.nodeType && tween.elem.parentNode) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function (i, name) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function (speed, easing, callback) { return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback); }; }); jQuery.fn.extend({ fadeTo: function (speed, to, easing, callback) { // show any hidden elements after setting opacity to 0 return this.filter(isHidden).css("opacity", 0).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback); }, animate: function (prop, speed, easing, callback) { var empty = jQuery.isEmptyObject(prop), optall = jQuery.speed(speed, easing, callback), doAnimation = function () { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation(this, jQuery.extend({}, prop), optall); doAnimation.finish = function () { anim.stop(true); }; // Empty animations, or finishing resolves immediately if (empty || jQuery._data(this, "finish")) { anim.stop(true); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation); }, stop: function (type, clearQueue, gotoEnd) { var stopQueue = function (hooks) { var stop = hooks.stop; delete hooks.stop; stop(gotoEnd); }; if (typeof type !== "string") { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if (clearQueue && type !== false) { this.queue(type || "fx", []); } return this.each(function () { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data(this); if (index) { if (data[ index ] && data[ index ].stop) { stopQueue(data[ index ]); } } else { for (index in data) { if (data[ index ] && data[ index ].stop && rrun.test(index)) { stopQueue(data[ index ]); } } } for (index = timers.length; index--;) { if (timers[ index ].elem === this && (type == null || timers[ index ].queue === type)) { timers[ index ].anim.stop(gotoEnd); dequeue = false; timers.splice(index, 1); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if (dequeue || !gotoEnd) { jQuery.dequeue(this, type); } }); }, finish: function (type) { if (type !== false) { type = type || "fx"; } return this.each(function () { var index, data = jQuery._data(this), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue(this, type, []); if (hooks && hooks.cur && hooks.cur.finish) { hooks.cur.finish.call(this); } // look for any active animations, and finish them for (index = timers.length; index--;) { if (timers[ index ].elem === this && timers[ index ].queue === type) { timers[ index ].anim.stop(true); timers.splice(index, 1); } } // look for any animations in the old queue and finish them for (index = 0; index < length; index++) { if (queue[ index ] && queue[ index ].finish) { queue[ index ].finish.call(this); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx(type, includeWidth) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for (; i < 4; i += 2 - includeWidth) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if (includeWidth) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function (name, props) { jQuery.fn[ name ] = function (speed, easing, callback) { return this.animate(props, speed, easing, callback); }; }); jQuery.speed = function (speed, easing, fn) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction(speed) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if (opt.queue == null || opt.queue === true) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function () { if (jQuery.isFunction(opt.old)) { opt.old.call(this); } if (opt.queue) { jQuery.dequeue(this, opt.queue); } }; return opt; }; jQuery.easing = { linear: function (p) { return p; }, swing: function (p) { return 0.5 - Math.cos(p * Math.PI) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function () { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for (; i < timers.length; i++) { timer = timers[ i ]; // Checks the timer has not already been removed if (!timer() && timers[ i ] === timer) { timers.splice(i--, 1); } } if (!timers.length) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function (timer) { if (timer() && jQuery.timers.push(timer)) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function () { if (!timerId) { timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval); } }; jQuery.fx.stop = function () { clearInterval(timerId); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if (jQuery.expr && jQuery.expr.filters) { jQuery.expr.filters.animated = function (elem) { return jQuery.grep(jQuery.timers,function (fn) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function (options) { if (arguments.length) { return options === undefined ? this : this.each(function (i) { jQuery.offset.setOffset(this, options, i); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if (!doc) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if (!jQuery.contains(docElem, elem)) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if (typeof elem.getBoundingClientRect !== core_strundefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function (elem, options, i) { var position = jQuery.css(elem, "position"); // set position first, in-case top/left are set even on static elem if (position === "static") { elem.style.position = "relative"; } var curElem = jQuery(elem), curOffset = curElem.offset(), curCSSTop = jQuery.css(elem, "top"), curCSSLeft = jQuery.css(elem, "left"), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if (calculatePosition) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat(curCSSTop) || 0; curLeft = parseFloat(curCSSLeft) || 0; } if (jQuery.isFunction(options)) { options = options.call(elem, i, curOffset); } if (options.top != null) { props.top = ( options.top - curOffset.top ) + curTop; } if (options.left != null) { props.left = ( options.left - curOffset.left ) + curLeft; } if ("using" in options) { options.using.call(elem, props); } else { curElem.css(props); } } }; jQuery.fn.extend({ position: function () { if (!this[ 0 ]) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if (jQuery.css(elem, "position") === "fixed") { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if (!jQuery.nodeName(offsetParent[ 0 ], "html")) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css(offsetParent[ 0 ], "borderTopWidth", true); parentOffset.left += jQuery.css(offsetParent[ 0 ], "borderLeftWidth", true); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true), left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true) }; }, offsetParent: function () { return this.map(function () { var offsetParent = this.offsetParent || document.documentElement; while (offsetParent && ( !jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static" )) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each({scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function (method, prop) { var top = /Y/.test(prop); jQuery.fn[ method ] = function (val) { return jQuery.access(this, function (elem, method, val) { var win = getWindow(elem); if (val === undefined) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if (win) { win.scrollTo( !top ? val : jQuery(win).scrollLeft(), top ? val : jQuery(win).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null); }; }); function getWindow(elem) { return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each({ Height: "height", Width: "width" }, function (name, type) { jQuery.each({ padding: "inner" + name, content: type, "": "outer" + name }, function (defaultExtra, funcName) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function (margin, value) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access(this, function (elem, type, value) { var doc; if (jQuery.isWindow(elem)) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if (elem.nodeType === 9) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css(elem, type, extra) : // Set width or height on the element jQuery.style(elem, type, value, extra); }, type, chainable ? margin : undefined, chainable, null); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if (typeof define === "function" && define.amd && define.amd.jQuery) { define("jquery", [], function () { return jQuery; }); } })(window);
mit
Sharagoz/rails_exception_handler
spec/integration/rails_exception_handler_spec.rb
4789
require 'spec_helper' describe RailsExceptionHandler do it "should catch controller errors" do get "/home/controller_error" RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) last_response.body.should match(/Internal server error/) RailsExceptionHandler::ActiveRecord::ErrorMessage.first.class_name.should == 'NoMethodError' RailsExceptionHandler::Mongoid::ErrorMessage.first.class_name.should == 'NoMethodError' if defined?(Mongoid) end it "should catch model errors" do get "/home/model_error" RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) last_response.body.should match(/Internal server error/) RailsExceptionHandler::ActiveRecord::ErrorMessage.first.class_name.should == 'NoMethodError' RailsExceptionHandler::Mongoid::ErrorMessage.first.class_name.should == 'NoMethodError' if defined?(Mongoid) end it "should catch view errors" do get "/home/view_error" RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) last_response.body.should match(/Internal server error/) RailsExceptionHandler::ActiveRecord::ErrorMessage.first.class_name.should == 'ActionView::Template::Error' RailsExceptionHandler::Mongoid::ErrorMessage.first.class_name.should == 'ActionView::Template::Error' if defined?(Mongoid) end it "should catch routing errors" do get "/incorrect_route" RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) last_response.body.should match(/Internal server error/) RailsExceptionHandler::ActiveRecord::ErrorMessage.first.class_name.should == 'ActionController::RoutingError' RailsExceptionHandler::Mongoid::ErrorMessage.first.class_name.should == 'ActionController::RoutingError' if defined?(Mongoid) end it "should catch syntax errors" do get "/home/syntax_error" RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) last_response.body.should match(/Internal server error/) RailsExceptionHandler::ActiveRecord::ErrorMessage.first.class_name.should == 'SyntaxError' RailsExceptionHandler::Mongoid::ErrorMessage.first.class_name.should == 'SyntaxError' if defined?(Mongoid) end it "should store the specified information in the database" do RailsExceptionHandler.configure { |config| config.store_user_info = {:method => :current_user, :field => :login} } get "/home/controller_error", {}, {'HTTP_REFERER' => 'http://google.com/', 'HTTP_USER_AGENT' => 'Mozilla/4.0 (compatible; MSIE 8.0)'} RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) msgs = [RailsExceptionHandler::ActiveRecord::ErrorMessage.first] msgs << RailsExceptionHandler::Mongoid::ErrorMessage.first if defined?(Mongoid) msgs.each do |msg| msg.app_name.should == 'ExceptionHandlerTestApp' msg.class_name.should == 'NoMethodError' msg.message.should include "undefined method `foo' for nil:NilClass" msg.trace.should match /#{TEST_APP}\/app\/controllers\/home_controller.rb:4:in `controller_error'/ msg.params.should match /"controller"=>"home"/ msg.params.should match /"action"=>"controller_error"/ msg.user_agent.should == 'Mozilla/4.0 (compatible; MSIE 8.0)' msg.target_url.should == 'http://example.org/home/controller_error' msg.referer_url.should == 'http://google.com/' msg.user_info.should == 'matz' msg.server_name.should == 'example.org' msg.remote_addr.should == '127.0.0.1' msg.created_at.should be > 5.seconds.ago msg.created_at.should be < Time.now end end describe 'it should use the correct layout' do example '- application layout exists' do get "/home/controller_error" last_response.body.should match(/this_is_the_application_layout/) end example '- custom layout specified in render call' do pending "does not work" get "/home/custom_layout" last_response.body.should match(/this_is_the_custom_layout/) end example '- falling back when application layout doesn exist' do pending "must be tested manually" get "/incorrect_route" last_response.body.should match(/this_is_the_fallback_layout/) end end end
mit
keatflame/wekit
cron.go
1571
package wekit import ( "fmt" "os" "strings" "time" ) // CronJob process type CronJob struct { Name string Arg []string RunType int64 RunDateTime *time.Time Directories []string LogFileName string CommitBuffer int64 Process map[string]int64 } // NewCronJob create new cron job func NewCronJob(name string) *CronJob { t := time.Now() c := &CronJob{ Name: name, Arg: os.Args[2:], RunDateTime: &t, CommitBuffer: 50, } c.LogFileName = c.Name + ".log" process := make(map[string]int64) process["Processed"] = 0 c.Process = process return c } // MakeDir make directory from Directories property func (c *CronJob) MakeDir() { for _, v := range c.Directories { MakeDir(v) } } // IsCommitBuffer check number of processed record func (c *CronJob) IsCommitBuffer() bool { return c.Process["Processed"]%c.CommitBuffer == 0 && c.Process["Processed"] > 0 } // PrintProcess print current process count func (c *CronJob) PrintProcess() { strs := make([]string, 0) strs = append(strs, fmt.Sprintf("%s: %d", "Processed", c.Process["Processed"])) for i, v := range c.Process { if i == "Processed" { continue } if v > 0 { str := fmt.Sprintf("%s: %d", i, v) strs = append(strs, str) } } p(fmt.Sprintf("%s - %s", c.Name, strings.Join(strs, ", "))) } // Start print start notice func (c *CronJob) Start() { p("...START...") } // End print end notice func (c *CronJob) End() { p("....END....") } // Panic print error message func (c *CronJob) Panic(msg string) { p(msg) os.Exit(0) }
mit
Jawira/case-converter
src/Convert.php
12563
<?php declare(strict_types=1); namespace Jawira\CaseConverter; use Jawira\CaseConverter\Glue\AdaCase; use Jawira\CaseConverter\Glue\CamelCase; use Jawira\CaseConverter\Glue\CobolCase; use Jawira\CaseConverter\Glue\DashGluer; use Jawira\CaseConverter\Glue\DotNotation; use Jawira\CaseConverter\Glue\Gluer; use Jawira\CaseConverter\Glue\KebabCase; use Jawira\CaseConverter\Glue\LowerCase; use Jawira\CaseConverter\Glue\MacroCase; use Jawira\CaseConverter\Glue\PascalCase; use Jawira\CaseConverter\Glue\SentenceCase; use Jawira\CaseConverter\Glue\SnakeCase; use Jawira\CaseConverter\Glue\SpaceGluer; use Jawira\CaseConverter\Glue\TitleCase; use Jawira\CaseConverter\Glue\TrainCase; use Jawira\CaseConverter\Glue\UnderscoreGluer; use Jawira\CaseConverter\Glue\UpperCase; use Jawira\CaseConverter\Split\DashSplitter; use Jawira\CaseConverter\Split\DotSplitter; use Jawira\CaseConverter\Split\SpaceSplitter; use Jawira\CaseConverter\Split\Splitter; use Jawira\CaseConverter\Split\UnderscoreSplitter; use Jawira\CaseConverter\Split\UppercaseSplitter; use function is_subclass_of; use function mb_strpos; use function preg_match; /** * Convert string between different naming conventions. * * Handled formats: * * - Ada case * - Camel case * - Cobol case * - Kebab case * - Lower case * - Macro case * - Pascal case * - Sentence case * - Snake case * - Title case * - Train case * - Upper case * * @method self fromAda() Treat input string as _Ada case_ * @method self fromCamel() Treat input string as _Camel case_ * @method self fromCobol() Treat input string as _Cobol case_ * @method self fromDot() Treat input string as _Dot notation_ * @method self fromKebab() Treat input string as _Kebab case_ * @method self fromLower() Treat input string as _Lower case_ * @method self fromMacro() Treat input string as _Macro case_ * @method self fromPascal() Treat input string as _Pascal case_ * @method self fromSentence() Treat input string as _Sentence case_ * @method self fromSnake() Treat input string as _Snake case_ * @method self fromTitle() Treat input string as _Title case_ * @method self fromTrain() Treat input string as _Train case_ * @method self fromUpper() Treat input string as _Upper case_ * * @method string toAda() Return string in _Ada case_ format * @method string toCamel() Return string in _Camel case_ format * @method string toCobol() Return string in _Cobol case_ format * @method string toDot() Return string in _Dot notation_ * @method string toKebab() Return string in _Kebab case_ format * @method string toLower() Return string in _Lower case_ format * @method string toMacro() Return string in _Macro case_ format * @method string toPascal() Return string in _Pascal case_ format * @method string toSentence() Return string in _Sentence case_ format * @method string toSnake() Return string in _Snake case_ format * @method string toTitle() Return string in _Title case_ format * @method string toTrain() Return string in _Train case_ format * @method string toUpper() Return string in _Upper case_ format * * @see https://softwareengineering.stackexchange.com/questions/322413/bothered-by-an-unknown-letter-case-name * @see http://www.unicode.org/charts/case/ * @package Jawira\CaseConverter * @author Jawira Portugal <dev@tugal.be> */ class Convert { /** * @var string Input string to convert */ protected $source; /** * @var string[] Words extracted from input string */ protected $words; /** * @var bool */ protected $forceSimpleCaseMapping; /** * Constructor method * * @param string $source String to convert * * @throws \Jawira\CaseConverter\CaseConverterException */ public function __construct(string $source) { $this->source = $source; $this->forceSimpleCaseMapping = false; $this->fromAuto(); } /** * Auto-detect naming convention * * @return \Jawira\CaseConverter\Convert * @throws \Jawira\CaseConverter\CaseConverterException */ public function fromAuto(): self { $splitter = $this->analyse($this->source); $this->extractWords($splitter); return $this; } /** * Detects word separator of $input string and tells you what strategy you should use. * * @param string $input String to be analysed * * @throws \Jawira\CaseConverter\CaseConverterException * @return \Jawira\CaseConverter\Split\Splitter */ protected function analyse(string $input): Splitter { switch (true) { case $this->contains($input, UnderscoreGluer::DELIMITER): $splittingStrategy = new UnderscoreSplitter($input); break; case $this->contains($input, DashGluer::DELIMITER): $splittingStrategy = new DashSplitter($input); break; case $this->contains($input, SpaceGluer::DELIMITER): $splittingStrategy = new SpaceSplitter($input); break; case $this->contains($input, DotNotation::DELIMITER): $splittingStrategy = new DotSplitter($input); break; case $this->isUppercaseWord($input): $splittingStrategy = new UnderscoreSplitter($input); break; default: $splittingStrategy = new UppercaseSplitter($input); break; } return $splittingStrategy; } /** * Return true if $needle is found in $input string * * @param string $input String where the search is performed * @param string $needle Needle * * @return bool */ protected function contains(string $input, string $needle): bool { return is_int(mb_strpos($input, $needle)); } /** * Returns true if $input string is a single word composed only by uppercase characters. * * ``` * isUppercaseWord('BRUSSELS'); // true * isUppercaseWord('Brussels'); // false * ``` * * @see https://www.regular-expressions.info/unicode.html#category * * @param string $input String to be tested. * * @return bool * @throws \Jawira\CaseConverter\CaseConverterException */ protected function isUppercaseWord(string $input): bool { $match = preg_match('#^\p{Lu}+$#u', $input); if (false === $match) { throw new CaseConverterException('Error executing regex'); // @codeCoverageIgnore } return 1 === $match; } /** * Main function, receives input string and then it stores extracted words into an array. * * @param \Jawira\CaseConverter\Split\Splitter $splitter * * @return $this */ protected function extractWords(Splitter $splitter): self { $this->words = $splitter->split(); return $this; } /** * Returns original input string * * @return string Original input string */ public function getSource(): string { return $this->source; } /** * Handle `to*` methods and `from*` methods * * @param string $methodName * @param array $arguments * * @return string|\Jawira\CaseConverter\Convert * @throws \Jawira\CaseConverter\CaseConverterException */ public function __call($methodName, $arguments) { if (0 === mb_strpos($methodName, 'from')) { $result = $this->handleSplitterMethod($methodName); } elseif (0 === mb_strpos($methodName, 'to')) { $result = $this->handleGluerMethod($methodName); } else { throw new CaseConverterException("Unknown method: $methodName"); } return $result; } /** * Methods to explicitly define naming conventions for input string * * @param string $methodName * * @return $this * @throws \Jawira\CaseConverter\CaseConverterException */ protected function handleSplitterMethod(string $methodName): self { switch ($methodName) { case 'fromCamel': case 'fromPascal': $splitterName = UppercaseSplitter::class; break; case 'fromSnake': case 'fromAda': case 'fromMacro': $splitterName = UnderscoreSplitter::class; break; case 'fromKebab': case 'fromTrain': case 'fromCobol': $splitterName = DashSplitter::class; break; case 'fromLower': case 'fromUpper': case 'fromTitle': case 'fromSentence': $splitterName = SpaceSplitter::class; break; case 'fromDot': $splitterName = DotSplitter::class; break; default: throw new CaseConverterException("Unknown method: $methodName"); break; } $splitter = $this->createSplitter($splitterName, $this->source); $this->extractWords($splitter); return $this; } /** * @param string $className Class name in string format * @param string $source Input string to be split * * @return \Jawira\CaseConverter\Split\Splitter */ protected function createSplitter(string $className, string $source): Splitter { assert(is_subclass_of($className, Splitter::class)); return new $className($source); } /** * Handles all methods starting by `to*` * * @param string $methodName * * @return string * @throws \Jawira\CaseConverter\CaseConverterException */ protected function handleGluerMethod(string $methodName): string { switch ($methodName) { case 'toAda': $className = AdaCase::class; break; case 'toCamel': $className = CamelCase::class; break; case 'toCobol': $className = CobolCase::class; break; case 'toKebab': $className = KebabCase::class; break; case 'toLower': $className = LowerCase::class; break; case 'toMacro': $className = MacroCase::class; break; case 'toPascal': $className = PascalCase::class; break; case 'toSentence': $className = SentenceCase::class; break; case 'toSnake': $className = SnakeCase::class; break; case 'toTitle': $className = TitleCase::class; break; case 'toTrain': $className = TrainCase::class; break; case 'toUpper': $className = UpperCase::class; break; case 'toDot': $className = DotNotation::class; break; default: throw new CaseConverterException("Unknown method: $methodName"); break; } $gluer = $this->createGluer($className, $this->words, $this->forceSimpleCaseMapping); return $gluer->glue(); } /** * @param string $className Class name in string format * @param array $words Words to glue * @param bool $forceSimpleCaseMapping Should _Simple Case-Mapping_ be forced? * * @return \Jawira\CaseConverter\Glue\Gluer */ protected function createGluer(string $className, array $words, bool $forceSimpleCaseMapping): Gluer { assert(is_subclass_of($className, Gluer::class)); return new $className($words, $forceSimpleCaseMapping); } /** * Detected words extracted from original string. * * @return array */ public function toArray(): array { return $this->words; } /** * Forces to use Simple Case-Mapping * * Call this method if you want to maintain the behaviour before PHP 7.3 * * @see https://unicode.org/faq/casemap_charprop.html * @return \Jawira\CaseConverter\Convert */ public function forceSimpleCaseMapping(): self { $this->forceSimpleCaseMapping = true; return $this; } }
mit
ianstormtaylor/slate
site/examples/editable-voids.tsx
3581
import React, { useState, useMemo } from 'react' import { Transforms, createEditor, Descendant } from 'slate' import { Slate, Editable, useSlateStatic, withReact } from 'slate-react' import { withHistory } from 'slate-history' import { css } from '@emotion/css' import RichTextEditor from './richtext' import { Button, Icon, Toolbar } from '../components' import { EditableVoidElement } from './custom-types' const EditableVoidsExample = () => { const [value, setValue] = useState<Descendant[]>(initialValue) const editor = useMemo( () => withEditableVoids(withHistory(withReact(createEditor()))), [] ) return ( <Slate editor={editor} value={value} onChange={setValue}> <Toolbar> <InsertEditableVoidButton /> </Toolbar> <Editable renderElement={props => <Element {...props} />} placeholder="Enter some text..." /> </Slate> ) } const withEditableVoids = editor => { const { isVoid } = editor editor.isVoid = element => { return element.type === 'editable-void' ? true : isVoid(element) } return editor } const insertEditableVoid = editor => { const text = { text: '' } const voidNode: EditableVoidElement = { type: 'editable-void', children: [text], } Transforms.insertNodes(editor, voidNode) } const Element = props => { const { attributes, children, element } = props switch (element.type) { case 'editable-void': return <EditableVoid {...props} /> default: return <p {...attributes}>{children}</p> } } const unsetWidthStyle = css` width: unset; ` const EditableVoid = ({ attributes, children, element }) => { const [inputValue, setInputValue] = useState('') return ( // Need contentEditable=false or Firefox has issues with certain input types. <div {...attributes} contentEditable={false}> <div className={css` box-shadow: 0 0 0 3px #ddd; padding: 8px; `} > <h4>Name:</h4> <input className={css` margin: 8px 0; `} type="text" value={inputValue} onChange={e => { setInputValue(e.target.value) }} /> <h4>Left or right handed:</h4> <input className={unsetWidthStyle} type="radio" name="handedness" value="left" />{' '} Left <br /> <input className={unsetWidthStyle} type="radio" name="handedness" value="right" />{' '} Right <h4>Tell us about yourself:</h4> <div className={css` padding: 20px; border: 2px solid #ddd; `} > <RichTextEditor /> </div> </div> {children} </div> ) } const InsertEditableVoidButton = () => { const editor = useSlateStatic() return ( <Button onMouseDown={event => { event.preventDefault() insertEditableVoid(editor) }} > <Icon>add</Icon> </Button> ) } const initialValue: Descendant[] = [ { type: 'paragraph', children: [ { text: 'In addition to nodes that contain editable text, you can insert void nodes, which can also contain editable elements, inputs, or an entire other Slate editor.', }, ], }, { type: 'editable-void', children: [{ text: '' }], }, { type: 'paragraph', children: [ { text: '', }, ], }, ] export default EditableVoidsExample
mit
kivegun/HIS_Srilanka
application/modules/login/views/count.php
1576
<?php /** * Created by PhpStorm. * User: kivegun * Date: 11/30/16 * Time: 6:36 AM */ ?> <div style='position:absolute;width:90%;height:50px;border:2px solid red;text-align:center;background-color:#f1f1f1;'> Please try to login again in <span id='time'>15</span>sec. <div id='link'></div> </div> <script language='javascript'> var countdownfrom=15; var time = document.getElementById('time'); var currentsecond=parseInt(time.innerHTML); var t=setTimeout('display()',15000); countredirect(); var t1=null; function countredirect(){ if (currentsecond!=1){ currentsecond-=1 var time = document.getElementById('time'); time.innerHTML=currentsecond; t1=setTimeout('countredirect()',1000) ; } else{ var l = document.getElementById('link'); l.innerHTML= '<a id=\'link\' href=\'<?php echo base_url()."index.php/login?NEXT=" ?>\'>Login</a>'; clearTimeout(t1); t1=null; self.document.location='<?php echo base_url()."index.php/login?NEXT=" ?>'; return; } } </script>
mit
Greakz/TypeScriptReactTest
src/Components/Pages/ArticleDetails/ArticleDetails.state.ts
568
import { WebData } from '../../../ReduxCore/Util/webData'; import { ArticleFormState, createArticleFormState } from '../../../Evolve/Forms/ArticleForm'; import { Article } from '../../../Evolve/Entities/Article'; export interface ArticleDetailsState { editMode: boolean; saving: boolean; webData: WebData<Article>; form: ArticleFormState; } export function initArticleDetailsState(): ArticleDetailsState { return { editMode: false, saving: false, webData: {type: 'Loading'}, form: createArticleFormState() }; }
mit
dartpro13/e-governmentPitria
application/views/admin/content_list_surat_kelahiran.php
5311
<div class="right_col" role="main"> <div class=""> <div class="page-title"> <div class="title_left"> <h3>Surat Layanan Penduduk <small>/ List Surat Kelahiran</small></h3> </div> <div class="title_right"> <div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search"> <div class="input-group"> <input type="text" id="myInput" class="form-control" onkeyup="myFunction()" placeholder="Search for names.."> <span class="input-group-btn"> <button class="btn btn-default" type="button">Go!</button> </span> </div> </div> </div> </div> <div class="clearfix"></div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>e-Government <small>list surat kelahiran</small></h2> <ul class="nav navbar-right panel_toolbox"> <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Settings 1</a> </li> <li><a href="#">Settings 2</a> </li> </ul> </li> <li><a class="close-link"><i class="fa fa-close"></i></a> </li> </ul> <div class="clearfix"></div> </div> <div class="x_content"> <p class="text-muted font-13 m-b-30"> <!-- DataTables has most features enabled by default, so all you need to do to use it with your own tables is to call the construction function: <code>$().DataTable();</code> --> </p> <table id="datatable" class="table table-striped table-bordered"> <thead> <tr> <th>No.</th> <th>Nama Pemohon</th> <th>Tempat Tanggal Lahir</th> <th>Jenis Kelamin</th> <th>Pekerjaan</th> <th>Alamat</th> <th>Nama Ayah Kandung</th> <th>Nama Ibu Kandung</th> <th>Anak ke</th> <th>Tanggal Pembuatan</th> <th>Status</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $no=1; foreach ($surat as $row) { ?> <tr> <td><?= $no++;?></td> <td><?= $row->nama;?></td> <td><?= $row->tempat_tanggal_lahir;?></td> <td><?= $row->jenis_kelamin;?></td> <td><?= $row->pekerjaan;?></td> <td><?= $row->alamat;?></td> <td><?= $row->nama_ayah_kandung;?></td> <td><?= $row->nama_ibu_kandung;?></td> <td><?= $row->anak_ke;?></td> <td><?= $row->tanggal_pembuatan;?></td> <td><?= $row->status;?></td> <td> <?php if($row->status=="Di Setujui"){ $button='target="_blank" href="'; $button.=base_url(). 'index.php/admin/doprint_skl/'.$row->id_surat.'/"';; }else{ $button='href=""'; $button.='onClick="'; $button.="alert('Surat belum disetujui!')"; $button.='"'; } ?> <a <?=$button;?> style="background-color:cornflowerblue;color:white;padding:5px;border-radius:10px;">print</a><br/><br/> <a href="<?php echo base_url(). 'index.php/admin/update_surat_kelahiran/'.$row->id_surat; ?>" style="background-color:cornflowerblue;color:white;padding:5px;border-radius:10px;">update</a><br/><br/> <a href="<?php echo base_url(). 'index.php/action/hapus_surat_kelahiran/'.$row->id_surat; ?>" style="background-color:crimson;color:white;padding:5px;border-radius:10px;">delete</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <script> function myFunction() { // Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("datatable"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[1]; if (td) { if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script>
mit
hanucito/utn-fullstack
clase3/ejercicios/ejercicio1/model/api.js
1911
const readJSONCPS = require('read-json'); const writeJSONCPS = require('write-json'); const path = require('path'); const booksFile = path.resolve(__dirname, '../data/books.json'); const categoriesFile = path.resolve(__dirname, '../data/categories.json'); const writeJSON = function(file, data) { return new Promise(resolve => { writeJSONCPS(file, data, (err, res) => { if (err) throw err; resolve(res); }) }) } const readJSON = function(file, data) { return new Promise(resolve => { readJSONCPS(file, (err, res) => { if (err) throw err; resolve(res); }) }) } const fetchBooks = () => { return new Promise((resolve, reject) => readJSONCPS(booksFile, (error, books) => { if (error) { return reject(error); } resolve(books); })); }; const fetchCategories = () => { return new Promise((resolve, reject) => readJSONCPS(categoriesFile, (error, categories) => { if (error) { return reject(error); } resolve(categories); })); }; const createCategory = data => { return fetchCategories() .then(categories => { console.log(data) }) } const createBook = data => { return fetchBooks() .then(books => { var max = Math.max.apply(null, books.map(book => Number(book.id.substr(1)) )) data = Object.assign(data, { id: 'b' + (max + 1) }) books.push(data); return writeJSON(booksFile, books) .then(() => { return data; }) }) } const createCategory = data => { return fetchCategories() .then(categories => { var max = Math.max.apply(null, books.map(book => Number(book.id.substr(0)) )) data = Object.assign(data, { id: (max + 1) }) categories.push(data); return writeJSON(categoriesFile, categories) .then(() => { return data; }) }) } module.exports = { fetchBooks, fetchCategories, createBook, createCategory }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/xmltext/src/main/java/eclassxmlschemadictionary_2_0Simplified/impl/Eclassxmlschemadictionary_2_0SimplifiedFactoryImpl.java
3037
/** */ package eclassxmlschemadictionary_2_0Simplified.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import eclassxmlschemadictionary_2_0Simplified.ECLASSDICTIONARY; import eclassxmlschemadictionary_2_0Simplified.Eclassxmlschemadictionary_2_0SimplifiedFactory; import eclassxmlschemadictionary_2_0Simplified.Eclassxmlschemadictionary_2_0SimplifiedPackage; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class Eclassxmlschemadictionary_2_0SimplifiedFactoryImpl extends EFactoryImpl implements Eclassxmlschemadictionary_2_0SimplifiedFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static Eclassxmlschemadictionary_2_0SimplifiedFactory init() { try { Eclassxmlschemadictionary_2_0SimplifiedFactory theEclassxmlschemadictionary_2_0SimplifiedFactory = (Eclassxmlschemadictionary_2_0SimplifiedFactory)EPackage.Registry.INSTANCE.getEFactory(Eclassxmlschemadictionary_2_0SimplifiedPackage.eNS_URI); if (theEclassxmlschemadictionary_2_0SimplifiedFactory != null) { return theEclassxmlschemadictionary_2_0SimplifiedFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new Eclassxmlschemadictionary_2_0SimplifiedFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Eclassxmlschemadictionary_2_0SimplifiedFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case Eclassxmlschemadictionary_2_0SimplifiedPackage.ECLASSDICTIONARY: return createECLASSDICTIONARY(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ECLASSDICTIONARY createECLASSDICTIONARY() { ECLASSDICTIONARYImpl eclassdictionary = new ECLASSDICTIONARYImpl(); return eclassdictionary; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Eclassxmlschemadictionary_2_0SimplifiedPackage getEclassxmlschemadictionary_2_0SimplifiedPackage() { return (Eclassxmlschemadictionary_2_0SimplifiedPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static Eclassxmlschemadictionary_2_0SimplifiedPackage getPackage() { return Eclassxmlschemadictionary_2_0SimplifiedPackage.eINSTANCE; } } //Eclassxmlschemadictionary_2_0SimplifiedFactoryImpl
mit
gpslab/cqrs
src/Query/Handler/QuerySubscriber.php
530
<?php /** * GpsLab component. * * @author Peter Gribanov <info@peter-gribanov.ru> * @copyright Copyright (c) 2011, Peter Gribanov * @license http://opensource.org/licenses/MIT */ namespace GpsLab\Component\Query\Handler; interface QuerySubscriber { /** * Get called methods for subscribed queries. * * <code> * { * <query_name>: <method_name>, * } * </code> * * @return array<class-string, string> */ public static function getSubscribedQueries(): array; }
mit
selvasingh/azure-sdk-for-java
sdk/spring/azure-spring-boot/src/test/java/com/microsoft/azure/spring/autoconfigure/cosmos/domain/PersonRepository.java
369
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.spring.autoconfigure.cosmos.domain; import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; @Repository public interface PersonRepository extends CosmosRepository<Person, String> { }
mit
mcgivrer/generator-java-webapp
app/templates/admin/static/js/main.js
1935
var CUI = CUI || {}; // 后台数据接口根路径 CUI.baseUrl = '/'; // 后台数据接口地址配置 CUI.dataUrl = { 'list': 'user/list.json', 'pay': 'pay/list.json' }; // select 数据配置 CUI.optionsData = { 'status': [{ 'id': 1, 'name': '完成' }, { 'id': 2, 'name': '未完成' }] }; CUI.getUrl = function(k) { return this.dataUrl[k] ? (this.baseUrl + this.dataUrl[k]) : console.warn('ERR on read cfg ' + k); } requirejs.config({ baseUrl: '../js/lib', paths: { app: '../app', common: '../common', 'selectize':'../components/selectize/dist/js/standalone/selectize', 'select2':'../components/select2/select2', 'bootstrap-datepicker':'../components/bootstrap-datepicker/js/bootstrap-datepicker', 'bootstrap-daterangepicker':'../components/bootstrap-daterangepicker/daterangepicker', 'bootstrap-grid':'../components/bootstrap3-grid/script/simplePagingGrid-0.6.0.0', moment: '../components/moment/moment', jquery: '../components/jquery/jquery' }, shim: { 'jquery': { exports: 'jQuery' }, 'jquery.mockjax': { deps:['jquery'], exports: '$.mockjax' }, 'jquery.validate': { deps:['jquery'], exports: '$.fn.validate' }, 'bootstrap-datepicker': { deps:['jquery'], exports: '$.fn.datepicker' }, 'bootstrap-daterangepicker': { deps:['jquery','moment'], exports: '$.fn.daterangepicker' }, 'bootbox': { deps:['jquery'], exports: 'bootbox' }, 'handlebars': { exports: 'Handlebars' }, 'bootstrap3-grid': { deps:['jquery','handlebars'], exports: '$.fn.simplePagingGrid' } } });
mit
eleven41/skeddly-sdk-net
SkeddlySDK/Model/AssumeUserWithSamlRequest.cs
408
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Skeddly.Model { public class AssumeUserWithSamlRequest { public string SamlResponseBase64 { get; set; } public bool? IsAssumeOnSingleProvider { get; set; } public string IdentityProviderSrn { get; set; } public IEnumerable<string> ManagedPolicySrns { get; set; } } }
mit
benhardy/braintree-scala
src/main/scala/Plan.scala
1563
package net.bhardy.braintree.scala import net.bhardy.braintree.scala.util.NodeWrapper object Plan { sealed trait DurationUnit {} object DurationUnit { case object DAY extends DurationUnit case object MONTH extends DurationUnit case object UNRECOGNIZED extends DurationUnit case object UNDEFINED extends DurationUnit def fromString(from:String): DurationUnit = { from.toUpperCase match { case "DAY" => DAY case "MONTH" => MONTH case _ => UNRECOGNIZED } } } } class Plan(node: NodeWrapper) { val id = node.findString("id") val addOns = node.findAll("add-ons/add-on") map {new AddOn(_)} val merchantId = node.findString("merchant-id") val billingDayOfMonth = node.findInteger("billing-day-of-month") val billingFrequency = node.findInteger("billing-frequency") val createdAt = node.findDateTime("created-at") val currencyIsoCode = node.findString("currency-iso-code") val description = node.findString("description") val discounts = node.findAll("discounts/discount") map {new Discount(_)} val name = node.findString("name") val numberOfBillingCycles = node.findInteger("number-of-billing-cycles") val price = node.findBigDecimal("price") val trialPeriod = node.findBooleanOpt("trial-period").getOrElse(false) val trialDuration = node.findInteger("trial-duration") val trialDurationUnit = node.findStringOpt("trial-duration-unit"). map(Plan.DurationUnit.fromString). getOrElse(Plan.DurationUnit.UNDEFINED) val updatedAt = node.findDateTime("updated-at") }
mit
SkyGamesLT/skygames
cake/cake/tests/groups/xml.group.php
1904
<?php /* SVN FILE: $Id: xml.group.php 7848 2008-11-08 02:58:37Z renan.saddam $ */ /** * Xml Group test. * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * * Licensed under The Open Group Test Suite License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests * @package cake.tests * @subpackage cake.tests.groups * @since CakePHP(tm) v 1.2.0.4206 * @version $Revision: 7848 $ * @modifiedby $LastChangedBy: renan.saddam $ * @lastmodified $Date: 2008-11-07 20:58:37 -0600 (Fri, 07 Nov 2008) $ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ /** XmlGroupTest * * This test group will run view class tests (view, theme). * * @package cake.tests * @subpackage cake.tests.groups */ /** * XmlGroupTest class * * @package cake * @subpackage cake.tests.groups */ class XmlGroupTest extends GroupTest { /** * label property * * @var string 'All core views' * @access public */ var $label = 'All Xml based classes'; /** * AllCoreViewsGroupTest method * * @access public * @return void */ function XmlGroupTest() { TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'xml'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS .'rss'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS .'xml'); } } ?>
mit
YABhq/Quazar
src/Publishes/resources/commerce/plans/all.blade.php
1038
@extends('commerce-frontend::layouts.store') @section('store-content') <div class="row"> @foreach ($plans as $plan) <div class="col-md-3"> <div class="card card-default"> <div class="card-header text-center"> <span class="plan-title"><a href="{{ $plan->href }}">{{ $plan->name }}</a></span> </div> <div class="card-body text-center plan-details"> <span class="lead">$ {{ $plan->amount }} {{ strtoupper($plan->currency) }}/ {{ strtoupper($plan->interval) }}</span><br> <span class="plan-slogan">{{ $plan->slogan }}</span><br> <span class="plan-description">{{ $plan->description }}</span> </div> <div class="card-footer"> <a href="{{ $plan->href }}">Subscribe</a> </div> </div> </div> @endforeach </div> @endsection
mit
keepwalking1234/neocoin
src/rpcrawtransaction.cpp
21589
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "rpcserver.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "keystore.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (int64_t)tx.nTime)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } #ifdef ENABLE_WALLET Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid neocoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; assert(pwalletMain != NULL); pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<const CScriptID&>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } #endif Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid neocoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() #endif ); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type)); Value v = find_value(prevOut, "redeemScript"); if (!(v == Value::null)) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, STANDARD_SCRIPT_VERIFY_FLAGS, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node if (!AcceptToMemoryPool(mempool, tx, true, NULL)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
mit
fahrydgt/hotel_site
application/views/hotels/search_hotels.php
7754
<script> $(document).ready(function(){ get_results(); $("#name").keyup(function(){ event.preventDefault(); get_results(); }); $("#city").keyup(function(){ event.preventDefault(); get_results(); }); $("#phone").keyup(function(){ event.preventDefault(); get_results(); }); $("#email").keyup(function(){ event.preventDefault(); get_results(); }); function get_results(){ $.ajax({ url: "<?php echo site_url('Hotels/search');?>", type: 'post', data : jQuery('#form_search').serializeArray(), success: function(result){ $("#result_search").html(result); $(".dataTable").DataTable(); } }); } }); </script> <?php // echo '<pre>'; print_r($facility_list); die;?> <div class="row"> <div class="col-md-12"> <br> <div class="col-md-12"> <!--Flash Error Msg--> <?php if($this->session->flashdata('error') != ''){ ?> <div class='alert alert-danger ' id="msg2"> <a class="close" data-dismiss="alert" href="#">&times;</a> <i ></i>&nbsp;<?php echo $this->session->flashdata('error'); ?> <script>jQuery(document).ready(function(){jQuery('#msg2').delay(3000).slideUp(2000);});</script> </div> <?php } ?> <?php if($this->session->flashdata('warn') != ''){ ?> <div class='alert alert-success ' id="msg2"> <a class="close" data-dismiss="alert" href="#">&times;</a> <i ></i>&nbsp;<?php echo $this->session->flashdata('warn'); ?> <script>jQuery(document).ready(function(){jQuery('#msg2').delay(3000).slideUp(2000);});</script> </div> <?php } ?> <div class=""> <a href="<?php echo base_url($this->router->fetch_class().'/add');?>" class="btn btn-app "><i class="fa fa-plus"></i>Create New</a> <a href="<?php echo base_url($this->router->fetch_class());?>" class="btn btn-app "><i class="fa fa-search"></i>Search</a> </div> </div> <br><hr> <section class="content"> <div class=""> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Search </h3> </div> <!-- /.box-header --> <!-- form start --> <?php echo form_open("", 'id="form_search" class="form-horizontal"')?> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="col-md-3 control-label">Hotel Name<span style="color: red"></span></label> <div class="col-md-9"> <div class="input-group"> <span class="input-group-addon"><span class="fa fa-pencil"></span></span> <?php echo form_input('name', set_value('name'), 'id="name" class="form-control" placeholder="Search by Hotel Name"'); ?> </div> <span class="help-block"><?php echo form_error('name');?></span> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="col-md-3 control-label">City<span style="color: red"></span></label> <div class="col-md-9"> <div class="input-group"> <span class="input-group-addon"><span class="fa fa-pencil"></span></span> <?php echo form_input('city', set_value('city'), 'id="city" class="form-control" placeholder="Search by city Name"'); ?> </div> <span class="help-block"><?php echo form_error('city');?></span> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="col-md-3 control-label">Email<span style="color: red"></span></label> <div class="col-md-9"> <div class="input-group"> <span class="input-group-addon"><span class="fa fa-pencil"></span></span> <?php echo form_input('email', set_value('email'), 'id="email" class="form-control" placeholder="Search by Email Address"'); ?> </div> <span class="help-block"><?php echo form_error('email');?></span> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="col-md-3 control-label">Phone<span style="color: red"></span></label> <div class="col-md-9"> <div class="input-group"> <span class="input-group-addon"><span class="fa fa-pencil"></span></span> <?php echo form_input('phone', set_value('phone'), 'id="phone" class="form-control" placeholder="Search by Contact Number"'); ?> </div> <span class="help-block"><?php echo form_error('email');?></span> </div> </div> </div> </div> </div> <div class="panel-footer"> <button class="btn btn-default">Clear Form</button> <a id="search_btn" class="btn btn-primary pull-right"><span class="fa fa-search"></span>Search</a> </div> </div> </section> <?php echo form_close(); ?> </div> <div class="col-md-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Data Table With Full Features</h3> </div> <!-- /.box-header --> <div id="result_search" class="box-body"> </div> <!-- /.box-body --> </div> </div> </div>
mit
jjfeore/turingtweets
turingtweets/turingtweets/models/__init__.py
2211
from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import configure_mappers import zope.sqlalchemy # import or define all models here to ensure they are attached to the # Base.metadata prior to any initialization routines from .mymodel import Tweet # flake8: noqa # run configure_mappers after defining all of the models to ensure # all relationships can be setup configure_mappers() def get_engine(settings, prefix='sqlalchemy.'): return engine_from_config(settings, prefix) def get_session_factory(engine): factory = sessionmaker() factory.configure(bind=engine) return factory def get_tm_session(session_factory, transaction_manager): """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised. - When using scripts you should wrap the session in a manager yourself. For example:: import transaction engine = get_engine(settings) session_factory = get_session_factory(engine) with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) """ dbsession = session_factory() zope.sqlalchemy.register( dbsession, transaction_manager=transaction_manager) return dbsession def includeme(config): """ Initialize the model for a Pyramid app. Activate this setup using ``config.include('turingtweets.models')``. """ settings = config.get_settings() # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') session_factory = get_session_factory(get_engine(settings)) config.registry['dbsession_factory'] = session_factory # make request.dbsession available for use in Pyramid config.add_request_method( # r.tm is the transaction manager used by pyramid_tm lambda r: get_tm_session(session_factory, r.tm), 'dbsession', reify=True )
mit
max-winderbaum/maxcoin
src/qt/locale/bitcoin_fr_CA.ts
97250
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fr_CA" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Maxcoin</source> <translation>A propos de Maxcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Maxcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Maxcoin&lt;/b&gt; version</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Ce logiciel est en phase expérimentale. Distribué sous licence MIT/X11, voir le fichier COPYING ou http://www.opensource.org/licenses/mit-license.php. Ce produit comprend des logiciels développés par le projet OpenSSL pour être utilisés dans la boîte à outils OpenSSL (http://www.openssl.org/), un logiciel cryptographique écrit par Eric Young (eay@cryptsoft.com) et un logiciel UPnP écrit par Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Maxcoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Carnet d&apos;adresses</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Double-cliquez afin de modifier l&apos;adress ou l&apos;étiquette</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Créer une nouvelle adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copier l&apos;adresse surligné a votre presse-papier</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Maxcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ceux-ci sont vos adresses Maxcoin qui vous permettent de recevoir des paiements. Vous pouvez en donner une différente à chaque expédieur afin de savoir qui vous payent.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Maxcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Maxcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Supprimer</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Maxcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporter les données du carnet d&apos;adresses</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Maxcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your maxcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about Maxcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Maxcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Maxcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Maxcoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Maxcoin</source> <translation>&amp;A propos de Maxcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Maxcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Maxcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Maxcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Maxcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Maxcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Maxcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Maxcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Maxcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Maxcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Maxcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Maxcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Maxcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Maxcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Maxcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Maxcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Maxcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start maxcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Maxcoin-Qt help message to get a list with possible Maxcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Maxcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Maxcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Maxcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Maxcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Maxcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Maxcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Maxcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Maxcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Maxcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Maxcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Maxcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or maxcoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: maxcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: maxcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=maxcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Maxcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Maxcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Maxcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Maxcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Maxcoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Maxcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Maxcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
mit
raquelxmoss/learning_connect
db/migrate/20150423222044_delete_agreements.rb
321
class DeleteAgreements < ActiveRecord::Migration def up drop_table :agreements end def down create_table :agreements do |t| t.text :description t.belongs_to :connection t.belongs_to :course t.integer :price t.string :location t.timestamps null: false end end end
mit
MobilityLabs/pdredesign-server
app/assets/javascripts/client/inventories/MessageElementCtrl.js
596
(function() { 'use strict'; angular.module('PDRClient') .controller('MessageElementCtrl', MessageElementCtrl); MessageElementCtrl.$inject = ['$scope']; function MessageElementCtrl($scope) { var vm = this; vm.message = $scope.message; var kind = $scope.kind || 'Inventory'; vm.title = { 'welcome': 'Welcome Invite', 'reminder': 'Individual ' + kind + ' Reminder', }[vm.message.category] || 'General Message'; vm.icon = { 'welcome': 'fa-envelope-o', 'reminder': 'fa-clock-o', }[vm.message.category] || 'fa-envelope-o'; } })();
mit
dsii-2016-unirsm/dsii-2016-unirsm.github.io
p5/10print/michele/cell.js
2811
function Cell(x, y, up) { this.x = x; // coordinate x this.y = y; // coordinate y this.angle = up ? -HALF_PI : HALF_PI; // orientamento del triangolo this.edges = [true, true, true]; // array booleana usata per stabilire quali bordi saranno disegnati this.visited = false; // booleana usata per sapere se la cella è stata già visitata } // formula per disegnare cerchi con diametro casuale sui bordi della cella visitata Cell.prototype.highlight = function(pg) { var diam = random(50); pg.noStroke(); pg.fill(255, 255, 255, 100); for (var i = 0, l = this.edges.length; i < l; i += 1) { pg.ellipse( this.x + Cell.r * cos(this.angle - i * Cell.theta), this.y + Cell.r * sin(this.angle - i * Cell.theta), diam, diam ); } }; // formula per disegnare i bordi attivi Cell.prototype.display = function(pg) { pg.strokeWeight(this.visited ? 3 : 1); pg.stroke(this.visited ? color(255, 255, 255) : color(0, 130, 200)); for (var i = 0, l = this.edges.length; i < l; i += 1) { if (this.edges[i]) { pg.line( this.x + Cell.r*cos(this.angle - (i+0)%l * Cell.theta), this.y + Cell.r*sin(this.angle - (i+0)%l * Cell.theta), this.x + Cell.r*cos(this.angle - (i+1)%l * Cell.theta), this.y + Cell.r*sin(this.angle - (i+1)%l * Cell.theta) ); } } }; Cell.prototype.chooseNeighbor = function () { var index; var x, y; var list = []; // codice per trovare i neighbor disponibili for(var i = 0, l = 3; i < l; i += 1) { // codice per trovare la posizione dei neighbor x = this.x + Cell.r * cos(this.angle - Cell.theta * (i + 0.5)); y = this.y + Cell.r * sin(this.angle - Cell.theta * (i + 0.5)); // usare la posizione per trovare l'index dei neighbor index = Cell.findIndex(round(x), round(y)); // se il neighbor non è stato ancora visitato, viene aggiunto alla lista dei neighbor disponibili if (index && !cells[index].visited) { list.push(cells[index]); } } // se ci sono neighbor disponibili, ne viene scelto uno if (list.length > 0) { return list[floor(random(list.length))]; } }; Cell.findIndex = function (x, y) { // codice per individuare la posizione sulla griglia var i = floor(2*x/Cell.l)-2; var j = floor(y/Cell.h); // codice per trovare l'index sull'array delle celle se si trova su una posizione valida della griglia var index = i; if (i >= j && i <= Cell.cols-j && j >= 0 && j < Cell.rows) { for (var k = 0; k < j; k += 1) { index += Cell.cols - 2*k; } return index; } }; Cell.removeWalls = function (c, n) { var angle = atan2(n.y - c.y, n.x - c.x); angle = (angle + PI)%PI; var idx = floor(2 * angle / Cell.theta); c.edges[idx] = false; n.edges[idx] = false; };
mit
VladimirRadojcic/Master
BusinessProcessModelingTool/src/bp/text/box/ProcessTextBox.java
5794
package bp.text.box; import java.util.List; import bp.event.AttributeChangeListener; import bp.model.data.Activity; import bp.model.data.ActivityEvent; import bp.model.data.ConditionalActivityEvent; import bp.model.data.Edge; import bp.model.data.Element; import bp.model.data.ErrorActivityEvent; import bp.model.data.MessageActivityEvent; import bp.model.data.Process; import bp.model.data.SignalActivityEvent; import bp.model.data.Task; import bp.model.data.TimerActivityEvent; import bp.model.util.BPKeyWords; import bp.model.util.Controller; public class ProcessTextBox extends BlockTextBox { private Process process; public ProcessTextBox(final Process process, final TextBox owner) { super(BPKeyWords.PROCESS, process.getUniqueName(), owner); this.process = process; addDataListener(); addElementsListener(); setIndentationLevel(0); } public ProcessTextBox() { } protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) { if (value != null) { if (keyWord == BPKeyWords.UNIQUE_NAME) { setValue(value); textChanged(); } else if (keyWord == BPKeyWords.NAME || keyWord == BPKeyWords.DESCRIPTION || keyWord == BPKeyWords.DATA) { updateAttribute(keyWord, value); } } } protected void updateAttribute(final BPKeyWords keyWord, final Object value) { final AttributeTextBox attTextBox = getAttributeTextBox(keyWord); if (attTextBox != null) { attTextBox.setValue(value); textChanged(); } else { appendTextBox(new AttributeTextBox(keyWord, value, this)); textChanged(); } } private void addDataListener() { this.process.addAttributeChangeListener(new AttributeChangeListener() { @Override public Controller getController() { return Controller.TEXT; } @Override public void fireAttributeChanged(final BPKeyWords keyWord, final Object value) { dataAttributeChanged(keyWord, value); } }); } private void addElementsListener() { this.process.addElementsListener(new ElementsListener()); } public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public class ElementsListener extends bp.event.ElementsListener { public ElementsListener() { } @Override public void elementRemoved(final Element e) { List<TextBox> textBoxes = getTextBoxes(); int index = -1; TextBox textBox; String uniqueName = ""; for (int i = 0; i < textBoxes.size(); i++) { textBox = textBoxes.get(i); if (textBox instanceof ElementTextBox) { uniqueName = ((ElementTextBox) textBox).getElement().getUniqueName(); if (uniqueName.equals(e.getUniqueName())) index = i; } } if (index > -1) { System.out.println("Index: " + index + ", unique name: " + uniqueName); textBoxes.remove(index); } System.out.println("Text boxes size, after: " + textBoxes.size()); System.out.println("ProcessTextBox: elementRemoved(e)."); textChanged(); } @Override public void elementAdded(final Element e) { if (!getTextBoxes().contains(e)) { if (e instanceof Task) { appendTextBox(new TaskTextBox((Task) e, BPKeyWords.TASK, ProcessTextBox.this)); textChanged(); } else if (e instanceof Edge) { appendTextBox(new EdgeTextBox((Edge) e, BPKeyWords.EDGE, ProcessTextBox.this)); textChanged(); } else if (e instanceof ActivityEvent) { final ActivityEvent aEvent = (ActivityEvent) e; final Activity a = aEvent.getActivity(); for (final TextBox tb : getTextBoxes()) { if (tb instanceof TaskTextBox) { final TaskTextBox ttb = (TaskTextBox) tb; if (ttb.getTask().equals(a)) { if (aEvent instanceof MessageActivityEvent) { ttb.appendTextBox(new ActivityEventTextBox(aEvent, BPKeyWords.MESSAGE_ACTIVITY_EVENT, ttb)); } else if (aEvent instanceof ConditionalActivityEvent) { ttb.appendTextBox(new ActivityEventTextBox(aEvent, BPKeyWords.CONDITIONAL_ACTIVITY_EVENT, ttb)); } else if (aEvent instanceof TimerActivityEvent) { ttb.appendTextBox(new ActivityEventTextBox(aEvent, BPKeyWords.TIMER_ACTIVITY_EVENT, ttb)); } else if (aEvent instanceof SignalActivityEvent) { ttb.appendTextBox(new ActivityEventTextBox(aEvent, BPKeyWords.SIGNAL_ACTIVITY_EVENT, ttb)); } else if (aEvent instanceof ErrorActivityEvent) { ttb.appendTextBox(new ActivityEventTextBox(aEvent, BPKeyWords.ERROR_ACTIVITY_EVENT, ttb)); } textChanged(); } } } } } } } }
mit
Episerver-trainning/episerver6r2_sso
Templates/AlloyTech/Units/Placeable/DateTimePicker.ascx.cs
6241
#region Copyright // Copyright © EPiServer AB. All rights reserved. // // This code is released by EPiServer AB under the Source Code File - Specific License Conditions, published August 20, 2007. // See http://www.episerver.com/Specific_License_Conditions for details. #endregion using System; using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using EPiServer.Globalization; namespace EPiServer.Templates.AlloyTech.Units.Placeable { /// <summary> /// Code behind class for DateTimePicker control /// Note: This control utilize AJAX toolkit control so ScriptManager should be registered on the page to use this control /// </summary> [ControlValueProperty("Text"), ValidationProperty("Text")] public partial class DateTimePicker : UserControlBase { #region Properties /// <summary> /// Gets or sets the DatePiker TextBox text. This property is used as Validation Property /// </summary> /// <value>The text.</value> public string Text { get { return DateTextBox.Text; } set { DateTextBox.Text = value; } } /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public DateTime Value { get { return GetValue(); } set { SetValue(value); } } /// <summary> /// Gets the input control. /// </summary> /// <value>The input.</value> public WebControl Input { get { return DateTextBox; } } /// <summary> /// Gets the current language. /// </summary> /// <value>The language.</value> public static string Language { get { return ContentLanguage.PreferredCulture.IetfLanguageTag; } } #endregion #region EventHandlers /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); SelectHours.Items.Clear(); for (int i = 0; i <= 23; i++) { SelectHours.Items.Add(new ListItem(i.ToString() ,i.ToString())); } SelectMinutes.Items.Clear(); for (int i = 0; i <= 55; i=i+5) { SelectMinutes.Items.Add(new ListItem(i.ToString("D2"), i.ToString())); } Page.Header.Controls.Add(CreateCSSLink(Page.ResolveUrl("~/Templates/AlloyTech/scripts/jquery/jquery.ui.datepicker.custom.theme.css"))); } #endregion #region Helpers /// <summary> /// Sets the value. /// </summary> /// <param name="value">The value.</param> private void SetValue(DateTime value) { //Initialize DatePicker text box switch (this.CurrentPage.LanguageBranch.ToUpperInvariant()) { case "EN": DateTextBox.Text = value.ToString("MM/dd/yyyy"); break; case "SV": DateTextBox.Text = value.ToString("yyyy/MM/dd"); break; default: DateTextBox.Text = value.ToString("MM/dd/yyyy"); break; } //Initialize Hour selector drop down string hourValue = value.Hour.ToString(); SelectHours.ClearSelection(); ListItem hourSelected = SelectHours.Items.Cast<ListItem>().FirstOrDefault(item => String.Equals(item.Value, hourValue, StringComparison.OrdinalIgnoreCase)); if (hourSelected != null) { hourSelected.Selected = true; } else { ListItem newHourItem = new ListItem(hourValue, hourValue); SelectHours.Items.Add(newHourItem); newHourItem.Selected = true; } //Initialize Minute selector drop down string minuteValue = value.Minute.ToString(); SelectMinutes.ClearSelection(); ListItem minutesSelected = SelectMinutes.Items.Cast<ListItem>().FirstOrDefault(item => String.Equals(item.Value, minuteValue, StringComparison.OrdinalIgnoreCase)); if (minutesSelected != null) { minutesSelected.Selected = true; } else { ListItem newMinuteItem = new ListItem(minuteValue, minuteValue); SelectMinutes.Items.Add(newMinuteItem); newMinuteItem.Selected = true; } } /// <summary> /// Gets the current DateTimePicker DateTime value. /// </summary> /// <returns></returns> private DateTime GetValue() { DateTime dateValue = new DateTime(); try { dateValue = DateTime.Parse(DateTextBox.Text); } catch (FormatException) {} DateTime dateTimeValue = new DateTime(dateValue.Year, dateValue.Month, dateValue.Day, int.Parse(SelectHours.SelectedValue), int.Parse(SelectMinutes.SelectedValue), 0); return dateTimeValue; } /// <summary> /// Create a HtmlLink element with attributes for a css file /// </summary> /// <param name="cssFilePath">Path to the css file to be included</param> /// <returns>A new HtmlLink element</returns> private HtmlLink CreateCSSLink(string cssFilePath) { HtmlLink linkTag = new HtmlLink(); linkTag.Attributes.Add("type", "text/css"); linkTag.Attributes.Add("rel", "stylesheet"); linkTag.Href = ResolveUrl(cssFilePath); return linkTag; } #endregion } }
mit
Fishdrowned/test-stuff
php/dynamic.traits/DynamicProperties/EmptyProperties.php
63
<?php namespace DynamicProperties; trait EmptyProperties { }
mit
matholroyd/tworgy-ruby
spec/spec_helper.rb
263
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rubygems' require 'tworgy-ruby' require 'tworgy-ruby-testing' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end
mit
legendvijay/quail
lib/assessments/imgAltNotPlaceHolder.js
295
/** * A wrapper for assessments that call a component to determine * the test outcome. */ 'use strict'; quail.imgAltNotPlaceHolder = function (quail, test, Case) { var options = { selector: 'img', attribute: 'alt' }; quail.components.placeholder(quail, test, Case, options); };
mit
jerrod/rbee
lib/vendor/unserialize.rb
7020
# License and Copyright {{{ # Copyright (c) 2003 Thomas Hurst <freaky@aagh.net> # # 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. # }}} # PHP serialize() and unserialize() workalikes # First Released: 2003-06-02 (1.0.0) # Prev Release: 2003-06-16 (1.0.1), by Thomas Hurst <tom@hur.st> # This Release: 2004-09-17 (1.0.2), by Thomas Hurst <tom@hur.st> # Switch all {}'s to explicit Hash.new's. # # These two methods should, for the most part, be functionally identical # to the respective PHP functions; # http://www.php.net/serialize, http://www.php.net/unserialize # # # string = PHP.serialize(mixed var[, bool assoc]) # Returns a string representing the argument in a form PHP.unserialize # and PHP's unserialize() should both be able to load. # # Array, Hash, Fixnum, Float, True/FalseClass, NilClass, String and Struct # are supported; as are objects which support the to_assoc method, which # returns an array of the form [['attr_name', 'value']..]. Anything else # will raise a TypeError. # # If 'assoc' is specified, Array's who's first element is a two value # array will be assumed to be an associative array, and will be serialized # as a PHP associative array rather than a multidimensional array. # # # # mixed = PHP.unserialize(string serialized, [hash classmap, [bool assoc]]) # Returns an object containing the reconstituted data from serialized. # # If a PHP array (associative; like an ordered hash) is encountered, it # scans the keys; if they're all incrementing integers counting from 0, # it's unserialized as an Array, otherwise it's unserialized as a Hash. # Note: this will lose ordering. To avoid this, specify assoc=true, # and it will be unserialized as an associative array: [[key,value],...] # # If a serialized object is encountered, the hash 'classmap' is searched for # the class name (as a symbol). Since PHP classnames are not case-preserving, # this *must* be a .capitalize()d representation. The value is expected # to be the class itself; i.e. something you could call .new on. # # If it's not found in 'classmap', the current constant namespace is searched, # and failing that, a new Struct(classname) is generated, with the arguments # for .new specified in the same order PHP provided; since PHP uses hashes # to represent attributes, this should be the same order they're specified # in PHP, but this is untested. # # each serialized attribute is sent to the new object using the respective # {attribute}=() method; you'll get a NameError if the method doesn't exist. # # Array, Hash, Fixnum, Float, True/FalseClass, NilClass and String should # be returned identically (i.e. foo == PHP.unserialize(PHP.serialize(foo)) # for these types); Struct should be too, provided it's in the namespace # Module.const_get within unserialize() can see, or you gave it the same # name in the Struct.new(<structname>), otherwise you should provide it in # classmap. # # Note: StringIO is required for unserialize(); it's loaded as needed # module PHP def self.unserialize(string, classmap = nil, assoc = false) require 'stringio' string = StringIO.new(string) def string.read_until(char) val = '' while (c = self.read(1)) != char val << c end val end classmap ||= Hash.new do_unserialize(string, classmap, assoc) end private def self.do_unserialize(string, classmap, assoc) val = nil # determine a type type = string.read(2)[0,1] case type when 'a' # associative array, a:length:{[index][value]...} count = string.read_until('{').to_i val = vals = Array.new count.times do |i| vals << [do_unserialize(string, classmap, assoc), do_unserialize(string, classmap, assoc)] end string.read(1) # skip the ending } unless assoc # now, we have an associative array, let's clean it up a bit... # arrays have all numeric indexes, in order; otherwise we assume a hash array = true i = 0 vals.each do |key,value| if key != i # wrong index -> assume hash array = false break end i += 1 end if array vals.collect! do |key,value| value end else val = Hash.new vals.each do |key,value| val[key] = value end end end when 'O' # object, O:length:"class":length:{[attribute][value]...} # class name (lowercase in PHP, grr) len = string.read_until(':').to_i + 3 # quotes, seperator klass = string.read(len)[1...-2].capitalize.intern # read it, kill useless quotes # read the attributes attrs = [] len = string.read_until('{').to_i len.times do attr = (do_unserialize(string, classmap, assoc)) attrs << [attr.intern, (attr << '=').intern, do_unserialize(string, classmap, assoc)] end string.read(1) val = nil # See if we need to map to a particular object if classmap.has_key?(klass) val = classmap[klass].new elsif Struct.const_defined?(klass) # Nope; see if there's a Struct classmap[klass] = val = Struct.const_get(klass) val = val.new else # Nope; see if there's a Constant begin classmap[klass] = val = Module.const_get(klass) val = val.new rescue NameError # Nope; make a new Struct classmap[klass] = val = Struct.new(klass.to_s, *attrs.collect { |v| v[0].to_s }) end end attrs.each do |attr,attrassign,v| val.__send__(attrassign, v) end when 's' # string, s:length:"data"; len = string.read_until(':').to_i + 3 # quotes, separator val = string.read(len)[1...-2] # read it, kill useless quotes when 'i' # integer, i:123 val = string.read_until(';').to_i when 'd' # double (float), d:1.23 val = string.read_until(';').to_f when 'N' # NULL, N; val = nil when 'b' # bool, b:0 or 1 val = (string.read(2)[0] == ?1 ? true : false) else raise TypeError, "Unable to unserialize type '#{type}'" end val end end
mit
chenjsh36/ThreeJSForFun
threejs_gallary/front/src/script/canvas_catchfish_game.js
21880
var Bubbles = require('./canvas_catchfish_bubbles.js'); // require('./canvas_catchfish_fish.js'); // 变量定义--------------------------------------------------- var bubble1, bubble2, bubble3 ; var scene, camera, renderer, stats, gui ; var geometry, material, cube, line; var ambientLight; var loader; var fish; var fishActive; var fishMixer; var fishActiveMixer; var ifFishActive = false; var $fishHider = $('#fish-hider'); var $fishCatcher = $('#fish-catcher'); var $fishCatcherLeft = $('#fish-catcher-left'); var $fishCatcherRight = $('#fish-catcher-right'); var ifFishCatcherActive = false; var ifFishCatch = false; var fishStatus = 'swim'; // ['swim', 'catch', 'die']; var fishBow; var fishBowMixer; // 鱼竿摇晃变量 var catcherTimeHandle; var catcherPicList = []; var catcherPicCur = 0; var catcherReady = true; // 船动画 var shipTimeHandle; var shipPicCur = 9; var shipPicList = []; var $ship = $('#ship'); // GLTF 文件数据 var fishFile; var fishActiveFile; var fishBowFile; var $fishCatcher2 = $('#fish-catcher2'); var clock = new THREE.Clock(); var canvasContainer = document.getElementById('webgl-container'); // 产品变量 var $productPage = $('#product-page'); var $product = $('#product-page .product'); var $caseShake = $('#product-page .case-shake'); var $caseOpen = $('#product-page .case-open'); var $buyBtn = $('#product-page .buy-btn'); var shakeCaseAnim; var openCaseAnim; imgData = []; // 变量定义--------------------------------------------------- // 函数定义------------------------------------------- function init() { var size = 500, step = 50, geometry, i, j ; var scalePoint = 1; var animation; var animations; //- Stats // stats = new Stats(); // document.body.appendChild(stats.dom); //- 创建场景 scene = new THREE.Scene(); //- 创建相机 camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000000 ); camera.position.z = -2000; camera.position.y = 100; camera.position.x = 0; camera.lookAt(scene.position); //- 渲染 renderer = new THREE.WebGLRenderer({antialias: false, alpha: true}); //- renderer.setClearColor( 0xffffffff ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.domElement.className = 'webgl-container'; canvasContainer.appendChild(renderer.domElement); //- 平面坐標系 // var CoSystem = new THREEex.CoSystem(500, 50, 0x000000); // line = CoSystem.create(); // scene.add(line); //- gltf 3d模型导入 // 挣扎的鱼 fishActive = fishActiveFile.scene; fishActive.position.set(0, 0, 0); fishActive.position.set(0, 0, -280); fishActive.rotation.z = -Math.PI / 16; fishActive.scale.set(1, 1, 1); animations = fishActiveFile.animations; if (animations && animations.length) { fishActiveMixer = new THREE.AnimationMixer(fishActive); for (i = 0; i < animations.length; i++) { animation = animations[i]; fishActiveMixer.clipAction(animation).play(); } } // 游动的鱼 scalePoint = .9; fish = fishFile.scene; fish.position.set(0, 0, -280); fish.rotation.z = -Math.PI / 16; fish.scale.set(scalePoint, scalePoint, scalePoint); animations = fishFile.animations; if (animations && animations.length) { fishMixer = new THREE.AnimationMixer(fish); for (i = 0; i < animations.length; i++) { animation = animations[i]; fishMixer.clipAction(animation).play(); } } scene.add( fish ); showSwimFish() // 托盘 fishBow = fishBowFile.scene; fishBow.position.set(0, -400, 0); fishBow.rotation.x = -Math.PI / 16; fishBow.scale.set(scalePoint, scalePoint, scalePoint); animations = fishBowFile.animations; if (animations && animations.length) { fishBowMixer = new THREE.AnimationMixer(fishBow); for (i = 0; i < animations.length; i++) { animation = animations[i]; fishBowMixer.clipAction(animation).play(); } } //- 环境灯 ambientLight = new THREE.AmbientLight(0xffffff); scene.add(ambientLight); //- 直射灯 //- var directionalLight = new THREE.DirectionalLight( 0xdddddd ); //- directionalLight.position.set( 0, 0, 1 ).normalize(); //- scene.add( directionalLight ); //- 点灯 //- var light = new THREE.PointLight(0xFFFFFF); //- light.position.set(50000, 50000, 50000); //- scene.add(light); //- 绑定窗口大小,自适应 var threeexResize = new THREEex.WindowResize(renderer, camera); //- threejs 的控制器 // var controls = new THREE.OrbitControls( camera, renderer.domElement ); // controls.target = new THREE.Vector3(0,15,0); //- controls.maxPolarAngle = Math.PI / 2; //- controls.addEventListener( 'change', function() { renderer.render(scene, camera); } ); // add this only if there is no animation loop (requestAnimationFrame) $fishHider.on('click', function() { $fishHider.hide(); $fishCatcher.removeClass('ready'); if (ifFishCatcherActive === true) return; ifFishCatcherActive = true; // http://api.jquery.com/animate/ // $(".test").animate({ whyNotToUseANonExistingProperty: 100 }, { // step: function(now,fx) { // $(this).css('-webkit-transform',"translate3d(0px, " + now + "px, 0px)"); // }, // duration:'slow' // },'linear'); $fishCatcher.animate({ bottom: '0%', }, { step: function(now, fx) { var begin = 62; var end = 0; var percent = 1 - (-62 - now) / -62; var sub = 0.2 * percent; var cur = 1 + sub; $(this).css({ '-webkit-transform': 'translate(-50%, 0%) scale(' + cur + ', ' + cur + ')', 'transform': 'translate(-50%, 0%) scale(' + cur + ', ' + cur + ')' }) }, duration: 200, easing: 'linear', done: function() { // console.log('catch fish!!!'); // $fishCatcher2.show(); // $fishCatcher.hide(); // 渔网到达鱼的位置开始摇晃 fishStatus = 'catch'; TWEEN.removeAll(); var left = new TWEEN.Tween(fishActive.position) .to({ x: -250 }, 200) var leftToMiddle = new TWEEN.Tween(fishActive.position) .to({ x: 0 }, 500) var left2 = new TWEEN.Tween(fishActive.position) .to({ x: -150 }, 300) var right2 = new TWEEN.Tween(fishActive.position) .to({ x: 380 }, 300) var rightToMiddle = new TWEEN.Tween(fishActive.position) .to({ x: 0 }, 500) var right = new TWEEN.Tween(fishActive.position) .to({ x: 300 }, 800) // leftToMiddle.chain(left); // right.chain(leftToMiddle); // left.chain(leftToMiddle); // rightToMiddle.chain(left); // var circle = right.chain(rightToMiddle); right2.chain(rightToMiddle); left2.chain(right2); leftToMiddle.chain(left2); var circle = left.chain(leftToMiddle); circle.start(); new TWEEN.Tween(this) .to({}, 1000 * 2) .onUpdate(function() { render(); }) .start(); // showCatcherShade(); showCatcherShade2(); } }); }) initProduct(); } function showSwimFish() { console.log('showSwimFish####!!'); var curx = fish.position.x; var cury = fish.position.y; var top = new TWEEN.Tween({i: cury}) .to({ i: 40 }, 1000) .delay(3000) // .onStart(function() { // this.i = fish.position.y; // console.log(this.i, fish.position.y); // }) .onUpdate(function() { fish.position.y = this.i; }) .easing(TWEEN.Easing.Exponential.InOut) var bottom = new TWEEN.Tween({i: cury}) .to({ i: -40 }, 1000) .delay(3000) // .onStart(function() { // this.i = fish.position.y; // }) .onUpdate(function() { fish.position.y = this.i; }) .easing(TWEEN.Easing.Exponential.InOut) var left = new TWEEN.Tween({i: curx}) .to({ i: -40 }, 1000) .delay(3000) // .onStart(function() { // this.i = fish.position.x; // }) .onUpdate(function() { fish.position.x = this.i; }) .easing(TWEEN.Easing.Exponential.InOut) var right = new TWEEN.Tween({i: curx}) .to({ i: 40 }, 1000) .delay(3000) // .onStart(function() { // this.i = fish.position.x; // }) .onUpdate(function() { fish.position.x = this.i; }) .easing(TWEEN.Easing.Exponential.InOut) var cartoon = [top, bottom, left, right]; var random = Math.floor(Math.random() * 4 - .0001) var cart = cartoon[random]; cart.onComplete(function() { showSwimFish(); }).start() } function animate() { requestAnimationFrame(animate); var now = Date.now(); if (fishStatus === 'catch') { fish && scene.remove(fish); fishActive && scene.add(fishActive); if (fishActiveMixer) { fishActiveMixer.update(clock.getDelta()) } } else if (fishStatus === 'swim') { fishActive && scene.remove(fishActive); fish && scene.add(fish); if (fishMixer) { fishMixer.update(clock.getDelta()) } } else if (fishStatus === 'die') { fishActive && scene.remove(fishActive); fish && scene.add(fish); fishBow && scene.add(fishBow); } if (fishBowMixer) { fishBowMixer.update(clock.getDelta()); } TWEEN.update(); camera.lookAt(scene.position); // stats.begin(); render(); // stats.end(); } //- 循环体-渲染 function render() { renderer.render( scene, camera ); } // 捕鱼结束 鱼竿下落 鱼掉下 托盘上升 function showCatcherEnd() { // 停止摇晃渔网 // $fishCatcher.removeClass('rotate'); // $fishCatcherLeft.removeClass('rotate'); // $fishCatcherRight.removeClass('rotate'); // 鱼状态改变 // $fishCatcher.show(); // $fishCatcher2.hide(); fishStatus = 'die'; TWEEN.removeAll(); new TWEEN.Tween(fish.rotation) .to({ x: Math.PI / 5 }, 2000) .easing(TWEEN.Easing.Exponential.InOut) .start(); new TWEEN.Tween(fishBow.position) .to({ y: -200 }, 2000) .easing(TWEEN.Easing.Exponential.InOut) .start(); new TWEEN.Tween(this) .to({}, 1000 * 2) .onUpdate(function() { render(); }) .onComplete(function() { endGame(); }) .start(); // 气泡和背景鱼群消失 $('#fishtank').animate({opacity: 0}, 300); $('#bubbles').animate({opacity: 0}, 300, function() { bubble1.stop(); }) $('#bubbles').animate({opacity: 0}, 300, function() { bubble2.stop(); }) $('#bubbles').animate({opacity: 0}, 300, function() { bubble3.stop(); }) $fishCatcher.animate({bottom: '-100%'}, 300, 'swing', function() { ifFishCatcherActive = false; }) } function endGame() { $('#webgl-container').addClass('scale'); setTimeout(function() { showProduct(1000); $('#webgl-container').animate({ opacity: 0 }, 1000, function() { console.log('remove '); $('#webgl-container').css({ display: 'none' }) }); }, 1000); } // 加载图片 function preLoadImg(url) { var def = $.Deferred(); var img = new Image(); img.src = url; if (img.complete) { def.resolve({ img: img, url: url }) } img.onload = function() { def.resolve({ img: img, url: url }); } img.onerror = function() { def.resolve({ img: null, url: url }) } return def.promise(); } // 加载单张图片 function loadImage(url, callback) { var img = new Image(); //创建一个Image对象,实现图片的预下载 img.src = url; if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数 callback.call(img); return; // 直接返回,不用再处理onload事件 } img.onload = function () { //图片下载完毕时异步调用callback函数。 callback.call(img);//将回调函数的this替换为Image对象 }; } // 加载所有图片 function loadAllImage(imgList) { var defList = []; var i = 0; var len; var def = $.Deferred(); for (i = 0, len = imgList.length; i < len; i++) { defList[i] = preLoadImg(imgList[i]) } $.when.apply(this, defList) .then(function() { var retData = Array.prototype.slice.apply(arguments); def.resolve(retData); }) return def.promise(); } // 隐藏加载 function hideLoading() { $('#loading').hide(); } // 3d模型def 加载 function loadGltf(url) { var def = $.Deferred(); var loader = new THREE.GLTFLoader(); loader.setCrossOrigin('https://ossgw.alicdn.com'); loader.load(url, function(data) { def.resolve(data); }) return def.promise(); } // 加载所有3d模型 function loadAllGltf(list) { var defList = []; var i = 0; var len; var def = $.Deferred(); for (i = 0, len = list.length; i < len; i++) { defList[i] = loadGltf(list[i]) } $.when.apply(this, defList) .then(function() { var retData = Array.prototype.slice.apply(arguments); def.resolve(retData); }) return def.promise(); } // 加载两条鱼 function loadFishGltf() { var def = $.Deferred(); // var fishurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/03807648cf70d99a7c1d3d634a2d4ea3.gltf'; // var fishActiveurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/bb90ddfe2542267c142e892ab91f60ad.gltf'; var fishurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/b6dd694e5a9945e4f7c16867e9909f3c.gltf'; var fishActiveurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/645064d03c9be7cfa980c76886dbddba.gltf'; var fishBowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/c5e934aae17373e927fe98aaf1f71767.gltf' $.when(loadGltf(fishurl), loadGltf(fishActiveurl), loadGltf(fishBowUrl)) .then(function(fishData, fishActiveData, fishBowData) { fishFile = fishData; fishActiveFile = fishActiveData; fishBowFile = fishBowData; def.resolve([fishurl, fishActiveurl, fishBowUrl]); }) return def.promise(); } // 补零 function prefixInteger(num, n) { return (Array(n).join(0) + num).slice(-n); } // 获取鱼竿摇摆的动画数组 function getFlyCatcherPicList() { var picPre = '/threejs/static/img/yuwang/'; var picNum = 75; var i = 0; var retList = []; for (; i < picNum; i++) { retList.push(picPre + 'YW0' + prefixInteger(i, 3) + '.png') } return retList; } // 获取船的动画数组 function getFlyShipPicList() { var picPre = '/threejs/static/img/ship/'; var picNum = 72; var i = 9; var retList = []; for (; i < picNum; i++) { retList.push(picPre + 'chuan0' + prefixInteger(i, 3) + '.png') } return retList; } // 鱼竿摇晃动画 function showCatcherShade() { var url = ''; clearTimeout(catcherTimeHandle); if (catcherPicCur < catcherPicList.length) { url = 'url("' + catcherPicList[catcherPicCur] + '")'; // console.log('showCatcherShade:', url); $fishCatcher2.css('background-image', url); // $fishCatcher2.css('background-size','cover'); catcherPicCur++; catcherTimeHandle = setTimeout(showCatcherShade, 2000 / 76); } else { catcherPicCur = 0; showCatcherEnd(); } } function showCatcherShade2() { // http://api.jquery.com/animate/ // $(".test").animate({ whyNotToUseANonExistingProperty: 100 }, { // step: function(now,fx) { // $(this).css('-webkit-transform',"translate3d(0px, " + now + "px, 0px)"); // }, // duration:'slow' // },'linear'); catcherRotate(25, 200, 'swing') .then(catcherRotate(0, 500, 'linear')) .then(catcherRotate(15, 300, 'linear')) .then(catcherRotate(-20, 300, 'linear')) .then(catcherRotate(0, 500, 'linear', showCatcherEnd)); } function catcherRotate(deg, time, easing, cb) { var def = $.Deferred(); $fishCatcher.animate({ asdfasdf: deg }, { step: function(now, fx) { $(this).css('-webkit-transform',"translate(-50%, 0%) scale(1, 1) rotateZ(" + now + "deg)"); $(this).css('transform',"translate(-50%, 0%) scale(1, 1) rotateZ(" + now + "deg)"); }, duration: time, easing: easing, done: function() { if (cb) { cb(); } def.resolve(); } }) return def.promise(); } // 船动画 function showShipFly() { var url = ''; clearTimeout(shipTimeHandle); if (shipPicCur < shipPicList.length) { url = 'url("' + shipPicList[shipPicCur] + '")'; // console.log('showShipFly:', url); $ship.css('background-image', url); // $ship.css('background-size','cover'); shipPicCur++; shipTimeHandle = setTimeout(showShipFly, 5000 / 72); } else { shipPicCur = 9; // showCatcherEnd(); } } // 产品函数 function initProduct() { var winSize = { width: $(window).width(), height: $(window).height() }; var buyBtnW = winSize.width * .4; var buyBtnH = 84 * buyBtnW / 346; var buyBtnBottom = 50; $buyBtn.css({ height: buyBtnH + 'px', width: buyBtnW + 'px', bottom: buyBtnBottom + 'px', 'margin-left': (-buyBtnW / 2) + 'px' }) var caseW = winSize.width * .8; var caseH = 638 * caseW / 640; var caseBottom = buyBtnBottom + buyBtnH + 50; $caseShake.css({ height: caseH + 'px', width: caseW + 'px', 'margin-left': (-caseW / 2) + 'px', bottom: caseBottom + 'px' }) $caseOpen.css({ height: caseH + 'px', width: caseW + 'px', 'margin-left': (-caseW / 2) + 'px', bottom: caseBottom + 'px' }) } function showProduct(duration) { shakeCase(); $productPage.fadeIn(duration); $caseShake.one('click', function() { openCase(); }) } function shakeCase() { var steps = 15; var width = $caseShake.width(); var backW = width * steps; var duration = .5 shakeCaseAnim = frameAnimation.anims($caseShake, backW, steps, duration, 0); shakeCaseAnim.start(); } function openCase() { var steps = 12; var width = $caseOpen.width(); var backW = width * steps; var duration = 1; shakeCaseAnim.stop(); $caseShake.hide(); $caseOpen.show(); console.log('openCase:', width, backW, steps); openCaseAnim = frameAnimation.anims($caseOpen, backW, steps, duration, 1); openCaseAnim.start(); } // 函数定义------------------------------------------- // 执行-------------------------------------- var waitImgList = [ // '/threejs/static/img/上下云透明', // '/threejs/static/img/canvas_ship.png', '/threejs/static/img/canvas_yuwang1.png', '/threejs/static/img/canvas_yuwang1.png', '/threejs/static/img/canvas_yuwang2.png', '/threejs/static/img/canvas_yuwang3.png', '/threejs/static/img/yuwang/YW0000.png', '/threejs/static/img/ship/chuan0045.png' ]; // catcherPicList = getFlyCatcherPicList(); // shipPicList = getFlyShipPicList(); loadAllImage(waitImgList.concat(catcherPicList, shipPicList)) .then(function(Imgdata) { imgData = Imgdata loadFishGltf() .then(function(gltfData) { hideLoading(); main(); }) }) function main() { var winsize = { width: window.innerWidth, height: window.innerHeight }; /* 气泡 */ bubble1 = new Bubbles({ canvasID: 'bubbles', sourcex: winsize.width / 3, sourcey: winsize.height - 30 }) bubble2 = new Bubbles({ canvasID: 'bubbles2', sourcex: winsize.width -30, sourcey: winsize.height / 2 }) bubble3 = new Bubbles({ canvasID: 'bubbles3', sourcex: 30, sourcey: winsize.height / 3 }) bubble1.start(); bubble2.start(); bubble3.start(); /* 气泡 */ // showShipFly(); $ship.animate({left: '100%'}, 4000); init(); animate(); } // main(); // 执行--------------------------------------
mit
tqcenglish/SoftStart
Golang/book/gobyexample/34_worker_pools/worker_pools.go
520
package main import "fmt" import "time" func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } // https://gobyexample.com/worker-pools func main() { jobs := make(chan int, 100) results := make(chan int, 100) // 开启线程池 for w := 1; w <= 3; w++ { go worker(w, jobs, results) } for j := 1; j <= 9; j++ { jobs <- j } close(jobs) for a := 1; a <= 9; a++ { <-results } }
mit
frc-862/SummerSirius
src/org/usfirst/frc862/sirius/subsystems/Pivot.java
6197
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc862.sirius.subsystems; import org.usfirst.frc862.jlib.collection.DoubleLookupTable; import org.usfirst.frc862.jlib.math.interp.Interpolator; import org.usfirst.frc862.jlib.math.interp.LinearInterpolator; import org.usfirst.frc862.sirius.Robot; import org.usfirst.frc862.sirius.RobotMap; import org.usfirst.frc862.sirius.commands.ManualPivotControl; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class Pivot extends Subsystem { private static final double ANGLE_EPSILON = 1.0; public static class AngleDistanceTable { public double distance; public double angle; } public static class PowerTableValue { public double angle; public double up_power; public double down_power; public double hold_power; public PowerTableValue() { } // Needed for serialization public PowerTableValue(double a, double u, double d, double h) { angle = a; up_power = u; down_power = d; hold_power = h; } } private Interpolator interplator; // Key = angle, value = associated powers private DoubleLookupTable<PowerTableValue> powerTable; public Pivot() { interplator = new LinearInterpolator(); powerTable = new DoubleLookupTable<>(Robot.configuration.pivotPowerTable.length); // TODO expose to smart dashboard for (PowerTableValue val : Robot.configuration.pivotPowerTable) { powerTable.put(val.angle, val); } } public PowerTableValue getPowerValues(double angle) { // find floor/ceiling values DoubleLookupTable<PowerTableValue>.DoubleValuePair floor = powerTable.floorEntry(angle); DoubleLookupTable<PowerTableValue>.DoubleValuePair ceil = powerTable.ceilingEntry(angle); if (ceil == null) { ceil = powerTable.lastEntry(); } if (floor == null) { floor = powerTable.firstEntry(); } // Pull angle and values from the ceil and floor double floorAngle = floor.getKey(); PowerTableValue floorValues = floor.getValue(); double ceilAngle = ceil.getKey(); PowerTableValue ceilValues = ceil.getValue(); // interpolate to position return new PowerTableValue(angle, interplator.interpolate(floorAngle, ceilAngle, angle, floorValues.up_power, ceilValues.up_power), interplator.interpolate(floorAngle, ceilAngle, angle, floorValues.down_power, ceilValues.down_power), interplator.interpolate(floorAngle, ceilAngle, angle, floorValues.hold_power, ceilValues.hold_power)); } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private final Encoder angleEncoder = RobotMap.pivotAngleEncoder; private final SpeedController angleMotor = RobotMap.pivotAngleMotor; private final DigitalInput hallEffect = RobotMap.pivotHallEffect; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new ManualPivotControl()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } public void checkHardStop() { // System.out.printf("We are at %f\n", angleEncoder.getDistance()); if (hallEffect.get() == false) { angleEncoder.reset(); } } public void moveToAngle(double angle) { PowerTableValue val = getPowerValues(angle); SmartDashboard.putNumber("Going to angle", angle); SmartDashboard.putNumber("At angle", getAngle()); if (atAngle(angle)) { SmartDashboard.putString("Direction", "hold"); SmartDashboard.putNumber("Power", val.hold_power); angleMotor.set(val.hold_power); } else if (angleEncoder.getDistance() > angle) { SmartDashboard.putString("Direction", "down"); SmartDashboard.putNumber("Power", val.down_power); angleMotor.set(val.down_power); } else { SmartDashboard.putString("Direction", "up"); SmartDashboard.putNumber("Power", val.up_power); angleMotor.set(val.up_power); } } public void hold() { PowerTableValue val = getPowerValues(angleEncoder.getDistance()); angleMotor.set(val.hold_power); } public boolean atAngle(double intakeAngle) { return Math.abs(angleEncoder.getDistance() - intakeAngle) < ANGLE_EPSILON; } public double getAngle() { return angleEncoder.getDistance(); } public void setPower(double v) { angleMotor.set(v); } public void resetAngleEncoder() { angleEncoder.reset(); } public boolean atHardStop() { return (hallEffect.get() == false); } public void up() { PowerTableValue val = getPowerValues(getAngle()); angleMotor.set(val.up_power); } public void down() { PowerTableValue val = getPowerValues(getAngle()); angleMotor.set(val.down_power); } }
mit
infochimps-customers/chimps
lib/chimps/utils/uses_curl.rb
1108
module Chimps module Utils # A module which defines methods to interface with +curl+ via a # system call. module UsesCurl def curl_program `which curl`.chomp end # Curl invocations (specifically those that do S3 HTTP POST) are # sometimes sensitive about the order of parameters. Instead of # a Hash we therefore take an Array of pairs here. # # @param [Array<Array<String>>] array # @return [String] def curl_params params params.map do |param, value| "-F #{param}='#{value}'" end.join(' ') end def curl url, options={} options = {:method => "GET", :output => '/dev/null', :params => []}.merge(options) progress_meter = Chimps.verbose? ? '' : '-s -S' command = "#{curl_program} #{progress_meter} -X #{options[:method]} -o #{options[:output]}" command += " #{curl_params(options[:params])}" unless options[:params].empty? command += " '#{url}'" Chimps.log.info(command) system(command) end end end end
mit
eturino/prime_challenge
lib/prime_challenge/matrix.rb
528
module PrimeChallenge class Matrix attr_reader :prime_numbers def initialize(prime_numbers) @prime_numbers = prime_numbers end def call [header_row].concat(body_rows) end private def header_row @header_row ||= [''].concat prime_numbers end def body_rows @mult_matrix_body_rows ||= prime_numbers.map do |prime| [prime].concat mult_primes_with prime end end def mult_primes_with(n) prime_numbers.map { |e| e * n } end end end
mit
LINKIWI/react-elemental
src/components/alert.js
2357
import PropTypes from 'prop-types'; import React from 'react'; import Spacing from 'components/spacing'; import Text from 'components/text'; import Clear from 'icons/clear'; import { colors } from 'styles/color'; import noop from 'util/noop'; // Mapping of alert types to their corresponding background and text colors const typeColorMap = { info: { color: colors.blue, background: colors.blueLight, }, success: { color: colors.green, background: colors.greenLight, }, warn: { color: colors.yellow, background: colors.yellowLight, }, error: { color: colors.red, background: colors.redLight, }, }; // Mapping of alert types to their corresponding text sizes. const textSizeMap = { alpha: 'iota', beta: 'kilo', }; // Mapping of alert types to their container padding values. const paddingMap = { alpha: '16px 22px', beta: '10px 15px', }; /** * Educational status alerts. */ const Alert = ({ type, size, title, message, dismissible, style: overrides, onDismiss, ...proxyProps }) => { const { color, background } = typeColorMap[type]; const style = { backgroundColor: background, padding: paddingMap[size], ...overrides, }; const dismissStyle = { background: 'inherit', border: 0, cursor: 'pointer', float: 'right', }; const clearStyle = { fill: color, height: '16px', }; return ( <div style={style} {...proxyProps}> {dismissible && ( <button onClick={onDismiss} style={dismissStyle}> <Clear style={clearStyle} /> </button> )} <Text size={textSizeMap[size]} color={color} bold inline> {title} </Text> <Spacing size="small" left inline> <Text size={textSizeMap[size]} color={color} inline> {message} </Text> </Spacing> </div> ); }; Alert.propTypes = { type: PropTypes.oneOf(['info', 'success', 'warn', 'error']), size: PropTypes.oneOf(['alpha', 'beta']), title: PropTypes.string.isRequired, message: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, ]).isRequired, dismissible: PropTypes.bool, style: PropTypes.object, onDismiss: PropTypes.func, }; Alert.defaultProps = { type: 'info', size: 'alpha', dismissible: false, style: {}, onDismiss: noop, }; export default Alert;
mit
AIon-Gbbe/automatic_irigation_sistem_app
src/app/app.routing.ts
703
import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {AddNewBucketComponent} from "./add-new-bucket/add-new-bucket.component"; import {BucketDetailsComponent} from "./bucket-details/bucket-details.component"; const appRoutes: Routes = [ { path: 'adaugaGhiveci', component: AddNewBucketComponent }, { path: 'detaliiGhiveci', component: BucketDetailsComponent }, { path: '', // component: BucketDetailsComponent, redirectTo: '/detaliiGhiveci', pathMatch: 'full' } ]; export const routing_in_app: ModuleWithProviders = RouterModule.forRoot(appRoutes);
mit
garymabin/YGOMobile
apache-async-http-HC4/src/org/apache/http/HC4/conn/ManagedHttpClientConnection.java
2850
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.HC4.conn; import java.io.IOException; import java.net.Socket; import javax.net.ssl.SSLSession; import org.apache.http.HC4.HttpClientConnection; import org.apache.http.HC4.HttpInetConnection; /** * Represents a managed connection whose state and life cycle is managed by * a connection manager. This interface extends {@link HttpClientConnection} * with methods to bind the connection to an arbitrary socket and * to obtain SSL session details. * * @since 4.3 */ public interface ManagedHttpClientConnection extends HttpClientConnection, HttpInetConnection { /** * Returns connection ID which is expected to be unique * for the life span of the connection manager. */ String getId(); /** * Binds this connection to the given socket. The connection * is considered open if it is bound and the underlying socket * is connection to a remote host. * * @param socket the socket to bind the connection to. * @throws IOException */ void bind(Socket socket) throws IOException; /** * Returns the underlying socket. */ Socket getSocket(); /** * Obtains the SSL session of the underlying connection, if any. * If this connection is open, and the underlying socket is an * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of * that socket is obtained. This is a potentially blocking operation. * * @return the underlying SSL session if available, * {@code null} otherwise */ SSLSession getSSLSession(); }
mit
mg-wat/pum-lato-2014-2015
Lab2-2/app/src/main/java/pl/edu/wat/wel/fragmenttest/ListAdapter.java
2317
package pl.edu.wat.wel.fragmenttest; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Klasa Adaptera RecyclerView - dostarcza danych do wyświetlenia w sposob dynamiczny * Rozszerza adapter generyczny (uniwersalny), należy jednak wskazać, która klasa reprezentuje * renderowany element layoutu (ViewHolder) */ public class ListAdapter extends RecyclerView.Adapter<ListViewHolder> { /** * Lista w której przechwoujemy nasze dane (dowolne obiekty) */ private List<String> items; /** * Uzupełnienie listy przykładowymi danymi */ public ListAdapter() { this.items = new ArrayList<>(3); items.add("Pierwszy wiersz"); items.add("Drugi wiersz"); items.add("Trzeci wiersz"); items.add("Czwarty wiersz"); items.add("Piąty wiersz"); items.add("Szósty wiersz"); items.add("Siódmy wiersz"); items.add("Ósmy wiersz"); } /** * Dynamiczne renderowanie wiersza listy w danym viewGroup * @param viewGroup * @param i * @return */ @Override public ListViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { /** * LayoutInflater - z opisu w postaci XML tworzy elementy layoutu * Dodaje utworzony element do klasy odpowiedzialnej za wyświetlanie elementów listy */ View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false); return new ListViewHolder(view); } /** * Metoda odpowiedzialna za ustawienie wartości danego elementu listy * W przykładzie źródłem danych jest lista elementów typu String * @param listViewHolder * @param i */ @Override public void onBindViewHolder(ListViewHolder listViewHolder, int i) { // ustawienie wartości pola textView na i-tą wartość z listy listViewHolder.textView.setText(items.get(i)); } /** * Metoda informująca o ilości elementów dostępnych do wyświetlenia * @return */ @Override public int getItemCount() { return items.size(); } }
mit
linkeddatalab/statspace
src/main/java/at/tuwien/ldlab/statspace/util/SpecialEndpointList.java
4402
package at.tuwien.ldlab.statspace.util; import java.io.File; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class SpecialEndpointList { private ArrayList<SpecialEndpoint> arrEndpoint; public SpecialEndpointList(String path){ String sE, sQ, sW, sH, sR, sD, sF; arrEndpoint = new ArrayList<SpecialEndpoint>(); try{ File f = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(f); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("sparql"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; sE = eElement.getAttribute("endpoint"); if(eElement.hasAttribute("query")) sQ = eElement.getAttribute("query"); else sQ = ""; if(eElement.hasAttribute("widget")) sW = eElement.getAttribute("widget"); else sW = ""; if(eElement.hasAttribute("http")) sH = eElement.getAttribute("http"); else sH = ""; if(eElement.hasAttribute("removeDuplicate")) sR = eElement.getAttribute("removeDuplicate"); else sR = ""; if(eElement.hasAttribute("useDistinct")) sD = eElement.getAttribute("useDistinct"); else sD = ""; if(eElement.hasAttribute("findOtherValue")) sF = eElement.getAttribute("findOtherValue"); else sF = ""; arrEndpoint.add(new SpecialEndpoint(sE, sQ, sW, sH, sR, sD, sF)); } } }catch (Exception e) { System.out.println(e.toString()); } } public String getEndpoint(int i){return arrEndpoint.get(i).getEndpoint();} public String getEndpointForWidget(int i){return arrEndpoint.get(i).getEndpointForWidget();} public String getEndpointForQuery(int i){return arrEndpoint.get(i).getEndpointForQuery();} public boolean getHTTPRequest(int i){ if(arrEndpoint.get(i).getHTTPRequest().equalsIgnoreCase("Yes")) return true; else return false; } public boolean getRemoveDuplicate(int i){ if(arrEndpoint.get(i).getRemoveDuplicate().equalsIgnoreCase("Yes")) return true; else return false; } public String getUseDistinct(int i){ if(arrEndpoint.get(i).getDistinct().equalsIgnoreCase("No")) return "No"; else if(arrEndpoint.get(i).getDistinct().equalsIgnoreCase("Yes")) return "Yes"; else return ""; } public boolean getFindOtherValue(int i){ if(arrEndpoint.get(i).getFindOtherValue().equalsIgnoreCase("No")) return false; else return true; } public int getEndpointIndex(String sEndpoint){ sEndpoint = sEndpoint.toLowerCase(); int i; for(i=0; i<arrEndpoint.size(); i++){ if(sEndpoint.contains(arrEndpoint.get(i).getEndpoint().toLowerCase())|| sEndpoint.equals(arrEndpoint.get(i).getEndpointForQuery().toLowerCase())|| sEndpoint.equals(arrEndpoint.get(i).getEndpointForWidget().toLowerCase())) return i; } return -1; } public int getIndexQuery(String sQuery){ int i; for(i=0; i<arrEndpoint.size(); i++){ if(sQuery.equals(arrEndpoint.get(i).getEndpointForQuery())) return i; } return -1; } private class SpecialEndpoint{ private String endpoint; private String endpointForquery; private String endpointForwidget; private String http; private String remove; private String distinct; private String findOther; public SpecialEndpoint(String sE, String sQ, String sW, String sH, String sR, String sD, String sF){ endpoint = sE; endpointForquery = sQ; endpointForwidget = sW; http = sH; remove = sR; distinct = sD; findOther = sF; } public String getEndpoint(){return endpoint;} public String getEndpointForQuery(){return endpointForquery;} public String getEndpointForWidget(){return endpointForwidget;} public String getHTTPRequest(){return http;} public String getRemoveDuplicate(){return remove;} public String getDistinct(){return distinct;} public String getFindOtherValue(){return findOther;} } }
mit
coboosting/coboosting.github.io
js/ziyun.js
1570
/*! * Ziyun Javascript (http://www.ziyuntech.com) * Copyright 2016 Ziyun Technology, Inc. * Licensed under the MIT license */ // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); $(".scroll-top").fadeIn('1000', "easeInOutExpo"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); $(".scroll-top").fadeOut('1000', "easeInOutExpo"); } }); // Image Carousel $(function() { $('.carousel').carousel({ interval: 5000 //changes the speed }); }); // Panel Carousel $(function() { var owl = $(".panel-carousel"); owl.owlCarousel({ items: 3, //5 items above 1000px browser width itemsDesktop: [1024, 3], //4 items between 1000px and 901px itemsDesktopSmall: [900, 2], // betweem 900px and 601px itemsTablet: [600, 2], //2 items between 600 and 480 itemsMobile: [479, 1], //1 item between 480 and 0 pagination: true, // Show pagination navigation: false // Show navigation }); // Custom Navigation Events $(".btn-next").on('click', function() { owl.trigger('owl.next'); }) $(".btn-prev").on('click', function() { owl.trigger('owl.prev'); }) }); // jQuery mobile $(function() { //Enable swiping... $("#myCarousel").swiperight(function() { $(this).carousel('prev'); }); $("#myCarousel").swipeleft(function() { $(this).carousel('next'); }); });
mit
BartKrol/tvmanager
client/src/components/shows/shows.service.js
378
'use strict'; /*jshint esnext: true */ function popularShows($http) { var popularShows = $http.get('/api/v1/popular'). success(function(data, status, headers, config) { return data; }). error(function(data, status, headers, config) { }); return { popularShows: popularShows }; } popularShows.$inject = ['$http']; export default popularShows;
mit
SirKettle/myPortfolio
src/app/views/about/about.js
2036
'use strict'; var angular = require('angular'); var template = require('./about.html'); // sub components var headerComponent = require('../../components/header/header'); var footerComponent = require('../../components/footer/footer'); var socialNetworksComponent = require('../../components/socialNetworks/socialNetworks'); var blogComponent = require('../../components/blog/blog'); var contributionActivityComponent = require('../../components/contributionActivity/contributionActivity.js'); module.exports = angular.module('myApp.views.about', [ headerComponent.name, footerComponent.name, socialNetworksComponent.name, blogComponent.name, contributionActivityComponent.name ]) .directive('myViewAbout', function ( ) { var PLACEHOLDER_IMAGE_SRC = '/images/family_still.jpg'; var ANIMATED_IMAGE_SRC = '/images/family_animation.gif'; return { restrict: 'E', template: template, controller: 'MyViewAboutCtrl', replace: true, scope: { }, link: function (scope, elem, attrs, controller) { function _loadImages () { // The animated gif is expensive (3MB) so initially render the image // with a smaller jpg placeholder until we have loaded the gif. var animatedImage; // set placeholder image src scope._familyImageSrc = PLACEHOLDER_IMAGE_SRC; // create new image to load gif animatedImage = new Image(); animatedImage.src = ANIMATED_IMAGE_SRC; animatedImage.onload = function () { // switch the image src to the animated gif scope._familyImageSrc = ANIMATED_IMAGE_SRC; scope.$digest(); }; } function _calculateAge (birthday) { // birthday is a date var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); } scope._harrisonAge = _calculateAge(new Date('2010-07-13T03:20:00')); scope._elliotAge = _calculateAge(new Date('2012-07-15T17:30:00')); _loadImages(); } }; }) .controller('MyViewAboutCtrl', function ( ) { });
mit
knuu/competitive-programming
atcoder/abc/abc147_c.py
504
N = int(input()) notes = [] for _ in range(N): note = [] for _ in range(int(input())): x, y = map(int, input().split()) note.append((x-1, y)) notes.append(note) ans = 0 for state in range(1 << N): flag = True for i in range(N): if state >> i & 1: for x, y in notes[i]: flag &= (y == 1 and state >> x & 1) or (y == 0 and (state >> x & 1) == 0) if flag: ans = max(ans, sum(state >> i & 1 for i in range(N))) print(ans)
mit
twinh/wei
tests/unit/IsEmailTest.php
858
<?php namespace WeiTest; /** * @internal */ final class IsEmailTest extends BaseValidatorTestCase { /** * @dataProvider providerForEmail * @param mixed $input */ public function testEmail($input) { $this->assertTrue($this->isEmail($input)); } /** * @dataProvider providerForNotEmail * @param mixed $input */ public function testNotEmail($input) { $this->assertFalse($this->isEmail($input)); } public function providerForEmail() { return [ ['abc@def.com'], ['abc@def.com.cn'], ['a@a.c'], ['a_b@c.com'], ['_a@b.com'], ['_@a.com'], ]; } public function providerForNotEmail() { return [ ['not email.com'], ['@a.com'], ]; } }
mit
davcs86/Highcharts4Net
Highcharts4Net/Library/Options/PlotOptionsAreasplinerangeEvents.cs
3299
using Highcharts4Net.Library.Helpers; namespace Highcharts4Net.Library.Options { public class PlotOptionsAreasplinerangeEvents { /// <summary> /// Fires after the series has finished its initial animation, or in case animation is disabled, immediately as the series is displayed. /// </summary> public FunctionString AfterAnimate { get; set; } /// <summary> /// Fires when the checkbox next to the series' name in the legend is clicked.. The <code>this</code> keyword refers to the series object itself. One parameter, <code>event</code>, is passed to the function. The state of the checkbox is found by <code>event.checked</code>. Return <code>false</code> to prevent the default action which is to toggle the select state of the series. /// </summary> public FunctionString CheckboxClick { get; set; } /// <summary> /// Fires when the series is clicked. The <code>this</code> keyword refers to the series object itself. One parameter, <code>event</code>, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. Additionally, <code>event.point</code> holds a pointer to the nearest point on the graph. /// </summary> public FunctionString Click { get; set; } /// <summary> /// Fires when the series is hidden after chart generation time, either by clicking the legend item or by calling <code>.hide()</code>. /// </summary> public FunctionString Hide { get; set; } /// <summary> /// Fires when the legend item belonging to the series is clicked. The <code>this</code> keyword refers to the series object itself. One parameter, <code>event</code>, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. The default action is to toggle the visibility of the series. This can be prevented by returning <code>false</code> or calling <code>event.preventDefault()</code>. /// </summary> public FunctionString LegendItemClick { get; set; } /// <summary> /// Fires when the mouse leaves the graph. The <code>this</code> keyword refers to the series object itself. One parameter, <code>event</code>, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. If the <a class='internal' href='#plotOptions.series'>stickyTracking</a> option is true, <code>mouseOut</code> doesn't happen before the mouse enters another graph or leaves the plot area. /// </summary> public FunctionString MouseOut { get; set; } /// <summary> /// Fires when the mouse enters the graph. The <code>this</code> keyword refers to the series object itself. One parameter, <code>event</code>, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. /// </summary> public FunctionString MouseOver { get; set; } /// <summary> /// Fires when the series is shown after chart generation time, either by clicking the legend item or by calling <code>.show()</code>. /// </summary> public FunctionString Show { get; set; } } }
mit
Rewtek/GameLibrary
Code/Rewtek.GameLibrary/Properties/AssemblyInfo.cs
1597
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("Rewtek Game Library")] [assembly: AssemblyDescription("Basic game library for 2D games using DirectX.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rewtek Network")] [assembly: AssemblyProduct("Rewtek.GameLibrary")] [assembly: AssemblyCopyright("Copyright (c) 2014 Rewtek Network")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("3abfd3f0-66a5-41ee-bdee-40fd8bc6e9f9")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.822.*")] [assembly: AssemblyFileVersion("0.822.214.0")]
mit
akshaykamath/StateReviewTrendAnalysisYelp
StateReviewTrendsPOC.py
4899
__author__ = 'Akshay' """ File contains code to Mine reviews and stars from a state reviews. This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map. For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for each state. Use the resulting json to plot it onto the map. For the actual map visualisation, please refer State Review Nightlife POC. Since only 5 business reviews were taken per state, this still needs work. """ ############################################## from __future__ import division import sys reload(sys) import json import datetime sys.setdefaultencoding('utf8') state_5_star_dict = {} state_4_star_dict = {} state_3_star_dict = {} state_2_star_dict = {} state_1_star_dict = {} state_business = {} def create_set_for_business_with_cat(category): business_count = 0 with open('Data\yelp_academic_dataset_business.json') as fp: for line in fp.readlines(): temp = json.loads(line, encoding='utf-8') categories = str(temp["categories"]) state = str(temp["state"]) if state == "ON" or state == "ELN" or state == "EDH" or state == "MLN" or state == "NTH" or state == "FIF": continue if state not in state_business: state_business[state] = 0 if len(state_business.keys()) == 50: break if category in categories: print state business_id = str(temp["business_id"]) city = str(temp["city"]) name = str(temp["name"]) create_yelp_set(business_id, state, city, name) print "set prepared." def create_yelp_set(business_id, state, city, name): file_write = open('Data\state_stars_date_business.txt', mode='a') if state_business[state] == 5: print state, " is already completed." return with open('Data\yelp_academic_dataset_review.json') as fp: for line in fp.readlines(): temp = json.loads(line, encoding='utf-8') if str(temp["business_id"]) == business_id: state_business[state] += 1 star = str(temp["stars"]) date = str(temp["date"]) date_tm = datetime.datetime.strptime(date, "%Y-%m-%d").date() file_write.write(business_id) file_write.write('\t') file_write.write(state) file_write.write('\t') file_write.write(star) file_write.write('\t') file_write.write(city) file_write.write('\t') file_write.write(name) file_write.write('\t') file_write.write(str(date_tm)) file_write.write('\n') if state_business[state] == 5: break for key, value in state_5_star_dict.iteritems(): print key, value file_write.close() print "Done." def state_review_trends(): count = 0 with open('Data\state_stars_date_business.txt') as fp: for line in fp.readlines(): count += 1 tup = (line.split("\t")[0], line.split("\t")[1], line.split("\t")[2], line.split("\t")[3], line.split("\t")[4], line.split("\t")[5]) state = tup[1] star_rating = int(tup[2]) if int(star_rating) != 5: continue if state not in state_5_star_dict: state_5_star_dict[state] = 0 if state not in state_4_star_dict: state_4_star_dict[state] = 0 if state not in state_3_star_dict: state_3_star_dict[state] = 0 if state not in state_2_star_dict: state_2_star_dict[state] = 0 if state not in state_1_star_dict: state_1_star_dict[state] = 0 if star_rating == 5: state_5_star_dict[state] += 1 if star_rating == 4: state_4_star_dict[state] += 1 if star_rating == 3: state_3_star_dict[state] += 1 if star_rating == 2: state_2_star_dict[state] += 1 if star_rating == 1: state_1_star_dict[state] += 1 response = [] print "Number of 5 star reviews per state." for key, value in state_5_star_dict.iteritems(): response.append({'id': key, 'value': value}) print key, value json_data = json.dumps(response) print json_data print "Done." print count def main(): # Uncomment the line to run mining data. # create_set_for_business_with_cat("Nightlife") state_review_trends() if __name__ == "__main__": print "Execute Script!!" main()
mit
Orlion/Minor
app/Modules/Index/Tpl/Index/index.php
1338
<html> <head> <script type="text/javascript"> console.log('<?=$name ?>=A PHP Framework'); console.log('It just did what a framework should do.'); </script> <style> body { padding-top: 10%; background-color: #95CACA; } .minor-content{ text-align: center; } .minor-title b{ font-size: 10em; font-family:"Microsoft YaHei"; } .minor-title span{ font-size: 2em; font-family:"Microsoft YaHei"; } .minor-m{ color: #0066CC; } .minor-i{ color: #FFE66F; } .minor-n{ color: #FF5151; } .minor-o{ color: #FFE66F; } .minor-r{ color: #0066CC; } .minor-desc{ font-size: 3em; } </style> </head> <body> <div class="minor-content"> <p class="minor-title"> <b class="minor-m">M</b> <b class="minor-i">i</b> <b class="minor-n">n</b> <b class="minor-o">o</b> <b class="minor-r">r</b> <span>&copy;</span> </p> <p class="minor-desc">It just did what a framework should do.</p> </div> </body> </html>
mit
Tuna-CMS/tuna-bundle
src/Tuna/Component/Common/Traits/LocaleTrait.php
452
<?php namespace TunaCMS\Component\Common\Traits; use Gedmo\Mapping\Annotation as Gedmo; trait LocaleTrait { /** * @var string * * @Gedmo\Locale */ protected $locale; /** * @inheritdoc */ public function setLocale($locale) { $this->locale = $locale; return $this; } /** * @inheritdoc */ public function getLocale() { return $this->locale; } }
mit
orion6912/mizonokuchi-lab
DbfluteProject/src/main/java/com/example/demo/dbflute/exbhv/TUsersBhv.java
371
package com.example.demo.dbflute.exbhv; import com.example.demo.dbflute.bsbhv.BsTUsersBhv; /** * The behavior of t_users. * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ @org.springframework.stereotype.Component("tUsersBhv") public class TUsersBhv extends BsTUsersBhv { }
mit
Institute-Web-Science-and-Technologies/LiveGovWP1
server/HARTools/src/main/java/eu/liveandgov/wp1/classifier/UKOB_NEW_Classifier.java
22173
package eu.liveandgov.wp1.classifier; // Generated with Weka 3.6.10 // // This code is public domain and comes with no warranty. // // Timestamp: Fri Mar 07 15:58:54 CET 2014 public class UKOB_NEW_Classifier { public static String getActivityName(int p) { switch (p) { case 0: return "on_table"; case 1: return "running"; case 2: return "sitting"; case 3: return "standing"; case 4: return "walking"; default: return "unknown"; } } public static double classify(Object[] i) throws Exception { double p; p = UKOB_NEW_Classifier.N204ce4dd132(i); return p; } static double N204ce4dd132(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 2; } else if ((Double) i[3] <= -3.147356) { p = UKOB_NEW_Classifier.N184579bc133(i); } else if ((Double) i[3] > -3.147356) { p = UKOB_NEW_Classifier.N1d558088135(i); } return p; } static double N184579bc133(Object []i) { double p = Double.NaN; if (i[8] == null) { p = 2; } else if ((Double) i[8] <= 1.07363) { p = 2; } else if ((Double) i[8] > 1.07363) { p = UKOB_NEW_Classifier.N793b3216134(i); } return p; } static double N793b3216134(Object []i) { double p = Double.NaN; if (i[18] == null) { p = 2; } else if ((Double) i[18] <= 9.0) { p = 2; } else if ((Double) i[18] > 9.0) { p = 4; } return p; } static double N1d558088135(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 0; } else if ((Double) i[5] <= 0.037589) { p = UKOB_NEW_Classifier.N58696fc3136(i); } else if ((Double) i[5] > 0.037589) { p = UKOB_NEW_Classifier.N47378b88138(i); } return p; } static double N58696fc3136(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 0; } else if ((Double) i[9] <= 0.479831) { p = 0; } else if ((Double) i[9] > 0.479831) { p = UKOB_NEW_Classifier.N7228988d137(i); } return p; } static double N7228988d137(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 2; } else if ((Double) i[9] <= 0.923177) { p = 2; } else if ((Double) i[9] > 0.923177) { p = 3; } return p; } static double N47378b88138(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 4; } else if ((Double) i[6] <= 49.781174) { p = UKOB_NEW_Classifier.Nfa9b23f139(i); } else if ((Double) i[6] > 49.781174) { p = UKOB_NEW_Classifier.N307b158d195(i); } return p; } static double Nfa9b23f139(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 4; } else if ((Double) i[5] <= 54.237549) { p = UKOB_NEW_Classifier.N4df54e21140(i); } else if ((Double) i[5] > 54.237549) { p = 1; } return p; } static double N4df54e21140(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 4; } else if ((Double) i[11] <= 100.112328) { p = UKOB_NEW_Classifier.N23dc8083141(i); } else if ((Double) i[11] > 100.112328) { p = UKOB_NEW_Classifier.N3b39530b194(i); } return p; } static double N23dc8083141(Object []i) { double p = Double.NaN; if (i[4] == null) { p = 4; } else if ((Double) i[4] <= 61.716549) { p = UKOB_NEW_Classifier.N61792ad9142(i); } else if ((Double) i[4] > 61.716549) { p = UKOB_NEW_Classifier.N55d98345193(i); } return p; } static double N61792ad9142(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 4; } else if ((Double) i[5] <= 13.149132) { p = UKOB_NEW_Classifier.N59ec3e8d143(i); } else if ((Double) i[5] > 13.149132) { p = UKOB_NEW_Classifier.N2130126b169(i); } return p; } static double N59ec3e8d143(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 4; } else if ((Double) i[11] <= 0.452057) { p = UKOB_NEW_Classifier.N24fec91a144(i); } else if ((Double) i[11] > 0.452057) { p = UKOB_NEW_Classifier.N6b490981160(i); } return p; } static double N24fec91a144(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 4; } else if ((Double) i[6] <= 16.656715) { p = UKOB_NEW_Classifier.N5344dcef145(i); } else if ((Double) i[6] > 16.656715) { p = UKOB_NEW_Classifier.Nf1ae851155(i); } return p; } static double N5344dcef145(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 4; } else if ((Double) i[6] <= 1.000236) { p = UKOB_NEW_Classifier.N4e04f99e146(i); } else if ((Double) i[6] > 1.000236) { p = UKOB_NEW_Classifier.N28a01c16147(i); } return p; } static double N4e04f99e146(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 1; } else if ((Double) i[2] <= -6.271492) { p = 1; } else if ((Double) i[2] > -6.271492) { p = 4; } return p; } static double N28a01c16147(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 4; } else if ((Double) i[5] <= 9.851411) { p = 4; } else if ((Double) i[5] > 9.851411) { p = UKOB_NEW_Classifier.N2793fd30148(i); } return p; } static double N2793fd30148(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 4; } else if ((Double) i[11] <= -0.434301) { p = 4; } else if ((Double) i[11] > -0.434301) { p = UKOB_NEW_Classifier.N64d36e9c149(i); } return p; } static double N64d36e9c149(Object []i) { double p = Double.NaN; if (i[16] == null) { p = 4; } else if ((Double) i[16] <= 13.0) { p = 4; } else if ((Double) i[16] > 13.0) { p = UKOB_NEW_Classifier.N7502f77a150(i); } return p; } static double N7502f77a150(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 4; } else if ((Double) i[2] <= -9.785049) { p = 4; } else if ((Double) i[2] > -9.785049) { p = UKOB_NEW_Classifier.N15c5a69a151(i); } return p; } static double N15c5a69a151(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= -1.422839) { p = 4; } else if ((Double) i[3] > -1.422839) { p = UKOB_NEW_Classifier.N633cd3a0152(i); } return p; } static double N633cd3a0152(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 1; } else if ((Double) i[3] <= -1.028417) { p = 1; } else if ((Double) i[3] > -1.028417) { p = UKOB_NEW_Classifier.N2e69e046153(i); } return p; } static double N2e69e046153(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= 7.872425) { p = UKOB_NEW_Classifier.N29032b78154(i); } else if ((Double) i[3] > 7.872425) { p = 1; } return p; } static double N29032b78154(Object []i) { double p = Double.NaN; if (i[15] == null) { p = 4; } else if ((Double) i[15] <= 29.0) { p = 4; } else if ((Double) i[15] > 29.0) { p = 1; } return p; } static double Nf1ae851155(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= 8.235121) { p = 4; } else if ((Double) i[3] > 8.235121) { p = UKOB_NEW_Classifier.N2f8a2596156(i); } return p; } static double N2f8a2596156(Object []i) { double p = Double.NaN; if (i[4] == null) { p = 4; } else if ((Double) i[4] <= 4.86241) { p = 4; } else if ((Double) i[4] > 4.86241) { p = UKOB_NEW_Classifier.N16a9b33c157(i); } return p; } static double N16a9b33c157(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= 2.820256) { p = UKOB_NEW_Classifier.N5f3633c3158(i); } else if ((Double) i[1] > 2.820256) { p = UKOB_NEW_Classifier.N5f80780a159(i); } return p; } static double N5f3633c3158(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 4; } else if ((Double) i[9] <= 0.12637) { p = 4; } else if ((Double) i[9] > 0.12637) { p = 1; } return p; } static double N5f80780a159(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 4; } else if ((Double) i[1] <= 4.085389) { p = 4; } else if ((Double) i[1] > 4.085389) { p = 1; } return p; } static double N6b490981160(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 4; } else if ((Double) i[9] <= 0.983828) { p = UKOB_NEW_Classifier.N80f2b2e161(i); } else if ((Double) i[9] > 0.983828) { p = UKOB_NEW_Classifier.N7fbb8353165(i); } return p; } static double N80f2b2e161(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 4; } else if ((Double) i[5] <= 10.219557) { p = 4; } else if ((Double) i[5] > 10.219557) { p = UKOB_NEW_Classifier.N1bdbdd24162(i); } return p; } static double N1bdbdd24162(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 1; } else if ((Double) i[9] <= 0.216643) { p = UKOB_NEW_Classifier.N7f9374c5163(i); } else if ((Double) i[9] > 0.216643) { p = 4; } return p; } static double N7f9374c5163(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 4; } else if ((Double) i[1] <= 0.777919) { p = 4; } else if ((Double) i[1] > 0.777919) { p = UKOB_NEW_Classifier.N29d772f2164(i); } return p; } static double N29d772f2164(Object []i) { double p = Double.NaN; if (i[17] == null) { p = 1; } else if ((Double) i[17] <= 19.0) { p = 1; } else if ((Double) i[17] > 19.0) { p = 4; } return p; } static double N7fbb8353165(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 1; } else if ((Double) i[6] <= 4.230997) { p = 1; } else if ((Double) i[6] > 4.230997) { p = UKOB_NEW_Classifier.N6faaffa8166(i); } return p; } static double N6faaffa8166(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= -0.643157) { p = UKOB_NEW_Classifier.N4376a7de167(i); } else if ((Double) i[3] > -0.643157) { p = 4; } return p; } static double N4376a7de167(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= -0.118966) { p = 1; } else if ((Double) i[1] > -0.118966) { p = UKOB_NEW_Classifier.N2307026c168(i); } return p; } static double N2307026c168(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 4; } else if ((Double) i[1] <= 1.173586) { p = 4; } else if ((Double) i[1] > 1.173586) { p = 1; } return p; } static double N2130126b169(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 1; } else if ((Double) i[11] <= -0.427478) { p = UKOB_NEW_Classifier.N5b093fd2170(i); } else if ((Double) i[11] > -0.427478) { p = UKOB_NEW_Classifier.N7da99cc6186(i); } return p; } static double N5b093fd2170(Object []i) { double p = Double.NaN; if (i[7] == null) { p = 1; } else if ((Double) i[7] <= 12.444286) { p = UKOB_NEW_Classifier.N3c3d22af171(i); } else if ((Double) i[7] > 12.444286) { p = UKOB_NEW_Classifier.N5a8d77a3185(i); } return p; } static double N3c3d22af171(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 4; } else if ((Double) i[1] <= -2.788938) { p = 4; } else if ((Double) i[1] > -2.788938) { p = UKOB_NEW_Classifier.N51b02e0e172(i); } return p; } static double N51b02e0e172(Object []i) { double p = Double.NaN; if (i[8] == null) { p = 4; } else if ((Double) i[8] <= 18.259687) { p = UKOB_NEW_Classifier.N59fc308173(i); } else if ((Double) i[8] > 18.259687) { p = UKOB_NEW_Classifier.N5c66ba68180(i); } return p; } static double N59fc308173(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 1; } else if ((Double) i[2] <= -9.028058) { p = UKOB_NEW_Classifier.N3bbd451a174(i); } else if ((Double) i[2] > -9.028058) { p = UKOB_NEW_Classifier.N712d0e5178(i); } return p; } static double N3bbd451a174(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= 0.054357) { p = UKOB_NEW_Classifier.N703cc9a175(i); } else if ((Double) i[1] > 0.054357) { p = 4; } return p; } static double N703cc9a175(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 4; } else if ((Double) i[9] <= 0.988371) { p = 4; } else if ((Double) i[9] > 0.988371) { p = UKOB_NEW_Classifier.Na6d960f176(i); } return p; } static double Na6d960f176(Object []i) { double p = Double.NaN; if (i[5] == null) { p = 1; } else if ((Double) i[5] <= 13.414605) { p = UKOB_NEW_Classifier.N2096b822177(i); } else if ((Double) i[5] > 13.414605) { p = 1; } return p; } static double N2096b822177(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= -0.116156) { p = 1; } else if ((Double) i[1] > -0.116156) { p = 4; } return p; } static double N712d0e5178(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 4; } else if ((Double) i[1] <= -0.515174) { p = UKOB_NEW_Classifier.N64506e03179(i); } else if ((Double) i[1] > -0.515174) { p = 4; } return p; } static double N64506e03179(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= 7.711304) { p = 4; } else if ((Double) i[3] > 7.711304) { p = 1; } return p; } static double N5c66ba68180(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= 7.946371) { p = UKOB_NEW_Classifier.N5c58313c181(i); } else if ((Double) i[1] > 7.946371) { p = 4; } return p; } static double N5c58313c181(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 4; } else if ((Double) i[6] <= 8.975226) { p = UKOB_NEW_Classifier.N22088981182(i); } else if ((Double) i[6] > 8.975226) { p = UKOB_NEW_Classifier.N5e7b859b183(i); } return p; } static double N22088981182(Object []i) { double p = Double.NaN; if (i[15] == null) { p = 1; } else if ((Double) i[15] <= 16.0) { p = 1; } else if ((Double) i[15] > 16.0) { p = 4; } return p; } static double N5e7b859b183(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 1; } else if ((Double) i[11] <= -0.609702) { p = 1; } else if ((Double) i[11] > -0.609702) { p = UKOB_NEW_Classifier.N7f80b392184(i); } return p; } static double N7f80b392184(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 4; } else if ((Double) i[2] <= -6.059775) { p = 4; } else if ((Double) i[2] > -6.059775) { p = 1; } return p; } static double N5a8d77a3185(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 4; } else if ((Double) i[2] <= -10.409928) { p = 4; } else if ((Double) i[2] > -10.409928) { p = 1; } return p; } static double N7da99cc6186(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 4; } else if ((Double) i[3] <= 5.222265) { p = UKOB_NEW_Classifier.Na73cb9e187(i); } else if ((Double) i[3] > 5.222265) { p = UKOB_NEW_Classifier.N6c0c10eb191(i); } return p; } static double Na73cb9e187(Object []i) { double p = Double.NaN; if (i[7] == null) { p = 4; } else if ((Double) i[7] <= 10.370795) { p = UKOB_NEW_Classifier.N383cf76e188(i); } else if ((Double) i[7] > 10.370795) { p = UKOB_NEW_Classifier.N2a98739a189(i); } return p; } static double N383cf76e188(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 1; } else if ((Double) i[2] <= -8.81798) { p = 1; } else if ((Double) i[2] > -8.81798) { p = 4; } return p; } static double N2a98739a189(Object []i) { double p = Double.NaN; if (i[6] == null) { p = 4; } else if ((Double) i[6] <= 9.88914) { p = UKOB_NEW_Classifier.N7ecd994e190(i); } else if ((Double) i[6] > 9.88914) { p = 4; } return p; } static double N7ecd994e190(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 4; } else if ((Double) i[9] <= 0.975227) { p = 4; } else if ((Double) i[9] > 0.975227) { p = 1; } return p; } static double N6c0c10eb191(Object []i) { double p = Double.NaN; if (i[8] == null) { p = 4; } else if ((Double) i[8] <= 15.139568) { p = 4; } else if ((Double) i[8] > 15.139568) { p = UKOB_NEW_Classifier.Nc2aebb8192(i); } return p; } static double Nc2aebb8192(Object []i) { double p = Double.NaN; if (i[2] == null) { p = 1; } else if ((Double) i[2] <= 4.638933) { p = 1; } else if ((Double) i[2] > 4.638933) { p = 4; } return p; } static double N55d98345193(Object []i) { double p = Double.NaN; if (i[9] == null) { p = 1; } else if ((Double) i[9] <= 0.382263) { p = 1; } else if ((Double) i[9] > 0.382263) { p = 4; } return p; } static double N3b39530b194(Object []i) { double p = Double.NaN; if (i[13] == null) { p = 0; } else if ((Double) i[13] <= 177.0) { p = 0; } else if ((Double) i[13] > 177.0) { p = 3; } return p; } static double N307b158d195(Object []i) { double p = Double.NaN; if (i[11] == null) { p = 1; } else if ((Double) i[11] <= 0.475229) { p = UKOB_NEW_Classifier.N60c3f4d8196(i); } else if ((Double) i[11] > 0.475229) { p = 4; } return p; } static double N60c3f4d8196(Object []i) { double p = Double.NaN; if (i[3] == null) { p = 1; } else if ((Double) i[3] <= -0.719296) { p = UKOB_NEW_Classifier.N60ffc289197(i); } else if ((Double) i[3] > -0.719296) { p = 1; } return p; } static double N60ffc289197(Object []i) { double p = Double.NaN; if (i[1] == null) { p = 1; } else if ((Double) i[1] <= 0.430599) { p = 1; } else if ((Double) i[1] > 0.430599) { p = 4; } return p; } }
mit
dorianneto/laraticket
resources/lang/pt_BR/miscellaneous.php
931
<?php return [ 'dashboard' => 'Dashboard', 'auxiliary' => 'Auxiliar|Auxiliares', 'category' => 'Categoria|Categorias', 'department' => 'Departamento|Departamentos', 'priority' => 'Prioridade|Prioridades', 'ticket' => 'Ticket|Tickets', 'report' => 'Reportar', 'login' => 'Login', 'register' => 'Registrar', 'reset_password' => 'Resetar senha', 'closed' => 'Fechado', 'invalid' => 'Inválido', 'in progress' => 'Em progresso', 'open' => 'Aberto', 'resolved' => 'Resolvido', 'sign_in' => 'Acesso', 'sign_out' => 'Sair', 'edit_profile' => 'Configurações da conta', 'my_profile' => 'Meu perfil', 'my_ticket' => 'Meu ticket|Meus tickets', 'show_all' => 'Visualizar todos', 'ticket_state' => 'Tickets :state', 'select_option_default' => 'Selecione uma opção', 'archived' => 'Arquivado|Arquivados', ];
mit
michaelkauflin/TestHelperExtensions
TestHelperExtensions.Test/StringExtensions_GetRandom_Should.cs
1698
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestHelperExtensions.Test { [TestClass] public class StringExtensions_GetRandom_Should { [TestMethod] public void ReturnAStringOfLength8IfNoLengthSpecified() { var actual = string.Empty.GetRandom(); Assert.AreEqual(8, actual.Length); } [TestMethod, ExpectedException(typeof(ArgumentException))] public void ThrowArgumentExceptionIfSpecifiedLengthIsZero() { var actual = string.Empty.GetRandom(0); } [TestMethod, ExpectedException(typeof(ArgumentException))] public void ThrowArgumentExceptionIfSpecifiedLengthIsNegative() { var length = -50.GetRandom(1); var actual = string.Empty.GetRandom(length); } [TestMethod] public void ReturnAStringOfTheSpecifiedLength() { for (int i = 0; i < 1000; i++) { var expectedLength = 50.GetRandom(1); var actual = string.Empty.GetRandom(expectedLength); Assert.AreEqual(expectedLength, actual.Length); } } /// <remarks> /// This is a sanity-check only, not a test for randomness /// </remarks> [TestMethod] public void NotReturnConsecutiveIdenticalStrings() { string lastValue = string.Empty; for (int i = 0; i < 1000; i++) { var actual = string.Empty.GetRandom(50); Assert.IsFalse(actual.Equals(lastValue)); lastValue = actual; } } } }
mit
vasyahacker/fdream
libs/objects.rb
13352
# -*- coding: utf-8 -*- ############### #Objects/items# ############### class Obj attr_accessor :id, :type, :names, :names_string, :data, :descriptions, :static, :id_parent, :parent_type, :number_of_uses, :code, :adjectives, :descr, :id_owner attr_reader :silence_flag def initialize(names, type) @id = 0 @type = type @names = names.split(',') @names_string = names @data = '' @descriptions = "" @descr = "" @static = false @id_parent = 0 @id_owner = 0 @parent_type = 'player' @number_of_uses = 0 @code = '' @thread = nil @codealive = true @listeneventcode = nil @incomingplayercode = nil @sex = 'male' @silence_flag = false @adjectives = "" end def KtoChto return @names[0] if @names.size > 0 @names_string end def KogoChego return @names[1] if @names.size > 1 @names_string end def KomuChemu return @names[2] if @names.size > 2 @names_string end def KogoChto return @names[3] if @names.size > 3 @names_string end def KemChem return @names[4] if @names.size > 4 @names_string end def OKomOChom return @names[5] if @names.size > 5 @names_string end def showtoplayer(sender, message) return if @parent_type=="player" and @type == 'NPC' $gg.sendmess(sender, message) end def showtoall(sender, message) return if @parent_type == "player" and @type == 'NPC' if @parent_type == "player" p = $gg.getplayerbyid @id_parent where = p.where else where = @id_parent end $gg.showtoall(sender, message, where) end def incomingplayer(sender, p) @incomingplayercode.call(sender, p) unless @incomingplayercode.nil? end def listen(sender, message) Thread.new do begin @listencode.call(sender, message) unless @listencode.nil? rescue => detail if @parent_type == 'player' p = $gg.getplayerbyid(@id_parent) cont = "player(#{p.name}) backpack in loc ##{p.where.to_s}" else cont = "location \##{@id_parent.to_s}" end mess = "\n# # #\nERROR: #{$!.to_s}\nin listen obect code \""+ KtoChto()+"\" in "+cont+"\n# # #" $gg.sendmess($MAINADDR, mess) $stderr.puts "\n[#{Time.now.to_s}]: \n[objects] listen: #{$!.to_s}\n#{mess}\n"+detail.backtrace.join("\n") end end end def saveself() $gg.db.updateobject(self) end def listenevent(&eventcode) @listencode = eventcode end def incomingplayerevent(&eventcode) @incomingplayercode = eventcode end def runfork() killfork @thread = Thread.new do begin eval(@code) rescue => detail if @parent_type == 'player' p = $gg.getplayerbyid(@id_parent) cont = "player(#{p.name}) backpack in loc ##{p.where.to_s}" else cont = "location \##{@id_parent.to_s}" end mess = "\n# # #\nERROR: #{$!.to_s}\nin embeded obect code \""+ KtoChto()+"\" in "+cont+"\n# # #" $gg.sendmess($MAINADDR, mess) $stderr.puts "\n[#{Time.now.to_s}]: \n[objects] runfork: #{$!.to_s}\n#{mess}\n"+detail.backtrace.join("\n") end end end def killfork @listencode = nil return if @thread.nil? || !@thread.alive? @codealive = false i = 10 while @thread.alive? do i-=1 sleep 1 @thread.kill if i == 0 end @codealive = true end def action(txt, sender2=false) return if @parent_type == 'player' and @type == 'NPC' if sender2 != false p2 = (sender2) ? $gg.players[sender2] : sender2 out = $gg.TextBuild(txt, p2) if out.class == Array showtoplayer(sender2, out[1]) showtoall(sender2, out[0]) end else showtoall("", txt) end end def getname(sender) $gg.players[sender].name end def use if @code != '' runfork() return true else return false end end end class NPC < Obj attr_accessor :state, :followingplayers, :sms, :sex alias :name :KtoChto alias :chey :KogoChego alias :komu :KomuChemu alias :kogo :KogoChto alias :kem :KemChem alias :okom :OKomOChom alias :where :id_parent def ready true end def where return if @parent_type == 'player' @id_parent end def where=(val) @id_parent = val end def male? (@sex == 'male') ? true : false end def female? (@sex == 'female') ? true : false end def descr @descriptions end def realise?(time, pp) true end def action(txt, sender2=false) return if @parent_type == 'player' and @type == 'NPC' p2 = (sender2) ? $gg.players[sender2] : sender2 out = $gg.TextBuild(txt, self, p2) if out.class == Array && sender2 != false showtoplayer(sender2, out[1]) showtoall(sender2, out[0]) else showtoall("", out) end end def say(message, sender=false) return if @parent_type == 'player' $gg.say(self, ((sender) ? getname(sender)+": " : "") + message) end def db_open @db = SQLite3::Database.new("db/obj_#{@id}.db") end def quote(s) s.force_encoding('utf-8').gsub(/'/, "''") unless s == nil || s == [] end def kick_noobs(from, to) return if @parent_type == 'player' $gg.players.each { |addr, p| if p.ready && p.where == from $gg.recall(addr, to, true) unless p.realise?($gg.time) end } end def moveplayers(from, to) return if @parent_type == 'player' $gg.moveplayers("", from, to) end def moveplayer(sender, to) return if @parent_type == 'player' $gg.recall(sender, to, true) end def recall(to) return if @parent_type == 'player' l1 = $gg.locations[@id_parent] l2 = $gg.locations[to] @id_parent = to l1.objects.delete_if { |x| x.id == @id } l2.objects.push self saveself end def go(direct) $gg.go(self, direct) unless @parent_type == 'player' end end class CardsPack class Cards class Card attr_accessor :value, :type, :access, :id, :svert def initialize(v="", t="") @value = v @type = t @access = false @id = 0 @svert = 0 end def clear @value = "" @type = "" @access = false @svert = 0 end end attr_accessor :pack, :lastinsertid, :lastsvertid def initialize @lastinsertid = 0 @lastsvertid = [] @pack = [] 36.times { @pack.push(Card.new()) } init # clear end def init @pointer = 0 p = 0 for v in ["6", "7", "8", "9", "10", "В", "Д", "К", "Т"] for t in ["к", "ч", "б", "п"] @pack[p].value = v @pack[p].type = t @pack[p].access = true p = p+1 end end end def clear @pack.clear #each{|c|c.clear} @pointer = 0 @lastinsertid = 0 end def show out = "" @pack.each do |c| if c.access out += "#{c.value}#{c.type}" out += "(#{c.svert.to_s})" if c.svert > 0 out += " " end end return out end def shuffle @pack.replace @pack.sort_by { rand } 0.upto(35) { |i| @pack[i].id=i } end def add(from) n = from.sub return n if n == false @pack.push n @lastinsertid = n.id return true end def sub return false if @pointer > 35 ret = @pack[@pointer].clone @pointer += 1 return ret end def svertka return false if @pack.size < 3 0.upto(@pack.size-3) do |i| if ((@pack[i].value == @pack[i+2].value || @pack[i].type == @pack[i+2].type)) @lastsvertid[0] = @pack[i].id @lastsvertid[1] = @pack[i+1].id @pack.delete_at i return @lastinsertid end end return false end def copy(from) 0.upto(35) { |i| @pack[i] = from.pack[i].clone } end def maxs m = 0 @pack.each { |c| m = c.svert if m < c.svert } return m end def showcard(id) out = @pack[id].value out += @pack[id].type return out end end def Doit(sens) d = Cards.new e = Cards.new r = Cards.new step = sens out = "Ты берешь колоду карт и хорошо перемешиваешь... затем начинаешь терпеливо раскладывать пасьянс Медичи..." flag = true while flag && step > 0 do step -= 1 r.init d.clear r.shuffle e.copy(r); while d.add(r) do # print "\nВыкладываем из колоды на стол следующую карту ",E.showcard(D.lastinsertid) while true do # print "\nНа столе: ",D.show id = d.svertka if id == false # print " не найдено сверток..." break end # print "\nнакладываем ",E.showcard(D.lastsvertid[1])," на ",E.showcard(D.lastsvertid[0]) e.pack[id].svert += 1 end end flag = (d.pack.size == 2) ? false : true end out += "\nВ итоге остались следующие карты:\n" out += d.show if flag out += "\nЖаль.. колода не свернулась..." else out += "\nКолода свернулась!\n Цепочка выглядит следующим образом: " out += e.show out += "\nВ скобках показана мощность карты(сколько из-за нее произошло сверток) Максимальная мощность "+e.maxs.to_s end out end end class Rune < Obj def recall() if $gg.locations[@data.to_i].nil? showtoplayer(addr, "Место, куда ты собираешся попасть с помощью #{KogoChego()} больше не существует.") return end p = $gg.getplayerbyid @id_parent addr = $gg.players.key(p) l = $gg.locations[@data.to_i] unless l.areflag showtoplayer(addr, "Место, куда ты собираешься попасть с помощью #{KogoChego()} защищено от телепортаций и случайных перемещений.") return end action "~kto~ закрыл[а] глаза и исчез[ла].)><(Ты закрыл[а] глаза и стал[а] вспоминать все что тебе известно о месте, известном тебе как \"#{l.name}\", но детали получалось вспоминать только обрывками, затем ты нащупал[а] в кармане нужную руну телепорта и сильно сжал[а] ее в руке. В тот же момент перед твоим внутренним взором предстало это место во всех деталях. Мгновенье спустя ты с удивлением обнаружил[а] что твои глаза уже не закрыты и ты просто смотришь на то что только что себе представлял[а].", addr p.where = @data.to_i action "Ты случайно замечаешь что здесь, рядом с тобой, уже находится ~kto~, но когда он[а] тут появил{ся}[ась] вспомнить не можешь.)><(#{$gg.look(addr)}", addr end def mark() p = $gg.getplayerbyid @id_parent addr = $gg.players.key(p) l = $gg.locations[p.where] unless l.areflag showtoplayer(addr, "Это место защищено от телепортаций и случайных перемещений.") return end action '~kto~ осмотрел{ся}[ась] вокруг, затем достал[а] из кармана какую-то деревянную дощечку и крепко сжал[а] ее закрыв при этом глаза на несколько секунд. После чего ты почувствовал легкий энергетический всплеск вокруг себя.)><(Ты осмотрел{ся}[ась] вокруг, и постарал{ся}[ась] запомнить это место как можно детальнее, затем достал[а] из кармана чистую руну телепорта и крепко сжал[а] ее, закрыв при этом глаза, концентрируясь только на этом месте. В следующий миг ты почувствовал[а] как руна в твоей руке нагрелась и вырезанный на ней узор стал меняться, затем руна остыла. Ты понимаешь что руна теперь принадлежит этому месту.', addr @descr = @descr+"\n Ты чувствуешь что этот предмет связан с местом, под названием «#{l.name}»" @data = p.where saveself end def use() if $gg.isNumeric(@data) recall() else mark() end end end
mit
AnaSula/NYU-Python-Programming-Class
intro-programming/assignment_5/controlled_fall.py
931
import math import math def get_fall_time(height): # gravity isn't going to change, units in m/(s^2) acceleration_by_gravity = 9.8 time_elapsed = math.sqrt((2 * height) / acceleration_by_gravity) return time_elapsed get_fall_time(15) def isVulnerable(tower_height, tower_x, tower_y, target_x, target_y): muzzle_velocity = 300 # update this line to calculate time_in_air using get_fall_time() function time_in_air = get_fall_time(tower_height) tower_range = time_in_air*muzzle_velocity delta_x = tower_x - target_x delta_y = tower_y - target_y separation = delta_x**2+delta_y**2 if separation < tower_range: print("The target is closer than the tower range, what should we return?") return None else: print("The target is further than the tower range, what should we return?") return None isVulnerable(15, 20, 30, 40, 50)
mit
rhythm-section/guh-libjs
src/models/device-class-state-type-model-service.js
2912
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015 Lukas Mayerhofer <lukas.mayerhofer@guh.guru> * * * * 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. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ (function() { 'use strict'; angular .module('guh.models') .factory('DSDeviceClassStateType', DSDeviceClassStateTypeFactory) .run(function(DSDeviceClassStateType) {}); DSDeviceClassStateTypeFactory.$inject = ['$log', 'DS', 'modelsHelper']; function DSDeviceClassStateTypeFactory($log, DS, modelsHelper) { var staticMethods = {}; /* * DataStore configuration */ var DSDeviceClassStateType = DS.defineResource({ // Model configuration name: 'deviceClassStateType', relations: { belongsTo: { deviceClass: { localField: 'deviceClass', localKey: 'deviceClassId' }, stateType: { localField: 'stateType', localKey: 'stateTypeId' } } } }); return DSDeviceClassStateType; } }());
mit
concord-consortium/lara
db/migrate/20160313031738_add_index_to_portal_publications.rb
157
class AddIndexToPortalPublications < ActiveRecord::Migration def change add_index :portal_publications, [:publishable_id, :publishable_type] end end
mit
nusedutech/coursemology.org
app/assets/javascripts/application.js
15428
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery-ui.min //= require jquery-fileupload //= require tree.jquery //= require angular //= require angular-resource //= require angular-route //= require angular-ui-sortable-rails //= require jquery.validate //= require jquery.validate.additional-methods //= require jquery-tmpl // //= require bootstrap-dropdown //= require bootstrap-transition //= require bootstrap-collapse //= require bootstrap-button //= require bootstrap-tab //= require bootstrap-tooltip //= require bootstrap-popover //= require bootstrap-affix //= require bootstrap-scrollspy // //= require bootstrap-colorpicker //= require bootstrap-datetimepicker //= require bootstrap-select // //= require bootstrap-modal //= require bootstrap-wysihtml5 //= require scrolltofixed // //= require jquery.purr //= require best_in_place //= require codemirror //= require codemirror/modes/python //= require codemirror/addons/runmode/runmode //= require codemirror/addons/edit/matchbrackets //= require moment //= require cocoon //= require ckeditor/init //= require ckeditor/adapters/jquery // //= require_self //= require_tree ./templates //= require_tree . $(document).ready(function() { $.getScript("https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"); (function() { /// Sets a date suggestion for the given datetimepicker (set as this) when it is blank. function setDefaultDateSuggestion(date) { var $this = $(this); var registered = $this.data('datetimepickerDefault'); $this.data('datetimepickerDefault', date); if (registered) { return; } $this.on('show', function() { // If we have no date set, we will jump the date picker to somewhere in the start/end range. var picker = $this.data('datetimepicker'); var defaultDate = $this.data('datetimepickerDefault'); if (!$this.val()) { if (defaultDate < now || now < defaultDate) { picker.setDate(defaultDate); picker.setDate(null); } } }); } var datetimepickers = $('.datepicker, .datetimepicker'); $('.datetimepicker').datetimepicker({ format: 'dd-MM-yyyy hh:mm', language: 'en-US', collapse: false, pickSeconds: false, maskInput: true }); $('.datepicker').datetimepicker({ format: 'dd-MM-yyyy', language: 'en-US', pickTime: false, collapse: false, maskInput: true }); var now = new Date(); var tomorrow = moment().add('d', 1).startOf('day').toDate(); var yesterday = moment().subtract('d', 1).endOf('day').toDate(); $('.datetimepicker.future-only:not(.past-only)').datetimepicker('setStartDate', now). each(function() { setDefaultDateSuggestion.call(this, now); }); $('.datepicker.future-only:not(.past-only)').datetimepicker('setStartDate', tomorrow). each(function() { setDefaultDateSuggestion.call(this, tomorrow); }); $('.datetimepicker.past-only:not(.future-only)').datetimepicker('setEndDate', now). each(function() { setDefaultDateSuggestion.call(this, now); }); $('.datepicker.past-only:not(.future-only)').datetimepicker('setEndDate', now). each(function() { setDefaultDateSuggestion.call(this, now); }); // Extra code so that we will use the HTML5 data attribute of a date picker if we have one; otherwise // we let the code above handle it for us. The behaviour of a date picker becomes more and more specific. // // This also displays placeholder text so users know what format the date/time picker expects for keyboard // input. datetimepickers.each(function() { var $this = $(this); // TODO: The dates are passed through moment because of a bug in bootstrap-datetimepicker: // https://github.com/tarruda/bootstrap-datetimepicker/issues/210 // Furthermore, it's not following HTML5 specification: names split by hyphens are not camelCased. if ($this.data('dateEnddate')) { var date = moment($this.data('dateEnddate')).toDate(); $this.datetimepicker('setEndDate', date); setDefaultDateSuggestion.call(this, date); } if ($this.data('dateStartdate')) { var date = moment($this.data('dateStartdate')).toDate(); $this.datetimepicker('setStartDate', date); setDefaultDateSuggestion.call(this, date); } var dateTimeFormatString = $this.data('datetimepicker').format; var inputElement = $('input', this); if (!inputElement.attr("placeholder")) { // We only replace the placeholder if there isn't already one. inputElement.attr("placeholder", dateTimeFormatString); } }); })(); $('*[rel~=tooltip]').tooltip(); $('.colorpicker').colorpicker(); $('.selectpicker').selectpicker(); $('.origin_url').val(document.URL); // For our delete buttons, detach the companion button so it looks nicer in a .btn-group. // Then move it one level up so it acts like a first class citizen. $('.delete-button').each(function(n, elem) { var $elem = $(elem); var $parent = $elem.parent(); var $confirm = $elem.siblings('.delete-confirm-button'); $confirm.data('sibling', $elem); $elem.data('sibling', $confirm); $confirm.hide(); $confirm.detach(); $elem.detach(); $elem.insertBefore($parent); $parent.remove(); }); $('.delete-button').click(function(e) { var $this = $(this); var $parent = $this.parent(); var $sibling = $this.data('sibling'); $this.hide(); $sibling.insertBefore($this); $this.detach(); $sibling.fadeIn(); setTimeout(function() { $sibling.hide(); $this.insertBefore($sibling); $sibling.detach(); $this.fadeIn(); }, 2000); e.preventDefault(); e.stopPropagation(); }); $('.btn-hover-text').hover( function() { var $this = $(this); // caching $(this) $this.text($this.data('alt')); }, function() { var $this = $(this); // caching $(this) $this.text($this.data('original')); } ); $(function(){ $(".coursemology-code").each(_coursemologyFormatFunc); }); $(function(){ page_header = $(".page-header h1"); if (page_header.size() <= 0) return; page_name =page_header[0].innerHTML.replace(/\s/g,"-"); if (!page_name || page_name.indexOf('!') > 0 || page_name.indexOf(':') > 0) return; //<input type="hidden" id="<%= item[:text] %>_count" value="<%= item[:count] %>"> badge_count = $("#"+page_name+"_count"); if (badge_count.size() <= 0) return; new_items_seen = $(".new_"+page_name).size(); //<i class="<%= item[:icon] %>" id="badge_<%= item[:text] %>"></i> set_badge = $("#badge_"+page_name); if (new_items_seen >0 && set_badge.size() > 0) { update_count = badge_count.val() - new_items_seen; if (update_count > 0) set_badge[0].innerHTML = update_count; else set_badge.addClass("hidden"); } }); $(':input[type=number]' ).live('mousewheel',function(e){ $(this).blur(); }); // Make sure that any form elements with an error class are propagated // upwards to the parent control group $('.control-group label.error, .control-group div.error').each(function(n, element) { $(element).parents('.control-group').addClass('error'); }); // Make sure that form elements with add-on components have the error message // displayed after the add-on, not before (Rails limitation) $('div.error + span.add-on').each(function(n, elem) { var $elem = $(elem); var $input = $('input', $elem.parent()); $elem.detach().insertAfter($input); }); // Make sure that all links with the disabled tag or disabled attribute // do not trigger a navigation $('body').on('click', 'a.btn.disabled, a.btn[disabled]', function(e) { e.preventDefault(); }); var fixHelper = function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }; $(".sort tbody").sortable({ helper: fixHelper }).disableSelection(); $('.team_popover').popover({ trigger: "hover" }); }); // Define our framework for implementing client-side form validation. jQuery.fn.extend({ /// Validatr will find all forms in the queried set, and register /// submission handlers. Validation will be triggered before submit /// and blocked when errors occur. /// /// It also takes an array of tuples where the first element is a /// string (selector from the set), or a jQuery object, and the /// second element is the validation callback for the element. /// The validation callback can return a promise to defer the operation, /// a falsey value to validate; or a string or an array of error /// messages to display. validatr: function(elements) { //to not name conflict with the jQuery plugin function show_error($this, error) { var group = $this.parents('.control-group'); group.addClass('error'); // Create the help message span if none exists. var $message = $('.help-inline', group); if ($message.length === 0) { $message = $('<span class="help-inline"></span>'); $message.appendTo($this.parent()); } $message.text(error); } function remove_error($this) { var group = $this.parents('.control-group'); group.removeClass('error'); $('.help-inline', group).remove(); } // Generates a handler which will set the appropriate fields with // the error message returned from the validator function. function generateElementValidator(handler) { return function() { var result = handler.apply(this, arguments); var $this = $(this); function process_result(result) { if (!result) { remove_error($this); } else if (typeof result === 'object' && typeof result['promise'] === 'function') { result.done(function(value) { process_result(value); }); } else { if (typeof result === 'string') { result = [result]; } show_error($this, result); } } process_result(result); }; } function validateForm(e) { if ($('.error', this).length > 0) { e.preventDefault(); } } // Register all the callbacks for the form elements for (var i = 0; i < elements.length; ++i) { var pair = elements[i]; var set = pair[0]; if (typeof set === 'string') { set = $(set, this); } var validator = generateElementValidator(pair[1]); set.change(validator); set.on('changeDate', validator); } // Register the callback for when the form should be submitted. $(this).submit(validateForm); $('input[type="submit"]', this).click(function() { validateForm.apply($(this).parents('form')[0], arguments); }); } }); function _coursemologyFormatFunc(i, elem) { var $elem = $(elem); // Make sure we process every code block exactly once. if ($elem.data('formatted')) { return; } $elem.data('formatted', true); // Replace all <br /> with \n for CodeMirror. var $br = $('br', $elem); $br.each(function(n, elem) { var $elem = $(elem); var $prev = $elem.prev(); var $next = $elem.next(); $(document.createTextNode('\n')).insertBefore($elem); $elem.remove(); }); $elem.css('white-space', 'pre'); var code = $elem.text(); // Apply the multiline CSS style if we have a multiline code segment. if ($br.length > 0) { $elem.addClass('multiline'); } // Wrap the elements with an appropriate CodeMirror block to trigger syntax highlighting if ($elem.parents('.cos_code').length == 0) { $elem.wrap('<div class="cos_code"></div>'); $elem.addClass('cm-s-molokai'); } /*if($(d).hasClass("pythonCode"))*/{ CodeMirror.runMode(code, 'python', elem); } } function coursemologyFormat(element){ $(element).find(".coursemology-code").each(_coursemologyFormatFunc); } String.prototype.nl2br = function(){ return (this + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2'); }; function IsNumeric(input) { return (input - 0) == input && input.length > 0; } function IsPositive(input) { return IsNumeric(input) && (input - 0) >= 0 } function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;") .replace(/\n/g, "<br/>") .replace(/\s/g,"&nbsp;"); } function event_log(category, label, action, push){ if(typeof push != 'undefined' && push) { _gaq.push(['_trackEvent',category, action, label]); } } if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; }; function access_denied_redirect(message, redirectURL){ var confirmationMessage = message + "\n\nPress Ok to go back to be redirected."; var url = (typeof redirectURL == 'string' && redirectURL !== '') ? redirectURL : '/' if (confirm(confirmationMessage) == true) { window.location.href = url; } }
mit
EncontrAR/backoffice
src/containers/Charts/reactVis/charts/candleStick/candlestick.js
2263
import React from 'react'; import { AbstractSeries } from 'react-vis'; const predefinedClassName = 'rv-xy-plot__series rv-xy-plot__series--candlestick'; export default class CandlestickSeries extends AbstractSeries { render() { const {className, data, marginLeft, marginTop} = this.props; if (!data) { return null; } const xFunctor = this._getAttributeFunctor('x'); const yFunctor = this._getAttributeFunctor('y'); const strokeFunctor = this._getAttributeFunctor('stroke') || this._getAttributeFunctor('color'); const fillFunctor = this._getAttributeFunctor('fill') || this._getAttributeFunctor('color'); const opacityFunctor = this._getAttributeFunctor('opacity'); const distance = Math.abs(xFunctor(data[1]) - xFunctor(data[0])) * 0.2; return ( <g className={`${predefinedClassName} ${className}`} ref="container" transform={`translate(${marginLeft},${marginTop})`}> {data.map((d, i) => { const xTrans = xFunctor(d); const yHigh = yFunctor({...d, y: d.yHigh}); const yOpen = yFunctor({...d, y: d.yOpen}); const yClose = yFunctor({...d, y: d.yClose}); const yLow = yFunctor({...d, y: d.yLow}); const lineAttrs = { stroke: strokeFunctor && strokeFunctor(d) }; const xWidth = distance * 2; return ( <g transform={`translate(${xTrans})`} opacity={opacityFunctor ? opacityFunctor(d) : 1} key={i} onClick={e => this._valueClickHandler(d, e)} onMouseOver={e => this._valueMouseOverHandler(d, e)} onMouseOut={e => this._valueMouseOutHandler(d, e)}> <line x1={-xWidth} x2={xWidth} y1={yHigh} y2={yHigh} {...lineAttrs} /> <line x1={0} x2={0} y1={yHigh} y2={yLow} {...lineAttrs} /> <line x1={-xWidth} x2={xWidth} y1={yLow} y2={yLow} {...lineAttrs} /> <rect x={-xWidth} width={Math.max(xWidth * 2, 0)} y={yOpen} height={Math.abs(yOpen - yClose)} fill={fillFunctor && fillFunctor(d)} /> </g>); })} </g> ); } }
mit
tlianglstyle/JZUI_V2
build/js/Layout.js
5726
/* Layout() * ======== * Implements AdminLTE layout. * Fixes the layout height in case min-height fails. * * @usage activated automatically upon window load. * Configure any options by passing data-option="value" * to the body tag. */ +function ($) { 'use strict' var DataKey = 'lte.layout' var Default = { slimscroll : true, resetHeight: true } var Selector = { wrapper : '.wrapper', contentWrapper: '.content-wrapper', layoutBoxed : '.layout-boxed', mainFooter : '.main-footer', mainHeader : '.main-header', sidebar : '.sidebar', controlSidebar: '.control-sidebar', fixed : '.fixed', sidebarMenu : '.sidebar-menu', logo : '.main-header .logo' } var ClassName = { fixed : 'fixed', holdTransition: 'hold-transition' } var Layout = function (options) { this.options = options this.bindedResize = false this.activate() } Layout.prototype.activate = function () { this.fix() this.fixSidebar() $('body').removeClass(ClassName.holdTransition) if (this.options.resetHeight) { $('body, html, ' + Selector.wrapper).css({ 'height' : 'auto', 'min-height': '100%' }) } if (!this.bindedResize) { $(window).resize(function () { this.fix() this.fixSidebar() $(Selector.logo + ', ' + Selector.sidebar).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () { this.fix() this.fixSidebar() }.bind(this)) }.bind(this)) this.bindedResize = true } $(Selector.sidebarMenu).on('expanded.tree', function () { this.fix() this.fixSidebar() }.bind(this)) $(Selector.sidebarMenu).on('collapsed.tree', function () { this.fix() this.fixSidebar() }.bind(this)) } Layout.prototype.fix = function () { // Remove overflow from .wrapper if layout-boxed exists $(Selector.layoutBoxed + ' > ' + Selector.wrapper).css('overflow', 'hidden') // Get window height and the wrapper height var footerHeight = $(Selector.mainFooter).outerHeight() || 0 var neg = $(Selector.mainHeader).outerHeight() + footerHeight var windowHeight = $(window).height() var sidebarHeight = $(Selector.sidebar).height() || 0 // Set the min-height of the content and sidebar based on // the height of the document. if ($('body').hasClass(ClassName.fixed)) { $(Selector.contentWrapper).css('min-height', windowHeight - footerHeight) console.log(windowHeight - footerHeight); $(Selector.contentWrapper+' .content').css('height', windowHeight - footerHeight); } else { var postSetHeight; console.log(windowHeight); postSetHeight = windowHeight - $('.navbar-custom-menu').height() - 30; console.log(postSetHeight); $(Selector.contentWrapper).css('height', postSetHeight) $(Selector.contentWrapper+' .content').css('height', postSetHeight); $(Selector.contentWrapper+' #content-main').css('height', postSetHeight-30); /*if (windowHeight >= sidebarHeight) { $(Selector.contentWrapper).css('min-height', windowHeight - neg) console.log(windowHeight - neg+'-1'); $(Selector.contentWrapper+' .content').css('height', windowHeight - neg); postSetHeight = windowHeight - neg } else { $(Selector.contentWrapper).css('min-height', sidebarHeight) $(Selector.contentWrapper+' .content').css('height', sidebarHeight); console.log(windowHeight - sidebarHeight+'-2'); postSetHeight = sidebarHeight }*/ // Fix for the control sidebar height var $controlSidebar = $(Selector.controlSidebar) if (typeof $controlSidebar !== 'undefined') { if ($controlSidebar.height() > postSetHeight){ //$(Selector.contentWrapper).css('min-height', $controlSidebar.height()) } } } } Layout.prototype.fixSidebar = function () { // Make sure the body tag has the .fixed class if (!$('body').hasClass(ClassName.fixed)) { if (typeof $.fn.slimScroll !== 'undefined') { $(Selector.sidebar).slimScroll({ destroy: true }).height('auto') } return } // Enable slimscroll for fixed layout if (this.options.slimscroll) { if (typeof $.fn.slimScroll !== 'undefined') { // Destroy if it exists $(Selector.sidebar).slimScroll({ destroy: true }).height('auto') // Add slimscroll $(Selector.sidebar).slimScroll({ height: ($(window).height() - $(Selector.mainHeader).height()) + 'px', color : 'rgba(0,0,0,0.2)', size : '3px' }) } } } // Plugin Definition // ================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data(DataKey) if (!data) { var options = $.extend({}, Default, $this.data(), typeof option === 'object' && option) $this.data(DataKey, (data = new Layout(options))) } if (typeof option === 'string') { if (typeof data[option] === 'undefined') { throw new Error('No method named ' + option) } data[option]() } }) } var old = $.fn.layout $.fn.layout = Plugin $.fn.layout.Constuctor = Layout // No conflict mode // ================ $.fn.layout.noConflict = function () { $.fn.layout = old return this } // Layout DATA-API // =============== $(window).on('load', function () { Plugin.call($('body')) }) }(jQuery)
mit
hlex/vms
app/reducers/ads.js
7397
import _ from 'lodash'; import { SET_FOOTER_ADS, RESET_FOOTER_ADS, SET_BASE_ADS, REMEMBER_BASE_AD_PLAYING_INDEX, ADD_PLAY_RECORD, CLEAR_PLAY_RECORD } from '../actions/actionTypes'; import { normalizeStripAds } from '../helpers/masterdata'; const stripAds = [ { id: '4103', type: 'image', name: 'EMP_TripAdvisor_EMPStripAds', path: 'StripAds/20160205_emporium_cn_tripadvisor_1080_344.png', filename: '20160205_emporium_cn_tripadvisor_1080_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: 'e0adb2162abf7192cb6060461e6af3fc', }, { id: '4112', type: 'image', name: 'EMP_TripAdvisor_EMPStripAds', path: 'StripAds/20160205_emporium_en_trioadvisor_1080_344.png', filename: '20160205_emporium_en_trioadvisor_1080_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '02a7b50c2ec2f200e89d1f92052aa470', }, { id: '4096', type: 'image', name: 'EMP_AIS_EMPInteractiveDirectory', path: 'iDirectory/20151204_ais_1600.jpg', filename: '20151204_ais_1600.jpg', expire: '2026-11-21', timeout: '7000', adSize: 'FULLSCREEN', checksum: '37a0f9b3688943bfb6c15dab2ca88903', }, { id: '4114', type: 'image', name: 'EMP_TripAdvisor_EMPInteractiveDirectory', path: 'iDirectory/20160205_emporium_en_tripadviso1080_1600_4.png', filename: '20160205_emporium_en_tripadviso1080_1600_4.png', expire: '2026-11-21', timeout: '7000', adSize: 'FULLSCREEN', checksum: '9e0847ca5c7b753bedd245cf61920773', }, { id: '4121', type: 'image', name: 'EMP_ExpediaSp_EMPStripAds', path: 'StripAds/20160427_special-hotel-deals_344.png', filename: '20160427_special-hotel-deals_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '9ca44783007073c11ca9d7a2cd777a3a', }, { id: '4094', type: 'image', name: 'EMP_AIS_EMPStripAds', path: 'StripAds/20151204_ais_344.jpg', filename: '20151204_ais_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '47e93aec13f7c9115ebbcfaacb309ccd', }, { id: '4105', type: 'image', name: 'EMP_TripAdvisor_EMPInteractiveDirectory', path: 'iDirectory/20160205_emporium_cn_tripadvisor_1080_1600_4.png', filename: '20160205_emporium_cn_tripadvisor_1080_1600_4.png', expire: '2026-11-21', timeout: '7000', adSize: 'FULLSCREEN', checksum: 'ffe70577b2fa52a5db77988ba1329135', }, { id: '4136', type: 'image', name: 'EMP_MCardPrv_EMPStripAds', path: 'StripAds/20160519_mcard-privilege_344.png', filename: '20160519_mcard-privilege_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '5248ed312ff9e6ee626e258a588535af', }, { id: '4145', type: 'image', name: 'EMP_Mcard_Matsuya_EMPStripAds', path: 'StripAds/20160617_m-card-matsaya-ginza_344.png', filename: '20160617_m-card-matsaya-ginza_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '678482f9d3e27ea5ca12563b32997589', }, { id: '4154', type: 'image', name: 'EMP_alipay_EMPStripAds', path: 'StripAds/20160624_alipay_em_344.jpg', filename: '20160624_alipay_em_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '74385118d288f3184a853e47c4fa9305', }, { id: '4163', type: 'image', name: 'EMP_Health_EMPStripAds', path: 'StripAds/20160701_health-up-your-life_344.jpg', filename: '20160701_health-up-your-life_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '61217232de7a8d9b6feb3cfea9052e4e', }, { id: '4172', type: 'image', name: 'EMP_Mpoint_discount_EMPStripAds', path: 'StripAds/20160722_mpoint-discount-up-to-15_344.jpg', filename: '20160722_mpoint-discount-up-to-15_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '242a51c978e7eaddd83f48bc2b13e2ae', }, { id: '4181', type: 'image', name: 'EMP_VisaChina_EMPStripAds', path: 'StripAds/20160805_visachinacrossborder_344.jpg', filename: '20160805_visachinacrossborder_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '0327072f92c0d3d8bac98519e274302d', }, { id: '4190', type: 'image', name: 'EMP_CTB_AP_EMPStripAds', path: 'StripAds/20160916_citibank-asia-pacific_344.jpg', filename: '20160916_citibank-asia-pacific_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '9fe6731c3b6e2c65e7a0657662b876ef', }, { id: '4199', type: 'image', name: 'EMP_diningexp_EMPStripAds', path: 'StripAds/20160916_magical-dining-experience_344.jpg', filename: '20160916_magical-dining-experience_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: 'f4d0a6724f7eafb25266cb2088b515fd', }, { id: '4211', type: 'video', name: 'EMP_UFC_EMPStripAds', path: 'StripAds/20161007_ufc_344.mp4', filename: '20161007_ufc_344.mp4', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '29e4304189c0d933efd3f121909e84b8', }, { id: '4217', type: 'image', name: 'EMP_EMPMag_EMPStripAds', path: 'StripAds/20161007_emp_magazine-no33_344.jpg', filename: '20161007_emp_magazine-no33_344.jpg', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '0535ff9d83538353bd3a84c62028c845', }, { id: '4226', type: 'image', name: 'EMP_BT_Gift17_EMPStripAds', path: 'StripAds/20161111_betrend-gift-2017_344.png', filename: '20161111_betrend-gift-2017_344.png', expire: '2026-11-21', timeout: '2000', adSize: 'STRIP', checksum: '0de9be00280a021661584f2a3af95319', }, ]; const baseAds = _.map(stripAds, ad => normalizeStripAds(ad)); // playRecord model // [id]: { // id: '', // name: '', // times: 0 // } const initialState = { playRecords: {}, footerAdType: '', baseAdPlayingIndex: 0, baseAds: [], footerAds: [], // baseAds, }; const getInitialState = () => ({ ...initialState, }); export default (state = getInitialState(), action) => { switch (action.type) { case RESET_FOOTER_ADS: return { ...state, footerAds: state.baseAds, footerAdType: 'base' }; case SET_BASE_ADS: return { ...state, baseAds: action.ads, }; case SET_FOOTER_ADS: return { ...state, footerAds: action.ads, footerAdType: action.footerAdType }; case REMEMBER_BASE_AD_PLAYING_INDEX: return { ...state, baseAdPlayingIndex: action.baseAdPlayingIndex }; case ADD_PLAY_RECORD: if (_.has(state.playRecords, action.id)) { return { ...state, playRecords: { ...state.playRecords, [action.id]: state.playRecords[action.id] + 1 } }; } return { ...state, playRecords: { ...state.playRecords, [action.id]: 1 } }; case CLEAR_PLAY_RECORD: return { ...state, playRecords: {} } default: return state; } };
mit
GrinningHermit/Cozmo-Explorer-Tool
event_monitor.py
6740
""" Event Monitor for Cozmo ============================ Based on Event Monitor for cozmo-tools: https://github.com/touretzkyds/cozmo-tools Created by: David S. Touretzky, Carnegie Mellon University Edited by: GrinningHermit ===== """ import re import threading import time import cozmo robot = None q = None # dependency on queue variable for messaging instead of printing to event-content directly thread_running = False # starting thread for custom events # custom eventlistener for picked-up and falling state, more states could be added class CheckState (threading.Thread): def __init__(self, thread_id, name, _q): threading.Thread.__init__(self) self.threadID = thread_id self.name = name self.q = _q def run(self): delay = 10 is_picked_up = False is_falling = False is_on_charger = False while thread_running: if robot.is_picked_up: delay = 0 if not is_picked_up: is_picked_up = True msg = 'cozmo.robot.Robot.is_pickup_up: True' self.q.put(msg) elif is_picked_up and delay > 9: is_picked_up = False msg = 'cozmo.robot.Robot.is_pickup_up: False' self.q.put(msg) elif delay <= 9: delay += 1 if robot.is_falling: if not is_falling: is_falling = True msg = 'cozmo.robot.Robot.is_falling: True' self.q.put(msg) elif not robot.is_falling: if is_falling: is_falling = False msg = 'cozmo.robot.Robot.is_falling: False' self.q.put(msg) if robot.is_on_charger: if not is_on_charger: is_on_charger = True msg = 'cozmo.robot.Robot.is_on_charger: True' self.q.put(msg) elif not robot.is_on_charger: if is_on_charger: is_on_charger = False msg = 'cozmo.robot.Robot.is_on_charger: False' self.q.put(msg) time.sleep(0.1) def print_prefix(evt): msg = evt.event_name + ' ' return msg def print_object(obj): if isinstance(obj,cozmo.objects.LightCube): cube_id = next(k for k,v in robot.world.light_cubes.items() if v==obj) msg = 'LightCube-' + str(cube_id) else: r = re.search('<(\w*)', obj.__repr__()) msg = r.group(1) return msg def monitor_generic(evt, **kwargs): msg = print_prefix(evt) if 'behavior_type_name' in kwargs: msg += kwargs['behavior_type_name'] + ' ' if 'obj' in kwargs: msg += print_object(kwargs['obj']) + ' ' if 'action' in kwargs: action = kwargs['action'] if isinstance(action, cozmo.anim.Animation): msg += action.anim_name + ' ' elif isinstance(action, cozmo.anim.AnimationTrigger): msg += action.trigger.name + ' ' msg += str(set(kwargs.keys())) q.put(msg) def monitor_EvtActionCompleted(evt, action, state, failure_code, failure_reason, **kwargs): msg = print_prefix(evt) msg += print_object(action) + ' ' if isinstance(action, cozmo.anim.Animation): msg += action.anim_name elif isinstance(action, cozmo.anim.AnimationTrigger): msg += action.trigger.name if failure_code is not None: msg += str(failure_code) + failure_reason q.put(msg) def monitor_EvtObjectTapped(evt, *, obj, tap_count, tap_duration, tap_intensity, **kwargs): msg = print_prefix(evt) msg += print_object(obj) msg += ' count=' + str(tap_count) + ' duration=' + str(tap_duration) + ' intensity=' + str(tap_intensity) q.put(msg) def monitor_face(evt, face, **kwargs): msg = print_prefix(evt) name = face.name if face.name is not '' else '[unknown face]' msg += name + ' face_id=' + str(face.face_id) q.put(msg) dispatch_table = { cozmo.action.EvtActionStarted : monitor_generic, cozmo.action.EvtActionCompleted : monitor_EvtActionCompleted, cozmo.behavior.EvtBehaviorStarted : monitor_generic, cozmo.behavior.EvtBehaviorStopped : monitor_generic, cozmo.anim.EvtAnimationsLoaded : monitor_generic, cozmo.anim.EvtAnimationCompleted : monitor_EvtActionCompleted, # cozmo.objects.EvtObjectAvailable : monitor_generic, # deprecated cozmo.objects.EvtObjectAppeared : monitor_generic, cozmo.objects.EvtObjectDisappeared : monitor_generic, cozmo.objects.EvtObjectObserved : monitor_generic, cozmo.objects.EvtObjectTapped : monitor_EvtObjectTapped, cozmo.faces.EvtFaceAppeared : monitor_face, cozmo.faces.EvtFaceObserved : monitor_face, cozmo.faces.EvtFaceDisappeared : monitor_face, } excluded_events = { # Occur too frequently to monitor by default cozmo.objects.EvtObjectObserved, cozmo.faces.EvtFaceObserved, } def monitor(_robot, _q, evt_class=None): if not isinstance(_robot, cozmo.robot.Robot): raise TypeError('First argument must be a Robot instance') if evt_class is not None and not issubclass(evt_class, cozmo.event.Event): raise TypeError('Second argument must be an Event subclass') global robot global q global thread_running robot = _robot q = _q thread_running = True if evt_class in dispatch_table: robot.world.add_event_handler(evt_class,dispatch_table[evt_class]) elif evt_class is not None: robot.world.add_event_handler(evt_class,monitor_generic) else: for k,v in dispatch_table.items(): if k not in excluded_events: robot.world.add_event_handler(k,v) thread_is_state_changed = CheckState(1, 'ThreadCheckState', q) thread_is_state_changed.start() def unmonitor(_robot, evt_class=None): if not isinstance(_robot, cozmo.robot.Robot): raise TypeError('First argument must be a Robot instance') if evt_class is not None and not issubclass(evt_class, cozmo.event.Event): raise TypeError('Second argument must be an Event subclass') global robot global thread_running robot = _robot thread_running = False try: if evt_class in dispatch_table: robot.world.remove_event_handler(evt_class,dispatch_table[evt_class]) elif evt_class is not None: robot.world.remove_event_handler(evt_class,monitor_generic) else: for k,v in dispatch_table.items(): robot.world.remove_event_handler(k,v) except Exception: pass
mit
geekmakerteam/gdp
gdp_android/app/src/androidTest/java/gdp/com/gdp/ApplicationTest.java
342
package gdp.com.gdp; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
ThorbenKuck/NetCom
src/main/java/de/thorbenkuck/netcom/exceptions/CommandNotRegisteredException.java
245
package de.thorbenkuck.netcom.exceptions; public class CommandNotRegisteredException extends RuntimeException { public CommandNotRegisteredException(Class clazz) { super("The command: " + clazz.getSimpleName() + " is not registered!"); } }
mit
dertroglodyt/ScribeOP
src/main/java/de/dertroglodyt/scribeop/OPGameSystem.java
687
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.dertroglodyt.scribeop; import de.dertroglodyt.scribeop.json.JSONException; import de.dertroglodyt.scribeop.json.JSONObject; /** * * @author dertroglodyt */ public class OPGameSystem { public final String id; public final String name; public OPGameSystem(JSONObject json) throws JSONException { super(); id = json.getStringOrNull("id"); name = json.getStringOrNull("name"); } @Override public String toString() { return name; } public String toLongString() { return name + " ID: " + id; } }
mit
Lunik/tcloud
src/server/model/search/jackett.js
2268
import Request from 'request-promise' import { parseString } from 'xml2js' export default class JackettAPI { constructor (options) { this.apiKey = options.apiKey this.endpoint = options.endpoint process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0 } _getUrl (query, category, count) { return `${this.endpoint}?apikey=${this.apiKey}&t=search&cat=${category}&q=${query}` } _getCat (category) { switch (category) { case 'TV': return "5000,5020,5030,5040,5045,5050,5060,5070,5080" case 'Movie': default: return "2000,2010,2020,2030,2040,2045,2050,2060" } } _getSizeItem (bytes) { var sizes = ['o', 'ko', 'mo', 'go', 'to'] if (bytes === 0) { return '0 b' } var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10) return `${Math.round(bytes / Math.pow(1024, i), 2)} ${sizes[i]}` } _formatItem (item) { return { title: item.title[0], seeds: item['torznab:attr'].filter((attr) => attr['$'].name === 'seeders')[0]['$'].value, peers: item['torznab:attr'].filter((attr) => attr['$'].name === 'peers')[0]['$'].value, size: this._getSizeItem(item.size[0]), link: item.link[0] } } _parseResult (data) { return new Promise((resolve, reject) => { data = parseString(data, (err, json) => { if (err) { return reject(err) } let torrents = [] if (json.rss.channel[0].hasOwnProperty('item')) { torrents = json.rss.channel[0].item.map((item) => this._formatItem(item)) } resolve(torrents) }) }) } search (query, category, count) { return new Promise((resolve, reject) => { let url = this._getUrl(query, category, count) let options = { uri: this.endpoint, qs: { method: "GET", strictSSL: false, apikey: this.apiKey, t: 'search', cat: this._getCat(category), q: query }, json: true } Request(options).then((data) => { return this._parseResult(data) }).then(resolve).catch(reject) }) } getMagnet (torrent) { return new Promise((resolve, reject) => { resolve(torrent.link) }) } }
mit
tbossi/Aenigmata
src/com/tbossi/aenigmata/puzzle/crossword/Clue.java
1165
package com.tbossi.aenigmata.puzzle.crossword; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; public abstract class Clue<W extends Word<?,?>> { private ObjectProperty<W> word; private SimpleStringProperty clue; public Clue(String clue, W word) { this.clue = new SimpleStringProperty(); setClue(clue); this.word = new SimpleObjectProperty<W>(); setWord(word); } public ObjectProperty<W> wordProperty() { return word; } public W getWord() { return word.get(); } public void setWord(W word) { if (word == null) throw new IllegalArgumentException("Word should not be null."); this.word.set(word); } /** * Defines the clue of the word. */ public SimpleStringProperty clueProperty() { return this.clue; } /** * Gets the clue string of the word. * @return the clue string. */ public String getClue() { return this.clue.get(); } /** * Sets the clue string. * @param clue */ public void setClue(String clue) { this.clue.set(clue); } }
mit
raeffu/prog1
src/_excercises/ch03/HouseComponent.java
358
package _excercises.ch03; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; /** This component draws a house. */ public class HouseComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; House house = new House(5, 100); house.draw(g2); } }
mit
Microsoft/vscode
src/vs/workbench/common/editor/resourceEditorInput.ts
6250
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { Verbosity, IEditorInputWithPreferredResource, EditorInputCapabilities } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { URI } from 'vs/base/common/uri'; import { IFileService, FileSystemProviderCapabilities } from 'vs/platform/files/common/files'; import { ILabelService } from 'vs/platform/label/common/label'; import { dirname, isEqual } from 'vs/base/common/resources'; /** * The base class for all editor inputs that open resources. */ export abstract class AbstractResourceEditorInput extends EditorInput implements IEditorInputWithPreferredResource { override get capabilities(): EditorInputCapabilities { let capabilities = EditorInputCapabilities.CanSplitInGroup; if (this.fileService.canHandleResource(this.resource)) { if (this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly)) { capabilities |= EditorInputCapabilities.Readonly; } } else { capabilities |= EditorInputCapabilities.Untitled; } return capabilities; } private _preferredResource: URI; get preferredResource(): URI { return this._preferredResource; } constructor( readonly resource: URI, preferredResource: URI | undefined, @ILabelService protected readonly labelService: ILabelService, @IFileService protected readonly fileService: IFileService ) { super(); this._preferredResource = preferredResource || resource; this.registerListeners(); } private registerListeners(): void { // Clear our labels on certain label related events this._register(this.labelService.onDidChangeFormatters(e => this.onLabelEvent(e.scheme))); this._register(this.fileService.onDidChangeFileSystemProviderRegistrations(e => this.onLabelEvent(e.scheme))); this._register(this.fileService.onDidChangeFileSystemProviderCapabilities(e => this.onLabelEvent(e.scheme))); } private onLabelEvent(scheme: string): void { if (scheme === this._preferredResource.scheme) { this.updateLabel(); } } private updateLabel(): void { // Clear any cached labels from before this._name = undefined; this._shortDescription = undefined; this._mediumDescription = undefined; this._longDescription = undefined; this._shortTitle = undefined; this._mediumTitle = undefined; this._longTitle = undefined; // Trigger recompute of label this._onDidChangeLabel.fire(); } setPreferredResource(preferredResource: URI): void { if (!isEqual(preferredResource, this._preferredResource)) { this._preferredResource = preferredResource; this.updateLabel(); } } private _name: string | undefined = undefined; override getName(skipDecorate?: boolean): string { if (typeof this._name !== 'string') { this._name = this.labelService.getUriBasenameLabel(this._preferredResource); } return skipDecorate ? this._name : this.decorateLabel(this._name); } override getDescription(verbosity = Verbosity.MEDIUM): string | undefined { switch (verbosity) { case Verbosity.SHORT: return this.shortDescription; case Verbosity.LONG: return this.longDescription; case Verbosity.MEDIUM: default: return this.mediumDescription; } } private _shortDescription: string | undefined = undefined; private get shortDescription(): string { if (typeof this._shortDescription !== 'string') { this._shortDescription = this.labelService.getUriBasenameLabel(dirname(this._preferredResource)); } return this._shortDescription; } private _mediumDescription: string | undefined = undefined; private get mediumDescription(): string { if (typeof this._mediumDescription !== 'string') { this._mediumDescription = this.labelService.getUriLabel(dirname(this._preferredResource), { relative: true }); } return this._mediumDescription; } private _longDescription: string | undefined = undefined; private get longDescription(): string { if (typeof this._longDescription !== 'string') { this._longDescription = this.labelService.getUriLabel(dirname(this._preferredResource)); } return this._longDescription; } private _shortTitle: string | undefined = undefined; private get shortTitle(): string { if (typeof this._shortTitle !== 'string') { this._shortTitle = this.getName(true /* skip decorations */); } return this._shortTitle; } private _mediumTitle: string | undefined = undefined; private get mediumTitle(): string { if (typeof this._mediumTitle !== 'string') { this._mediumTitle = this.labelService.getUriLabel(this._preferredResource, { relative: true }); } return this._mediumTitle; } private _longTitle: string | undefined = undefined; private get longTitle(): string { if (typeof this._longTitle !== 'string') { this._longTitle = this.labelService.getUriLabel(this._preferredResource); } return this._longTitle; } override getTitle(verbosity?: Verbosity): string { switch (verbosity) { case Verbosity.SHORT: return this.decorateLabel(this.shortTitle); case Verbosity.LONG: return this.decorateLabel(this.longTitle); default: case Verbosity.MEDIUM: return this.decorateLabel(this.mediumTitle); } } private decorateLabel(label: string): string { const readonly = this.hasCapability(EditorInputCapabilities.Readonly); const orphaned = this.isOrphaned(); return decorateFileEditorLabel(label, { orphaned, readonly }); } isOrphaned(): boolean { return false; } } export function decorateFileEditorLabel(label: string, state: { orphaned: boolean, readonly: boolean }): string { if (state.orphaned && state.readonly) { return localize('orphanedReadonlyFile', "{0} (deleted, read-only)", label); } if (state.orphaned) { return localize('orphanedFile', "{0} (deleted)", label); } if (state.readonly) { return localize('readonlyFile', "{0} (read-only)", label); } return label; }
mit
Karasiq/scalajs-highcharts
src/main/scala/com/highcharts/config/PlotOptionsMfiLabelStyle.scala
903
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highcharts]] */ package com.highcharts.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>plotOptions-mfi-label-style</code> */ @js.annotation.ScalaJSDefined class PlotOptionsMfiLabelStyle extends com.highcharts.HighchartsGenericObject { val fontWeight: js.UndefOr[String] = js.undefined } object PlotOptionsMfiLabelStyle { /** */ def apply(fontWeight: js.UndefOr[String] = js.undefined): PlotOptionsMfiLabelStyle = { val fontWeightOuter: js.UndefOr[String] = fontWeight com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsMfiLabelStyle { override val fontWeight: js.UndefOr[String] = fontWeightOuter }) } }
mit
Lymia/CivV_Mod2DLC
project/LuaJITBuild.scala
4529
/* * Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import sbt._ import sbt.Keys._ import Config._ import Utils._ object LuaJITBuild { val coreCount = java.lang.Runtime.getRuntime.availableProcessors def make(dir: File, actions: Seq[String], env: Map[String, String]) = runProcess(config_make +: "--trace" +: "-C" +: dir.toString +: "-j" +: coreCount.toString +: (actions ++ env.map(x => s"${x._1}=${x._2}"))) case class LuaJITPatchFile(platform: String, file: File) object Keys { val luajitCacheDir = SettingKey[File]("luajit-cache-dir") val luajitSourceDir = SettingKey[File]("luajit-source-dir") val luajitIncludes = SettingKey[File]("luajit-includes") val luajitFiles = TaskKey[Seq[LuaJITPatchFile]]("luajit-files") } import Keys._ // Patch build script val settings = Seq( luajitCacheDir := crossTarget.value / "luajit-cache", luajitSourceDir := baseDirectory.value / "src" / "patch" / "native" / "luajit", luajitIncludes := luajitSourceDir.value / "src", luajitFiles := { val patchDirectory = luajitCacheDir.value / "output" val logger = streams.value.log IO.createDirectory(patchDirectory) for (platform <- Seq("win32", "macos", "linux")) yield { val (platformEnv, flags, outputFile, extension, target_cc, target) = platform match { case "win32" => (Map("CROSS" -> config_mingw_prefix, "TARGET_SYS" -> "Windows"), Seq("-static-libgcc", "-Wl,--start-group", "-lmsvcr90", "-Wno-unused-command-line-argument") ++ config_win32_secureFlags, "src/lua51.dll", ".dll", config_win32_cc, config_target_win32) case "macos" => (Map("CROSS" -> config_macos_prefix, "TARGET_SYS" -> "Darwin"), Seq(s"--target=$config_target_macos"), "src/libluajit.so", ".dylib", config_macos_cc, config_target_macos) case "linux" => (Map(), Seq(s"--target=$config_target_linux"), "src/libluajit.so", ".so", config_linux_cc, config_target_linux) } val env = Map( "HOST_CC" -> s"$config_linux_cc -m32", "STATIC_CC" -> target_cc, "DYNAMIC_CC" -> s"$target_cc -fPIC", "TARGET_LD" -> target_cc, "TARGET_FLAGS" -> ("-O2" +: s"--target=$target" +: (config_common_secureFlags ++ flags)).mkString(" ") ) ++ platformEnv val excludeDeps = Set( "lj_bcdef.h", "lj_ffdef.h", "lj_libdef.h", "lj_recdef.h", "lj_folddef.h", "buildvm_arch.h", "vmdef.lua" ) val dependencies = Path.allSubpaths(luajitSourceDir.value).filter { case (_, x) => (x.endsWith(".c") || x.endsWith(".h") || x.endsWith("Makefile") || x.endsWith(".lua")) && !excludeDeps.contains(x.split("/").last) }.map(_._1) val outTarget = patchDirectory / s"luajit_$platform$extension" val outputPath = trackDependencies(luajitCacheDir.value / (platform + "_c_out"), dependencies.toSet) { logger.info("Compiling Luajit for "+platform) make(luajitSourceDir.value, Seq("clean"), env) make(luajitSourceDir.value, Seq("default"), env) IO.copyFile(luajitSourceDir.value / outputFile, outTarget) outTarget } LuaJITPatchFile(platform, outTarget) } } ) }
mit
neekolas/uhuru-wiki
frontend/app.js
548
"use strict"; var isDeleted = require("./is-deleted"); require("./identify-user"); require("./enable-link-clicking"); if (!isDeleted) { require("./paste"); require("./paste-media")(document.getElementById("content")); require("./medium-editor"); require("./editor-initialize")(); //require("./upload-attachments"); require("./upload-images"); require("./delete-image"); } require("./highlight-code"); require("./cover-image-loader"); require("./language-switcher"); require("./page-actions"); require("./resize-iframe");
mit
e1r0nd/codewars
(6 kyu) IQ Test/(6 kyu) IQ Test.js
1295
// #1 Using for loop // function iqTest(numbers) { // numbers = numbers.split(' '); // const evens = []; // const odds = []; // for (let i = 0; i < numbers.length; i++) { // numbers[i] & 1 ? odds.push(i + 1) : evens.push(i + 1); // } // return evens.length === 1 ? evens[0] : odds[0]; // } // #2 Using "some" // const iqTest = (numbers) => { // const evenOdd = [[0, 0], [0, 0]]; // numbers.split(' ').some((num, i) => { // const n = num % 2; // evenOdd[n][0]++; // store quantity // evenOdd[n][1] = i; // store its index // if (evenOdd[n][0] > 1 && evenOdd[+!n][0] == 1) { // return true; // stop iterating when found // } // }); // return ++evenOdd[evenOdd[0][0] == 1 ? 0 : 1][1]; // }; // #3 Using "filter" // const iqTest = (numbers) => { // numbers = numbers.split(' ').map((el) => +el); // const odd = numbers.filter((el) => el % 2 === 1); // const even = numbers.filter((el) => el % 2 === 0); // return odd.length < even.length // ? numbers.indexOf(odd[0]) + 1 // : numbers.indexOf(even[0]) + 1; // }; // #4 Using "reduce" const iqTest = (numbers) => { numbers = numbers.split` `.map((x) => +x % 2); return ( (numbers.reduce((x, y) => x + y) === 1 ? numbers.indexOf(1) : numbers.indexOf(0)) + 1 ); };
mit
renatopp/ghost-editor
src/editor/project/managers/TreeManager.js
2634
b3e.project.TreeManager = function(editor, project) { "use strict"; /** * Adds a new tree to the project. */ this.add = function(_id) { var tree; if (_id instanceof b3e.tree.Tree) { tree = _id; project.addChild(tree); editor.trigger('treeadded', tree); this.select(tree); } else { project.history._beginBatch(); tree = new b3e.tree.Tree(editor, project); var root = tree.nodes.getRoot(); project.addChild(tree); editor.trigger('treeadded', tree); if (_id) tree._id = _id; // select if this is the only tree this.select(tree); var _old = [this, this.remove, [tree]]; var _new = [this, this.add, [tree]]; project.history._add(new b3e.Command(_old, _new)); project.history._endBatch(); } return tree; }; /** * Gets a tree by id. */ this.get = function(tree) { if (typeof tree === 'string') { for (var i=0; i<project.children.length; i++) { if (project.children[i]._id === tree) { return project.children[i]; } } return undefined; } return tree; }; this.getSelected = function() { return project._selectedTree; }; /** * Select a tree. */ this.select = function(tree) { tree = this.get(tree); if (!tree || project.getChildIndex(tree)<0) return; if (project._selectedTree === tree) return; if (project._selectedTree) { project._selectedTree.visible = false; editor.trigger('treedeselected', project._selectedTree); } tree.visible = true; project._selectedTree = tree; editor.trigger('treeselected', tree); }; /** * Removes a tree from the project. */ this.remove = function(tree) { project.history._beginBatch(); tree = this.get(tree); var idx = project.children.indexOf(tree); project.removeChild(tree); // project.nodes.remove(tree._id); editor.trigger('treeremoved', tree); if (project.children.length === 0) { this.add(); } else if (tree === project._selectedTree) { this.select(idx===0?project.children[idx]:project.children[idx-1]); } var _old = [this, this.add, [tree]]; var _new = [this, this.remove, [tree]]; project.history._add(new b3e.Command(_old, _new)); project.history._endBatch(); }; /** * Iterates over tree list. */ this.each = function(callback, thisarg) { project.children.forEach(callback, thisarg); }; this._applySettings = function(settings) { this.each(function(tree) { tree._applySettings(settings); }); }; };
mit
substack/editor-timeline
lib/mark.js
1313
var fs = require('fs'); var html = fs.readFileSync(__dirname + '/mark.html', 'utf8'); var domify = require('domify'); var Left = require('./left.js'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; module.exports = Mark; inherits(Mark, EventEmitter); function Mark (pos) { var self = this; if (!(this instanceof Mark)) return new Mark(pos); this.pos = pos; var div = this.element = domify(html); div.addEventListener('click', function (ev) { ev.stopPropagation(); self.emit('click', div); }); div.addEventListener('mousedown', function (ev) { window.addEventListener('mouseup', mouseup); function mouseup () { pos.setPixels(div.style.left); window.removeEventListener('mouseup', mouseup); } }); if (pos.px) self.element.style.left = pos.px; pos.on('left', function (px) { self.element.style.left = px; }); pos.on('seconds', function (sec) { self.emit('seconds', sec); }); } Mark.prototype.appendTo = function (target) { if (typeof target === 'string') target = document.querySelector(target); target.appendChild(this.element); }; Mark.prototype.getSeconds = function () { return this.pos.seconds || 0; };
mit