text
stringlengths
2
1.05M
/* * * Loading actions * */ import { ADD_ITEM_TO_LOADING, REMOVE_ITEM_FROM_LOADING } from './constants'; export function addItemToLoading(item) { return { type: ADD_ITEM_TO_LOADING, item }; } export function removeItemFromLoading(item) { return { type: REMOVE_ITEM_FROM_LOADING, item }; }
$(function () { //获取顶级菜单 function getAmenu() { function amenuCB(data) { var tpl = $('#J_tpl_Amenu').html(); var menu = juicer(tpl, data); $('#J_Amenu').html(menu); } requestUrl('/menu/top', 'GET', '', amenuCB) } getAmenu(); //获取二级菜单 var Stpl = $('#J_tpl_Smenu').html(); var compiled_tpl = juicer(Stpl); function getSmenu(id, $src) { var data = {top_menu_id: id}; function smenuCB(data) { var adata = { id: id, dat: data } var html = compiled_tpl.render(adata); $('#J_Smenu').append(html); var forceLayout = $($src.attr('href')).height(); $($src.attr('href')).addClass('in'); } requestUrl('/menu/secondary', 'GET', data, smenuCB) } //绑定二级菜单事件 $('#J_Amenu').on('mouseenter.getSmenu', 'li', function () { var $this = $(this); var id = $(this).data('id'); $(this).children('a').addClass('hover'); if ($('#J_Smenu ul[data-id="' + id + '"]').length > 0) return; show_timer = setTimeout(function() { getSmenu(id, $this); }, 300) }).on('mouseleave.getSmenu', 'li', function() { clearTimeout(show_timer) }) $('#J_Smenu').on('click', 'li a', function() { $('.J_iframe_name').html($(this).html()); hideSideMenu(); }) var aside_menu_timer; function hideSideMenu(){ $('#aside-menu .child-list').removeClass('in'); $('#aside-menu .collapsed a').removeClass('hover'); } $('body') // 取消默认行为 .on('click.left_menu_click', '[data-parent="#aside-menu"]', function(e){ e.preventDefault(); e.stopImmediatePropagation(); }) // 鼠标enter显示 .on('mouseenter.left_menu_click', '[data-parent="#aside-menu"]', function (e) { clearTimeout(aside_menu_timer); hideSideMenu(); $($(this).attr('href')).addClass('in'); $(this).children('a').addClass('hover'); }) // 鼠标leave隐藏 .on('mouseleave.left_menu_click', '[data-parent="#aside-menu"]', function (e) { var _this = this; aside_menu_timer = setTimeout(function(){ $('#aside-menu .child-list').removeClass('in'); $('#aside-menu .collapsed a').removeClass('hover'); }, 400) }) .on('mouseenter.left_menu_click', '#aside-menu .child-list', function (e) { clearTimeout(aside_menu_timer); }) .on('mouseleave.left_menu_click', '#aside-menu .child-list', function (e) { hideSideMenu(); }); })
/* ------------------------------------------------------------------------------ * * # Editable component * * Specific JS code additions for form_editable.html page * * Version: 1.0 * Latest update: Aug 1, 2015 * * ---------------------------------------------------------------------------- */ $(function() { // Override defaults // ------------------------------ // Disable highlight $.fn.editable.defaults.highlight = false; // Output template $.fn.editableform.template = '<form class="editableform">' + '<div class="control-group">' + '<div class="editable-input"></div> <div class="editable-buttons"></div>' + '<div class="editable-error-block"></div>' + '</div> ' + '</form>' // Set popup mode as default $.fn.editable.defaults.mode = 'popup'; // Buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary btn-icon editable-submit"><i class="icon-check"></i></button>' + '<button type="button" class="btn btn-default btn-icon editable-cancel"><i class="icon-x"></i></button>'; // Demo settings // ------------------------------ // Toggle editable state var toggleState = document.querySelector('.switchery'); var toggleStateInit = new Switchery(toggleState); toggleState.onchange = function() { if(toggleState.checked) { $('.editable').editable('enable'); } else { $('.editable').editable('disable'); } }; // Write log in console function log(settings, response) { var s = [], str; s.push(settings.type.toUpperCase() + ' url = "' + settings.url + '"'); for(var a in settings.data) { if(settings.data[a] && typeof settings.data[a] === 'object') { str = []; for(var j in settings.data[a]) {str.push(j+': "'+settings.data[a][j]+'"');} str = '{ '+str.join(', ')+' }'; } else { str = '"'+settings.data[a]+'"'; } s.push(a + ' = ' + str); } s.push('RESPONSE: status = ' + response.status); if(response.responseText) { if($.isArray(response.responseText)) { s.push('['); $.each(response.responseText, function(i, v){ s.push('{value: ' + v.value+', text: "'+v.text+'"}'); }); s.push(']'); } else { s.push($.trim(response.responseText)); } } s.push('--------------------------------------\n'); }; // Basic editable components // ------------------------------ // Editable text field $('#text-field').editable(); // Disable clear button $('#disabled-clear').editable({ clear: false }); // With helper text $('#text-field-help').editable(); $('#text-field-help').on('shown', function(e, editable) { $('<span class="help-block">This is a help block</div>').insertAfter(editable.input.$input); }); // Empty field $('#empty-field').editable(); // Required text field $('#empty-field-validate').editable({ validate: function(value) { if($.trim(value) == '') return 'This field is required'; } }); // // Textareas // // Textarea $('#textarea').editable({ rows: 2, showbuttons: 'bottom' }); // Elastic textarea $('#textarea-elastic').editable({ rows: 2, showbuttons: 'bottom' }); $('#textarea-elastic').on('shown', function(e, editable) { editable.input.$input.addClass('elastic').autosize(); }); // // Buttons and icons // // Button variations $('#button-variation').editable(); $('#button-variation').on('shown', function(e, editable) { editable.input.$input.parents('.editable-input').parent().find('.editable-submit').removeClass('btn-success').addClass('btn-danger'); editable.input.$input.parents('.editable-input').parent().find('.editable-cancel').removeClass('btn-danger').addClass('btn-success'); }); // Icon variations $('#icon-variation').editable(); $('#icon-variation').on('shown', function(e, editable) { editable.input.$input.parents('.editable-input').parent().find('.editable-submit').children().removeClass('icon-check').addClass('icon-task'); editable.input.$input.parents('.editable-input').parent().find('.editable-cancel').children().removeClass('icon-x').addClass('icon-menu6'); }); // // Dates // // Date field $('#date').editable({ showbuttons: 'bottom' }); // Date picker $('#datepicker').editable({ showbuttons: 'bottom', datepicker: { isRTL: true, autoSize: true } }); // Date time $('#datetime').editable({ combodate: { firstItem: 'name' }, showbuttons: 'bottom' }); // // Multiple fields // // Simulate ajax requests $.mockjax({ url: '/address', response: function(settings) { log(settings, this); } }); // Initialize $('#multiple-fields').editable({ url: '/address', showbuttons: 'bottom', value: { city: "Moscow", street: "Lenina", building: "12" }, tpl: '<div class="editable-address form-group"><label>City: </label><input type="text" name="city" class="form-control"></div>'+ '<div class="editable-address form-group"><label>Street: </label><input type="text" name="street" class="form-control"></div>'+ '<div class="editable-address form-group"><label>Building: </label><input type="text" name="building" class="form-control"></div>', validate: function(value) { if(value.city == '') return 'city is required!'; }, display: function(value) { if(!value) { $(this).empty(); return; } var html = '<b>' + $('<div>').text(value.city).html() + '</b>, ' + $('<div>').text(value.street).html() + ' st., bld. ' + $('<div>').text(value.building).html(); $(this).html(html); } }); // // Input groups // // Addons $('#input-group-addon').editable(); $('#input-group-addon').on('shown', function (e, editable) { editable.input.$input.wrap('<div class="input-group"></div>'); $('<span class="input-group-addon"><i class="icon-mention"></i></span>').insertBefore(editable.input.$input); }); // Buttons $('#input-group-button').editable(); $('#input-group-button').on('shown', function (e, editable) { editable.input.$input.wrap('<div class="input-group"></div>'); $('<div class="input-group-btn"><button type="button" class="btn btn-default">Button</button></div>').insertBefore(editable.input.$input); }); // Dropdown $('#input-group-dropdown').editable(); $('#input-group-dropdown').on('shown', function (e, editable) { editable.input.$input.wrap('<div class="input-group"></div>'); $('<div class="input-group-btn"><button type="button" class="btn btn-default btn-icon" data-toggle="dropdown"><i class="icon-cog5"></i> <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> </ul> </div>').insertBefore(editable.input.$input); }); // Basic selects // ------------------------------ // Basic select $('#select-default').editable({ prepend: "Not selected", source: [ {value: 1, text: 'Male'}, {value: 2, text: 'Female'} ], display: function(value, sourceData) { var colors = {"": "gray", 1: "green", 2: "blue"}, elem = $.grep(sourceData, function(o){return o.value == value;}); if(elem.length) { $(this).text(elem[0].text).css("color", colors[value]); } else { $(this).empty(); } } }); // // Dependent select // // Simulate ajax requests $.mockjax({ url: '/default-list', responseTime: 400, response: function(settings) { if(settings.data.value == 'err') { this.status = 500; this.responseText = 'Validation error!'; } else { this.responseText = ''; } } }); // Data var sources = { 1: [{value: 11, text: 11}, {value: 111, text: 111}], 2: [{value: 22, text: 22}, {value: 222, text: 222}] }; // Initialize first list $('#default-list').editable({ url: '/default-list', pk: 1, source: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}], title: 'Select1', success: function(response, newValue) { $('#dependent-list').editable('option', 'source', sources[newValue]); $('#dependent-list').editable('setValue', null); } }); // Initialize dependent list $('#dependent-list').editable({ url: '/default-list', pk: 1, title: 'Select2', sourceError: 'Please, select value in first list' }); // // Select with remote source // // Simulate ajax requests $.mockjax({ url: '/remote', response: function(settings) { this.responseText = [ {value: 0, text: 'Guest'}, {value: 1, text: 'Service'}, {value: 2, text: 'Customer'}, {value: 3, text: 'Operator'}, {value: 4, text: 'Support'}, {value: 5, text: 'Admin'} ]; log(settings, this); } }); // Initialize $('#select-default-remote').editable({ source: '/remote', showbuttons: false }); // // Select with loading error // // Simulate ajax requests $.mockjax({ url: '/error', status: 500, response: function(settings) { this.responseText = 'Internal Server Error'; } }); // Initialize $('#select-default-error').editable({ source: '/error' }); // Checkboxes and radios // ------------------------------ // Single unstyled checkbox $('#single-unstyled-checkbox').editable({ source: {'1': 'Enabled'}, emptytext: 'Disabled', showbuttons: 'bottom', tpl: '<div class="checkbox"></div>' }); // Single styled checkbox $('#single-styled-checkbox').editable({ source: {'1': 'Enabled'}, emptytext: 'Disabled', showbuttons: 'bottom', tpl: '<div class="checkbox"></div>' }); $('#single-styled-checkbox').on('shown', function(e, editable) { editable.input.$input.uniform(); }); // Initialize uniform $(".styled, .multiselect-container input, .file-input > :file").uniform({ radioClass: 'choice', fileButtonHtml: '<i class="icon-googleplus"></i>' }); // // Checklists // // Unstyled checklist $('#unstyled-checklist').editable({ source: [ {value: 1, text: 'banana'}, {value: 2, text: 'peach'}, {value: 3, text: 'apple'}, {value: 4, text: 'watermelon'}, {value: 5, text: 'orange'} ], showbuttons: 'bottom', tpl: '<div class="checkbox"></div>' }); // Styled checklist $('#styled-checklist').editable({ source: [ {value: 1, text: 'banana'}, {value: 2, text: 'peach'}, {value: 3, text: 'apple'}, {value: 4, text: 'watermelon'}, {value: 5, text: 'orange'} ], showbuttons: 'bottom', tpl: '<div class="checkbox"></div>' }); // Update uniform dynamically $('#styled-checklist').on('shown', function(e, editable) { editable.input.$input.uniform(); }); // // Single switchery toggle // // Initialize plugin $('#switchery-checkbox').editable({ source: {'1': 'Enabled'}, emptytext: 'Disabled', showbuttons: 'bottom', tpl: '<div class="checkbox checkbox-switchery switchery-xs"></div>' }); // Initialize plugin and insert in editable popup on show $('#switchery-checkbox').on('shown', function (e, editable) { editable.input.$input.addClass('switcher-single'); var elem = document.querySelector('.switcher-single'); var init = new Switchery(elem); }); // // Switchery checklist // // Initialize plugin $('#switchery-checklist').editable({ source: [ {value: 1, text: 'banana'}, {value: 2, text: 'peach'}, {value: 3, text: 'apple'}, {value: 4, text: 'watermelon'}, {value: 5, text: 'orange'} ], showbuttons: 'bottom', tpl: '<div class="checkbox checkbox-switchery switchery-xs"></div>' }); // Initialize plugin and insert in editable popup on show $('#switchery-checklist').on('shown', function(e, editable) { editable.input.$input.addClass('switcher'); var elems = Array.prototype.slice.call(document.querySelectorAll('.switcher')); elems.forEach(function(html) { var switchery = new Switchery(html); }); }); // // Unordered checkbox list // // Initialize editable $.mockjax({ url: '/checkbox-unordered-list', status: 200, responseTime: 200 }); // Add data $.mockjax({ url: '/source-ul', status: 200, responseTime: 400, response: function(settings) { this.responseText = [ {value: 0, text: 'Guest'}, {value: 1, text: 'Service'}, {value: 2, text: 'Customer'}, {value: 3, text: 'Operator'}, {value: 4, text: 'Support'}, {value: 5, text: 'Admin'} ]; } }); // Initialize plugin $('#checkbox-unordered-list').editable({ source: '/source-ul', url: '/checkbox-unordered-list', display: function(value, sourceData) { var $el = $('#list'), checked, html = ''; if(!value) { $el.empty(); return; } checked = $.grep(sourceData, function(o){ return $.grep(value, function(v){ return v == o.value; }).length; }); $.each(checked, function(i, v) { html+= '<li>'+$.fn.editableutils.escape(v.text)+'</li>'; }); if(html) html = '<ul class="list-inline" style="margin-top: 10px;">'+html+'</ul>'; $el.html(html); }, showbuttons: 'bottom', tpl: '<div class="checkbox"></div>' }); // Initialize plugin and insert in editable popup on show $('#checkbox-unordered-list').on('shown', function(e, editable) { editable.input.$input.uniform(); }); // Advanced initialization // ------------------------------ // // Autotext option // // Simulate ajax requests $.mockjax({ url: '/autotext-url', status: 200, responseTime: 200 }); // Add data $.mockjax({ url: '/groups', status: 200, responseTime: 400, response: function(settings) { this.responseText = [ {value: 0, text: 'Guest'}, {value: 1, text: 'Service'}, {value: 2, text: 'Customer'}, {value: 3, text: 'Operator'}, {value: 4, text: 'Support'}, {value: 5, text: 'Admin'} ]; } }); // Initialize $('#editable-autotext').editable({ url: '/autotext-url' }); // // PUT method submit // // Simulate ajax requests $.mockjax({ url: '/editable-put-submit', responseTime: 200, response: function(settings) { console.log(settings); } }); // Initialize $('#editable-put-submit').editable({ url: '/editable-put-submit', ajaxOptions: { type: 'put' } }); // // Render server response // // Simulate ajax requests $.mockjax({ url: '/editable-render-response', responseTime: 400, response: function(settings) { this.responseText = 'New value: <b>'+settings.data.value+'</b>'; } }); // Initialize $('#editable-render-response').editable({ url: '/editable-render-response', display: function(value, response) { $(this).html(response); } }); // // Process JSON response // // Simulate ajax requests $.mockjax({ url: '/editable-json-response', responseTime: 200, response: function(settings) { if(settings.data.value) { this.responseText = '{"success": true}'; } else { this.responseText = '{"success": false, "msg": "required"}'; } } }); // Initialize $('#editable-json-response').editable({ url: '/editable-json-response', ajaxOptions: { dataType: 'json' }, success: function(response, newValue) { if(!response) { return "Unknown error!"; } if(response.success === false) { return response.msg; } } }); // // Input types // // Simulate ajax requests $.mockjax({ url: '/post-fields', response: function(settings) { log(settings, this); } }); // Password $('#type-password').editable({ url: '/post-fields', title: 'Enter your password' }); // Email $('#type-email').editable({ url: '/post-fields', title: 'Enter your email' }); // Url $('#type-url').editable({ url: '/post-fields', title: 'Enter URL' }); // Tel $('#type-tel').editable({ url: '/post-fields', title: 'Enter phone number' }); // Number $('#type-number').editable({ url: '/post-fields', title: 'Enter any number' }); // Range $('#type-range').editable({ url: '/post-fields', title: 'Number range' }); // Time $('#type-time').editable({ url: '/post-fields', title: 'Time' }); // Plugins and extensions // ------------------------------ // // Tag inputs // // Text tags input $('#input-tags-text').editable({ showbuttons: 'bottom', clear: false, display: function(value) { $(this).html(value).addClass('clearfix display-inline-block'); $(this).each(function() { var text = $(this).text().split(','); for( var i = 0, len = text.length; i < len; i++ ) { text[i] = '<span class="text-left">' + text[i] + '</span>'; } $(this).html(text.join('<span class="text-left">, </span>')); }); } }); $('#input-tags-text').on('shown', function(e, editable) { editable.input.$input.tagsinput({ maxTags: 5 }); }); // Label tags input $('#input-tags-labels').editable({ showbuttons: 'bottom', clear: false, display: function(value) { $(this).html(value); $(this).each(function() { var text = $(this).text().split(','); for( var i = 0, len = text.length; i < len; i++ ) { text[i] = '<span class="label label-primary">' + text[i] + '</span>'; } $(this).html(text.join(' ')); }); } }); $('#input-tags-labels').on('shown', function(e, editable) { editable.input.$input.tagsinput({ maxTags: 5 }); }); // // Typeahead // // Initialize editable $('#editable-typeahead').editable({ value: 'California' }); // Typeahead $('#editable-typeahead').on('shown', function(e, editable) { var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { // the typeahead jQuery plugin expects suggestions to a // JavaScript object, refer to typeahead docs for more info matches.push({ value: str }); } }); cb(matches); }; }; // Data var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; // Initialize typeahead editable.input.$input.typeahead( { hint: true, highlight: true, minLength: 1 }, { name: 'states', displayKey: 'value', source: substringMatcher(states) } ).attr('dir', 'rtl'); }); // // Touchspin spinners // // Basic $('#input-touchspin-basic').editable({ clear: false }); $('#input-touchspin-basic').on('shown', function(e, editable) { editable.input.$input.TouchSpin({ min: 0, max: 100, step: 0.1, decimals: 2 }).parent().parent().addClass('editable-touchspin'); }); // Advanced $('#input-touchspin-advanced').editable({ clear: false }); $('#input-touchspin-advanced').on('shown', function(e, editable) { editable.input.$input.TouchSpin({ prefix: '<i class="icon-accessibility"></i>', postfix: '<i class="icon-paragraph-justify2"></i>' }).parent().parent().addClass('editable-touchspin'); }); // // Input mask // // Initialize editable $('#input-mask').editable({ emptytext: 'Your credit card number' }); // Initialize plugin and insert in editable popup on show $('#input-mask').on('shown', function(e, editable) { editable.input.$input.inputmask({ mask: '9999-9999-9999-9999' }); $('<span class="help-block">9999-9999-9999-9999</div>').insertAfter(editable.input.$input); }); // // Input formatter // // Initialize editable $('#input-formatter').editable({ emptytext: 'Your birth date' }); // Initialize plugin and insert in editable popup on show $('#input-formatter').on('shown', function(e, editable) { editable.input.$input.formatter({ pattern: '{{99}}/{{99}}/{{9999}}' }); $('<span class="help-block">99/99/9999</div>').insertAfter(editable.input.$input); }); // Select2 select // ------------------------------ // Data var select2_countries = []; $.each( { "BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina", "BB": "Barbados", "WF": "Wallis and Futuna", "BL": "Saint Bartelemey", "BM": "Bermuda", "BN": "Brunei Darussalam", "BO": "Bolivia", "BH": "Bahrain", "BI": "Burundi", "BJ": "Benin", "BT": "Bhutan", "JM": "Jamaica", "BV": "Bouvet Island", "BW": "Botswana", "WS": "Samoa", "BR": "Brazil", "BS": "Bahamas", "JE": "Jersey", "BY": "Belarus", "O1": "Other Country", "LV": "Latvia", "RW": "Rwanda", "RS": "Serbia", "TL": "Timor-Leste", "RE": "Reunion", "LU": "Luxembourg", "TJ": "Tajikistan", "RO": "Romania", "PG": "Papua New Guinea", "GW": "Guinea-Bissau", "GU": "Guam", "GT": "Guatemala", "GS": "South Georgia and the South Sandwich Islands", "GR": "Greece", }, function(k, v) { select2_countries.push({id: k, text: v}); } ); // Single select $('#select2-single').editable({ source: select2_countries, select2: { width: 200, placeholder: 'Select country', allowClear: true } }); // Multiple select $('#select2-multiple').editable({ showbuttons: 'bottom', select2: { width: 300, tags: ['html', 'javascript', 'css', 'ajax'], tokenSeparators: [",", " "], multiple: true, placeholder: 'Select something' } }); // // Remote source // // Initialize $('#select2-single-remote').editable({ select2: { width: '300', placeholder: 'Select Country', minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", dataType: 'jsonp', data: function (term, page) { return { q: term, // search term page_limit: 10, apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working }; }, results: function (data, page) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to alter remote JSON data return {results: data.movies}; } }, initSelection: function(element, callback) { // the input tag has a value attribute preloaded that points to a preselected movie's id // this function resolves that id attribute to an object that select2 can render // using its formatResult renderer - that way the movie name is shown preselected var id=$(element).val(); if (id!=="") { $.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies/"+id+".json", { data: { apikey: "ju6z9mjyajq2djue3gbvv26t" }, dataType: "jsonp" }).done(function(data) { callback(data); }); } }, formatResult: movieFormatResult, // omitted for brevity, see the source of this page formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results } }); // Format results function movieFormatResult(movie) { var markup = "<table class='movie-result'><tr>"; if (movie.posters !== undefined && movie.posters.thumbnail !== undefined) { markup += "<td class='movie-image'><img src='" + movie.posters.thumbnail + "'/></td>"; } markup += "<td class='movie-info'><div class='movie-title'>" + movie.title + "</div>"; if (movie.critics_consensus !== undefined) { markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>"; } else if (movie.synopsis !== undefined) { markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>"; } markup += "</td></tr></table>"; return markup; } // Format selection function movieFormatSelection(movie) { return movie.title; } });
// 元素类型是否是函数 export function isFunction (virtualDOM) { return virtualDOM && virtualDOM.type && typeof virtualDOM.type === 'function' } // 是否是函数式组件 export function isFunctionElement (virtualDOM) { if (!isFunction(virtualDOM)) { return false } return !(virtualDOM.type.prototype && virtualDOM.type.prototype.render) } // 是否是同一个组件 export function isSameComponent (virtualDOM, oldVirtualDOM) { if (!isFunction(virtualDOM)) return false if (oldVirtualDOM.functionComponent) { // 函数式组件 return virtualDOM.type === oldVirtualDOM.functionComponent } if (oldVirtualDOM.component) { // 类组件 return virtualDOM.type === oldVirtualDOM.component.constructor } return false }
'use strict'; const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); //Get all the post router.get('/', async (req, res) => { try { const posts = await Post.find(); res.json(posts); } catch (err) { res.json({ message: err }); } }); //Specific post router.get('/:postId', async (req, res) => { try { const post = await Post.findById(req.params.postId); res.json(post); } catch (err) { res.json({ message: err }); } }); //Update specfic post router.patch('/postId', async (req, res) => { try { const updatedPost = await Post.updated( { _id: req.params.postId }, { title: req.body.title } ); res.json(updatedPost); } catch (err) { res.json({ message: err }); } }); //Delete specific post router.delete('/:postId', async (req, res) => { try { const removedPost = Post.remove({ _id: req.params.postId }); res.json(removedPost); } catch (err) { res.json({ message: err }); } }); //Submit all the post router.post('/', (req, res) => { const post = new Post({ title: req.body.title, description: req.body.description }); post.save() .then(data => { res.json(data); }) .catch(err => { res.json({ message: err }); }); }); module.exports = router;
/*eslint-disable */ import React from 'react' import Zoom from 'react-reveal/Zoom'; import Fade from 'react-reveal/Fade'; import styled, { css } from 'react-emotion' import Card from '../../components/team/card.js' import Layout from '../../layouts'; import Helmet from '../../components/helmet'; import Img from 'gatsby-image' const teamCards =css` display:flex; flex-wrap:wrap; flex-direction:row; justify-content:center; align-items:center; margin-top:60px; margin-bottom:60px; ` const Wrapper = styled.section` position: relative; margin: 0; ` const BgImg = styled(Img)` position: absolute; margin-top: 0px; top: 0; left: 0; width: 100%; background-color: white; z-index: -1; height: ${props => props.height || 'auto'}; @media (min-width: 35em) { min-height: 300px; } & > img { object-fit: ${props => props.fit || 'cover'} !important; object-position: ${props => props.position || '20% 0%'} !important; } &:before { content: ''; background: rgba(0,0,0,0); position: absolute; top: 0; left: 0; right: 0; bottom: 0; height: 100%; width: 100%; z-index: 1; } ` const Title = styled.h1` font-size: 1.5em; line-height: 1.5em; letter-spacing: 0.05em; text-transform: capitalize; font-weight: 600; position: absolute; width: 90%; max-width: 650px; padding: 0 1rem; top: 50%; left: 50%; transform: translate(-50%, -50%); color: white; text-align: center; `; const Line = styled.h1` display: none; font-size: 2em; font-weight: 600; position: absolute; width: 70%; top: 50%; left: 50%; transform: translate(-50%, -50%); border-left: 3px solid white; height: 2em; `; const BannerSection = (props) => ( <Wrapper> <BgImg height={props.height} sizes={props.image.sizes} position={`50% ${props.position}%`}/> { props.title && <Line /> } { props.title && <Title>{props.title}</Title> } </Wrapper> ) class TeamPage extends React.Component{ render(){ const we= this.props.data.TeamImages.edges['0'].node.teamImages; const bannerImage = this.props.data.BannerImage.edges['0'].node.teamBanner; const yAxisForCoverImage = 20; console.log(this.props) return( <Layout location={this.props.location}> <Helmet title='Tech47 | team' description='Tech47-team' image={bannerImage.sizes} pathname={this.props.location.pathname} absoluteUrl={true} /> <BannerSection title='Our Team' image={bannerImage} height={'50vh'} position={yAxisForCoverImage} /> <div className={teamCards} > { we.map((team) => (<Card key={team.title} description={team.description} pictureUrl={team.resolutions} fullName={team.title}/>)) } </div> </Layout>) } } export const contentfulTeamQuery = graphql` query TeamQuery { TeamImages:allContentfulTeamImages{ edges{ node{ teamImages{ title description resolutions(width:150, height: 150){ ...GatsbyContentfulResolutions } } } } } BannerImage:allContentfulTeamBanner{ edges{ node{ teamBanner{ sizes(maxWidth: 1800, quality:100) { ...GatsbyContentfulSizes_noBase64 } } } } } } `; export default TeamPage;
/* */ "format cjs"; 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 { Injectable } from 'angular2/core'; import { StringMapWrapper } from 'angular2/src/facade/collection'; import { isPresent, isArray } from 'angular2/src/facade/lang'; import * as modelModule from './model'; /** * Creates a form object from a user-specified configuration. * * ### Example ([live demo](http://plnkr.co/edit/ENgZo8EuIECZNensZCVr?p=preview)) * * ```typescript * @Component({ * selector: 'my-app', * viewBindings: [FORM_BINDINGS] * template: ` * <form [ngFormModel]="loginForm"> * <p>Login <input ngControl="login"></p> * <div ngControlGroup="passwordRetry"> * <p>Password <input type="password" ngControl="password"></p> * <p>Confirm password <input type="password" ngControl="passwordConfirmation"></p> * </div> * </form> * <h3>Form value:</h3> * <pre>{{value}}</pre> * `, * directives: [FORM_DIRECTIVES] * }) * export class App { * loginForm: ControlGroup; * * constructor(builder: FormBuilder) { * this.loginForm = builder.group({ * login: ["", Validators.required], * passwordRetry: builder.group({ * password: ["", Validators.required], * passwordConfirmation: ["", Validators.required, asyncValidator] * }) * }); * } * * get value(): string { * return JSON.stringify(this.loginForm.value, null, 2); * } * } * ``` */ export let FormBuilder = class { /** * Construct a new {@link ControlGroup} with the given map of configuration. * Valid keys for the `extra` parameter map are `optionals` and `validator`. * * See the {@link ControlGroup} constructor for more details. */ group(controlsConfig, extra = null) { var controls = this._reduceControls(controlsConfig); var optionals = isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null; var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; var asyncValidator = isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); } /** * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. */ control(value, validator = null, asyncValidator = null) { return new modelModule.Control(value, validator, asyncValidator); } /** * Construct an array of {@link Control}s from the given `controlsConfig` array of * configuration, with the given optional `validator` and `asyncValidator`. */ array(controlsConfig, validator = null, asyncValidator = null) { var controls = controlsConfig.map(c => this._createControl(c)); return new modelModule.ControlArray(controls, validator, asyncValidator); } /** @internal */ _reduceControls(controlsConfig) { var controls = {}; StringMapWrapper.forEach(controlsConfig, (controlConfig, controlName) => { controls[controlName] = this._createControl(controlConfig); }); return controls; } /** @internal */ _createControl(controlConfig) { if (controlConfig instanceof modelModule.Control || controlConfig instanceof modelModule.ControlGroup || controlConfig instanceof modelModule.ControlArray) { return controlConfig; } else if (isArray(controlConfig)) { var value = controlConfig[0]; var validator = controlConfig.length > 1 ? controlConfig[1] : null; var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null; return this.control(value, validator, asyncValidator); } else { return this.control(controlConfig); } } }; FormBuilder = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], FormBuilder); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9ybV9idWlsZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYW5ndWxhcjIvc3JjL2NvbW1vbi9mb3Jtcy9mb3JtX2J1aWxkZXIudHMiXSwibmFtZXMiOlsiRm9ybUJ1aWxkZXIiLCJGb3JtQnVpbGRlci5ncm91cCIsIkZvcm1CdWlsZGVyLmNvbnRyb2wiLCJGb3JtQnVpbGRlci5hcnJheSIsIkZvcm1CdWlsZGVyLl9yZWR1Y2VDb250cm9scyIsIkZvcm1CdWlsZGVyLl9jcmVhdGVDb250cm9sIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7T0FBTyxFQUFDLFVBQVUsRUFBQyxNQUFNLGVBQWU7T0FDakMsRUFBQyxnQkFBZ0IsRUFBQyxNQUFNLGdDQUFnQztPQUN4RCxFQUFDLFNBQVMsRUFBRSxPQUFPLEVBQW1CLE1BQU0sMEJBQTBCO09BQ3RFLEtBQUssV0FBVyxNQUFNLFNBQVM7QUFHdEM7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0F3Q0c7QUFDSDtJQUVFQTs7Ozs7T0FLR0E7SUFDSEEsS0FBS0EsQ0FBQ0EsY0FBb0NBLEVBQ3BDQSxLQUFLQSxHQUF5QkEsSUFBSUE7UUFDdENDLElBQUlBLFFBQVFBLEdBQUdBLElBQUlBLENBQUNBLGVBQWVBLENBQUNBLGNBQWNBLENBQUNBLENBQUNBO1FBQ3BEQSxJQUFJQSxTQUFTQSxHQUFHQSxTQUFTQSxDQUFDQSxLQUFLQSxDQUFDQSxHQUFHQSxnQkFBZ0JBLENBQUNBLEdBQUdBLENBQUNBLEtBQUtBLEVBQUVBLFdBQVdBLENBQUNBLEdBQUdBLElBQUlBLENBQUNBO1FBQ25GQSxJQUFJQSxTQUFTQSxHQUFHQSxTQUFTQSxDQUFDQSxLQUFLQSxDQUFDQSxHQUFHQSxnQkFBZ0JBLENBQUNBLEdBQUdBLENBQUNBLEtBQUtBLEVBQUVBLFdBQVdBLENBQUNBLEdBQUdBLElBQUlBLENBQUNBO1FBQ25GQSxJQUFJQSxjQUFjQSxHQUFHQSxTQUFTQSxDQUFDQSxLQUFLQSxDQUFDQSxHQUFHQSxnQkFBZ0JBLENBQUNBLEdBQUdBLENBQUNBLEtBQUtBLEVBQUVBLGdCQUFnQkEsQ0FBQ0EsR0FBR0EsSUFBSUEsQ0FBQ0E7UUFDN0ZBLE1BQU1BLENBQUNBLElBQUlBLFdBQVdBLENBQUNBLFlBQVlBLENBQUNBLFFBQVFBLEVBQUVBLFNBQVNBLEVBQUVBLFNBQVNBLEVBQUVBLGNBQWNBLENBQUNBLENBQUNBO0lBQ3RGQSxDQUFDQTtJQUNERDs7T0FFR0E7SUFDSEEsT0FBT0EsQ0FBQ0EsS0FBYUEsRUFBRUEsU0FBU0EsR0FBYUEsSUFBSUEsRUFDekNBLGNBQWNBLEdBQWFBLElBQUlBO1FBQ3JDRSxNQUFNQSxDQUFDQSxJQUFJQSxXQUFXQSxDQUFDQSxPQUFPQSxDQUFDQSxLQUFLQSxFQUFFQSxTQUFTQSxFQUFFQSxjQUFjQSxDQUFDQSxDQUFDQTtJQUNuRUEsQ0FBQ0E7SUFFREY7OztPQUdHQTtJQUNIQSxLQUFLQSxDQUFDQSxjQUFxQkEsRUFBRUEsU0FBU0EsR0FBYUEsSUFBSUEsRUFDakRBLGNBQWNBLEdBQWFBLElBQUlBO1FBQ25DRyxJQUFJQSxRQUFRQSxHQUFHQSxjQUFjQSxDQUFDQSxHQUFHQSxDQUFDQSxDQUFDQSxJQUFJQSxJQUFJQSxDQUFDQSxjQUFjQSxDQUFDQSxDQUFDQSxDQUFDQSxDQUFDQSxDQUFDQTtRQUMvREEsTUFBTUEsQ0FBQ0EsSUFBSUEsV0FBV0EsQ0FBQ0EsWUFBWUEsQ0FBQ0EsUUFBUUEsRUFBRUEsU0FBU0EsRUFBRUEsY0FBY0EsQ0FBQ0EsQ0FBQ0E7SUFDM0VBLENBQUNBO0lBRURILGdCQUFnQkE7SUFDaEJBLGVBQWVBLENBQUNBLGNBQW1CQTtRQUNqQ0ksSUFBSUEsUUFBUUEsR0FBaURBLEVBQUVBLENBQUNBO1FBQ2hFQSxnQkFBZ0JBLENBQUNBLE9BQU9BLENBQUNBLGNBQWNBLEVBQUVBLENBQUNBLGFBQWFBLEVBQUVBLFdBQVdBO1lBQ2xFQSxRQUFRQSxDQUFDQSxXQUFXQSxDQUFDQSxHQUFHQSxJQUFJQSxDQUFDQSxjQUFjQSxDQUFDQSxhQUFhQSxDQUFDQSxDQUFDQTtRQUM3REEsQ0FBQ0EsQ0FBQ0EsQ0FBQ0E7UUFDSEEsTUFBTUEsQ0FBQ0EsUUFBUUEsQ0FBQ0E7SUFDbEJBLENBQUNBO0lBRURKLGdCQUFnQkE7SUFDaEJBLGNBQWNBLENBQUNBLGFBQWtCQTtRQUMvQkssRUFBRUEsQ0FBQ0EsQ0FBQ0EsYUFBYUEsWUFBWUEsV0FBV0EsQ0FBQ0EsT0FBT0E7WUFDNUNBLGFBQWFBLFlBQVlBLFdBQVdBLENBQUNBLFlBQVlBO1lBQ2pEQSxhQUFhQSxZQUFZQSxXQUFXQSxDQUFDQSxZQUFZQSxDQUFDQSxDQUFDQSxDQUFDQTtZQUN0REEsTUFBTUEsQ0FBQ0EsYUFBYUEsQ0FBQ0E7UUFFdkJBLENBQUNBO1FBQUNBLElBQUlBLENBQUNBLEVBQUVBLENBQUNBLENBQUNBLE9BQU9BLENBQUNBLGFBQWFBLENBQUNBLENBQUNBLENBQUNBLENBQUNBO1lBQ2xDQSxJQUFJQSxLQUFLQSxHQUFHQSxhQUFhQSxDQUFDQSxDQUFDQSxDQUFDQSxDQUFDQTtZQUM3QkEsSUFBSUEsU0FBU0EsR0FBR0EsYUFBYUEsQ0FBQ0EsTUFBTUEsR0FBR0EsQ0FBQ0EsR0FBR0EsYUFBYUEsQ0FBQ0EsQ0FBQ0EsQ0FBQ0EsR0FBR0EsSUFBSUEsQ0FBQ0E7WUFDbkVBLElBQUlBLGNBQWNBLEdBQUdBLGFBQWFBLENBQUNBLE1BQU1BLEdBQUdBLENBQUNBLEdBQUdBLGFBQWFBLENBQUNBLENBQUNBLENBQUNBLEdBQUdBLElBQUlBLENBQUNBO1lBQ3hFQSxNQUFNQSxDQUFDQSxJQUFJQSxDQUFDQSxPQUFPQSxDQUFDQSxLQUFLQSxFQUFFQSxTQUFTQSxFQUFFQSxjQUFjQSxDQUFDQSxDQUFDQTtRQUV4REEsQ0FBQ0E7UUFBQ0EsSUFBSUEsQ0FBQ0EsQ0FBQ0E7WUFDTkEsTUFBTUEsQ0FBQ0EsSUFBSUEsQ0FBQ0EsT0FBT0EsQ0FBQ0EsYUFBYUEsQ0FBQ0EsQ0FBQ0E7UUFDckNBLENBQUNBO0lBQ0hBLENBQUNBO0FBQ0hMLENBQUNBO0FBNUREO0lBQUMsVUFBVSxFQUFFOztnQkE0RFo7QUFBQSIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7SW5qZWN0YWJsZX0gZnJvbSAnYW5ndWxhcjIvY29yZSc7XG5pbXBvcnQge1N0cmluZ01hcFdyYXBwZXJ9IGZyb20gJ2FuZ3VsYXIyL3NyYy9mYWNhZGUvY29sbGVjdGlvbic7XG5pbXBvcnQge2lzUHJlc2VudCwgaXNBcnJheSwgQ09OU1RfRVhQUiwgVHlwZX0gZnJvbSAnYW5ndWxhcjIvc3JjL2ZhY2FkZS9sYW5nJztcbmltcG9ydCAqIGFzIG1vZGVsTW9kdWxlIGZyb20gJy4vbW9kZWwnO1xuXG5cbi8qKlxuICogQ3JlYXRlcyBhIGZvcm0gb2JqZWN0IGZyb20gYSB1c2VyLXNwZWNpZmllZCBjb25maWd1cmF0aW9uLlxuICpcbiAqICMjIyBFeGFtcGxlIChbbGl2ZSBkZW1vXShodHRwOi8vcGxua3IuY28vZWRpdC9FTmdabzhFdUlFQ1pOZW5zWkNWcj9wPXByZXZpZXcpKVxuICpcbiAqIGBgYHR5cGVzY3JpcHRcbiAqIEBDb21wb25lbnQoe1xuICogICBzZWxlY3RvcjogJ215LWFwcCcsXG4gKiAgIHZpZXdCaW5kaW5nczogW0ZPUk1fQklORElOR1NdXG4gKiAgIHRlbXBsYXRlOiBgXG4gKiAgICAgPGZvcm0gW25nRm9ybU1vZGVsXT1cImxvZ2luRm9ybVwiPlxuICogICAgICAgPHA+TG9naW4gPGlucHV0IG5nQ29udHJvbD1cImxvZ2luXCI+PC9wPlxuICogICAgICAgPGRpdiBuZ0NvbnRyb2xHcm91cD1cInBhc3N3b3JkUmV0cnlcIj5cbiAqICAgICAgICAgPHA+UGFzc3dvcmQgPGlucHV0IHR5cGU9XCJwYXNzd29yZFwiIG5nQ29udHJvbD1cInBhc3N3b3JkXCI+PC9wPlxuICogICAgICAgICA8cD5Db25maXJtIHBhc3N3b3JkIDxpbnB1dCB0eXBlPVwicGFzc3dvcmRcIiBuZ0NvbnRyb2w9XCJwYXNzd29yZENvbmZpcm1hdGlvblwiPjwvcD5cbiAqICAgICAgIDwvZGl2PlxuICogICAgIDwvZm9ybT5cbiAqICAgICA8aDM+Rm9ybSB2YWx1ZTo8L2gzPlxuICogICAgIDxwcmU+e3t2YWx1ZX19PC9wcmU+XG4gKiAgIGAsXG4gKiAgIGRpcmVjdGl2ZXM6IFtGT1JNX0RJUkVDVElWRVNdXG4gKiB9KVxuICogZXhwb3J0IGNsYXNzIEFwcCB7XG4gKiAgIGxvZ2luRm9ybTogQ29udHJvbEdyb3VwO1xuICpcbiAqICAgY29uc3RydWN0b3IoYnVpbGRlcjogRm9ybUJ1aWxkZXIpIHtcbiAqICAgICB0aGlzLmxvZ2luRm9ybSA9IGJ1aWxkZXIuZ3JvdXAoe1xuICogICAgICAgbG9naW46IFtcIlwiLCBWYWxpZGF0b3JzLnJlcXVpcmVkXSxcbiAqICAgICAgIHBhc3N3b3JkUmV0cnk6IGJ1aWxkZXIuZ3JvdXAoe1xuICogICAgICAgICBwYXNzd29yZDogW1wiXCIsIFZhbGlkYXRvcnMucmVxdWlyZWRdLFxuICogICAgICAgICBwYXNzd29yZENvbmZpcm1hdGlvbjogW1wiXCIsIFZhbGlkYXRvcnMucmVxdWlyZWQsIGFzeW5jVmFsaWRhdG9yXVxuICogICAgICAgfSlcbiAqICAgICB9KTtcbiAqICAgfVxuICpcbiAqICAgZ2V0IHZhbHVlKCk6IHN0cmluZyB7XG4gKiAgICAgcmV0dXJuIEpTT04uc3RyaW5naWZ5KHRoaXMubG9naW5Gb3JtLnZhbHVlLCBudWxsLCAyKTtcbiAqICAgfVxuICogfVxuICogYGBgXG4gKi9cbkBJbmplY3RhYmxlKClcbmV4cG9ydCBjbGFzcyBGb3JtQnVpbGRlciB7XG4gIC8qKlxuICAgKiBDb25zdHJ1Y3QgYSBuZXcge0BsaW5rIENvbnRyb2xHcm91cH0gd2l0aCB0aGUgZ2l2ZW4gbWFwIG9mIGNvbmZpZ3VyYXRpb24uXG4gICAqIFZhbGlkIGtleXMgZm9yIHRoZSBgZXh0cmFgIHBhcmFtZXRlciBtYXAgYXJlIGBvcHRpb25hbHNgIGFuZCBgdmFsaWRhdG9yYC5cbiAgICpcbiAgICogU2VlIHRoZSB7QGxpbmsgQ29udHJvbEdyb3VwfSBjb25zdHJ1Y3RvciBmb3IgbW9yZSBkZXRhaWxzLlxuICAgKi9cbiAgZ3JvdXAoY29udHJvbHNDb25maWc6IHtba2V5OiBzdHJpbmddOiBhbnl9LFxuICAgICAgICBleHRyYToge1trZXk6IHN0cmluZ106IGFueX0gPSBudWxsKTogbW9kZWxNb2R1bGUuQ29udHJvbEdyb3VwIHtcbiAgICB2YXIgY29udHJvbHMgPSB0aGlzLl9yZWR1Y2VDb250cm9scyhjb250cm9sc0NvbmZpZyk7XG4gICAgdmFyIG9wdGlvbmFscyA9IGlzUHJlc2VudChleHRyYSkgPyBTdHJpbmdNYXBXcmFwcGVyLmdldChleHRyYSwgXCJvcHRpb25hbHNcIikgOiBudWxsO1xuICAgIHZhciB2YWxpZGF0b3IgPSBpc1ByZXNlbnQoZXh0cmEpID8gU3RyaW5nTWFwV3JhcHBlci5nZXQoZXh0cmEsIFwidmFsaWRhdG9yXCIpIDogbnVsbDtcbiAgICB2YXIgYXN5bmNWYWxpZGF0b3IgPSBpc1ByZXNlbnQoZXh0cmEpID8gU3RyaW5nTWFwV3JhcHBlci5nZXQoZXh0cmEsIFwiYXN5bmNWYWxpZGF0b3JcIikgOiBudWxsO1xuICAgIHJldHVybiBuZXcgbW9kZWxNb2R1bGUuQ29udHJvbEdyb3VwKGNvbnRyb2xzLCBvcHRpb25hbHMsIHZhbGlkYXRvciwgYXN5bmNWYWxpZGF0b3IpO1xuICB9XG4gIC8qKlxuICAgKiBDb25zdHJ1Y3QgYSBuZXcge0BsaW5rIENvbnRyb2x9IHdpdGggdGhlIGdpdmVuIGB2YWx1ZWAsYHZhbGlkYXRvcmAsIGFuZCBgYXN5bmNWYWxpZGF0b3JgLlxuICAgKi9cbiAgY29udHJvbCh2YWx1ZTogT2JqZWN0LCB2YWxpZGF0b3I6IEZ1bmN0aW9uID0gbnVsbCxcbiAgICAgICAgICBhc3luY1ZhbGlkYXRvcjogRnVuY3Rpb24gPSBudWxsKTogbW9kZWxNb2R1bGUuQ29udHJvbCB7XG4gICAgcmV0dXJuIG5ldyBtb2RlbE1vZHVsZS5Db250cm9sKHZhbHVlLCB2YWxpZGF0b3IsIGFzeW5jVmFsaWRhdG9yKTtcbiAgfVxuXG4gIC8qKlxuICAgKiBDb25zdHJ1Y3QgYW4gYXJyYXkgb2Yge0BsaW5rIENvbnRyb2x9cyBmcm9tIHRoZSBnaXZlbiBgY29udHJvbHNDb25maWdgIGFycmF5IG9mXG4gICAqIGNvbmZpZ3VyYXRpb24sIHdpdGggdGhlIGdpdmVuIG9wdGlvbmFsIGB2YWxpZGF0b3JgIGFuZCBgYXN5bmNWYWxpZGF0b3JgLlxuICAgKi9cbiAgYXJyYXkoY29udHJvbHNDb25maWc6IGFueVtdLCB2YWxpZGF0b3I6IEZ1bmN0aW9uID0gbnVsbCxcbiAgICAgICAgYXN5bmNWYWxpZGF0b3I6IEZ1bmN0aW9uID0gbnVsbCk6IG1vZGVsTW9kdWxlLkNvbnRyb2xBcnJheSB7XG4gICAgdmFyIGNvbnRyb2xzID0gY29udHJvbHNDb25maWcubWFwKGMgPT4gdGhpcy5fY3JlYXRlQ29udHJvbChjKSk7XG4gICAgcmV0dXJuIG5ldyBtb2RlbE1vZHVsZS5Db250cm9sQXJyYXkoY29udHJvbHMsIHZhbGlkYXRvciwgYXN5bmNWYWxpZGF0b3IpO1xuICB9XG5cbiAgLyoqIEBpbnRlcm5hbCAqL1xuICBfcmVkdWNlQ29udHJvbHMoY29udHJvbHNDb25maWc6IGFueSk6IHtba2V5OiBzdHJpbmddOiBtb2RlbE1vZHVsZS5BYnN0cmFjdENvbnRyb2x9IHtcbiAgICB2YXIgY29udHJvbHM6IHtba2V5OiBzdHJpbmddOiBtb2RlbE1vZHVsZS5BYnN0cmFjdENvbnRyb2x9ID0ge307XG4gICAgU3RyaW5nTWFwV3JhcHBlci5mb3JFYWNoKGNvbnRyb2xzQ29uZmlnLCAoY29udHJvbENvbmZpZywgY29udHJvbE5hbWUpID0+IHtcbiAgICAgIGNvbnRyb2xzW2NvbnRyb2xOYW1lXSA9IHRoaXMuX2NyZWF0ZUNvbnRyb2woY29udHJvbENvbmZpZyk7XG4gICAgfSk7XG4gICAgcmV0dXJuIGNvbnRyb2xzO1xuICB9XG5cbiAgLyoqIEBpbnRlcm5hbCAqL1xuICBfY3JlYXRlQ29udHJvbChjb250cm9sQ29uZmlnOiBhbnkpOiBtb2RlbE1vZHVsZS5BYnN0cmFjdENvbnRyb2wge1xuICAgIGlmIChjb250cm9sQ29uZmlnIGluc3RhbmNlb2YgbW9kZWxNb2R1bGUuQ29udHJvbCB8fFxuICAgICAgICBjb250cm9sQ29uZmlnIGluc3RhbmNlb2YgbW9kZWxNb2R1bGUuQ29udHJvbEdyb3VwIHx8XG4gICAgICAgIGNvbnRyb2xDb25maWcgaW5zdGFuY2VvZiBtb2RlbE1vZHVsZS5Db250cm9sQXJyYXkpIHtcbiAgICAgIHJldHVybiBjb250cm9sQ29uZmlnO1xuXG4gICAgfSBlbHNlIGlmIChpc0FycmF5KGNvbnRyb2xDb25maWcpKSB7XG4gICAgICB2YXIgdmFsdWUgPSBjb250cm9sQ29uZmlnWzBdO1xuICAgICAgdmFyIHZhbGlkYXRvciA9IGNvbnRyb2xDb25maWcubGVuZ3RoID4gMSA/IGNvbnRyb2xDb25maWdbMV0gOiBudWxsO1xuICAgICAgdmFyIGFzeW5jVmFsaWRhdG9yID0gY29udHJvbENvbmZpZy5sZW5ndGggPiAyID8gY29udHJvbENvbmZpZ1syXSA6IG51bGw7XG4gICAgICByZXR1cm4gdGhpcy5jb250cm9sKHZhbHVlLCB2YWxpZGF0b3IsIGFzeW5jVmFsaWRhdG9yKTtcblxuICAgIH0gZWxzZSB7XG4gICAgICByZXR1cm4gdGhpcy5jb250cm9sKGNvbnRyb2xDb25maWcpO1xuICAgIH1cbiAgfVxufSJdfQ==
(function($) { "use strict"; function initialize() { var mapOptions = { zoom: 15, scrollwheel: false, center: new google.maps.LatLng(34.0313519, -118.2154304) }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var marker = new google.maps.Marker({ position: map.getCenter(), map: map }); var styles = [ { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#8d8d8d" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "saturation": -100 }, { "lightness": 45 } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road.arterial", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "water", "elementType": "all", "stylers": [ { "color": "#dbdbdb" }, { "visibility": "on" } ] } ] map.setOptions({styles: styles}); } google.maps.event.addDomListener(window, 'load', initialize); })(jQuery);
#!/usr/bin/env node const fs = require('fs-extra'), os = require('os'), parseArgs = require('minimist'), onExit = require('signal-exit'); const { error, info } = require('./log'); const { ACTIONS } = require('./constants'); const apps = require('./apps'), bootstrap = require('./bootstrap'), checks = require('./checks'), daemon = require('./daemon'), fatality = require('./fatality'), help = require('./help'), packageUtils = require('./package'); const MODES = { development: { name: 'development', deployments: './temp/deployments', start: [ 'bin/svc-start', './temp/deployments', '{{app}}' ], stop: [ 'bin/svc-stop', '{{app}}' ], manageAppLifecycle: true, }, // intentionally not documented externally, this is a place that int. tests // can work out of without over-writing existing work test: { name: 'test', deployments: './test-workspace/deployments', start: [ 'bin/svc-start', './test-workspace/deployments', '{{app}}' ], stop: [ 'bin/svc-stop', '{{app}}' ], manageAppLifecycle: true, }, local: { name: 'local', deployments: `${os.homedir()}/.horticulturalist/deployments`, start: [ 'horti-svc-start', `${os.homedir()}/.horticulturalist/deployments`, '{{app}}' ], stop: [ 'horti-svc-stop', '{{app}}' ], manageAppLifecycle: true, }, medic_os: { name: 'Medic OS', deployments: '/srv/software', start: ['sudo', '-n', '/boot/svc-start', '{{app}}' ], stop: ['sudo', '-n', '/boot/svc-stop', '{{app}}' ], // MedicOS will start and stop apps, though we will still restart them // when upgrading manageAppLifecycle: false, }, }; const active = (...things) => things.filter(t => !!t); const argv = parseArgs(process.argv, { default: { daemon: true } }); const mode = argv.dev ? MODES.development : argv.test ? MODES.test : argv.local ? MODES.local : argv['medic-os'] ? MODES.medic_os : undefined; if (argv.version || argv.v) { help.outputVersion(); return; } if (argv.help || argv.h) { help.outputHelp(); return; } if (active(argv.dev, argv.local, argv['medic-os'], argv.test).length !== 1) { help.outputHelp(); error('You must pick one mode to run in.'); process.exit(-1); } if (active(argv.install, argv.stage, argv['complete-install']).length > 1) { help.outputHelp(); error('Pick only one action to perform'); process.exit(-1); } if (argv.bootstrap) { info('--bootstrap is DEPRECATED, use --install instead'); argv.install = argv.bootstrap; } const action = argv.install ? ACTIONS.INSTALL : argv.stage ? ACTIONS.STAGE : argv['complete-install'] ? ACTIONS.COMPLETE : undefined; let version = argv.install || argv.stage; if (version === true) { version = '@medic:medic:release'; } if (version) { version = packageUtils.parse(version); } mode.daemon = argv.daemon; if (!action && !mode.daemon) { help.outputHelp(); error('--no-daemon does not do anything without also specifiying an action'); process.exit(-1); } process.on('uncaughtException', fatality); process.on('unhandledRejection', (err) => { error(err); fatality('Unhandled rejection, please raise this as a bug!'); }); onExit((code) => { if (mode.manageAppLifecycle && mode.daemon) { apps.stopSync(mode.stop); } process.exit(code || 0); }); info(`Starting Horticulturalist ${require('../package.json').version} ${mode.daemon ? 'daemon ' : ''}in ${mode.name} mode`); checks() .then(() => { fs.mkdirs(mode.deployments); if (action === ACTIONS.INSTALL) { return bootstrap.install(version); } else if (action === ACTIONS.STAGE) { return bootstrap.stage(version); } else if (action === ACTIONS.COMPLETE) { return bootstrap.complete(); } else { return bootstrap.existing(); } }).then(deployDoc => { return daemon.init(deployDoc, mode); }) .catch(fatality);
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('OrderItem', { id: { autoIncrement: true, type: DataTypes.INTEGER, allowNull: true, primaryKey: true, field: 'Id' }, orderId: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'Order', key: 'Id' }, unique: true, field: 'OrderId' }, productId: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'Product', key: 'Id' }, unique: true, field: 'ProductId' }, unitPrice: { type: DataTypes.DECIMAL(12,2), allowNull: false, defaultValue: 0, field: 'UnitPrice' }, quantity: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1, field: 'Quantity' } }, { sequelize, tableName: 'OrderItem', timestamps: false, indexes: [ { name: "sqlite_autoindex_OrderItem_1", unique: true, fields: [ { name: "OrderId" }, { name: "ProductId" }, ] }, ] }); };
import React from 'react'; import { useStaticQuery, graphql } from 'gatsby'; import Img from 'gatsby-image'; const pageQuery = graphql` query AboutPageQuery { aboutYaml { whatWeDo whoWeAre details featuredImage { childImageSharp { fluid(maxWidth: 400) { ...GatsbyImageSharpFluid } } } } } `; const About = () => { const data = useStaticQuery(pageQuery); const about = data.aboutYaml; // console.log('about', about); return ( <> <div className="about-wrapper"> <div className="container"> <div className="row row--35 align-items-center"> <div className="col-lg-5 col-md-12"> <div className="thumbnail"> <Img className="w-100" fluid={about.featuredImage.childImageSharp.fluid} /> </div> </div> <div className="col-lg-7 col-md-12"> <div className="about-inner inner"> <div className="section-title"> <h2 className="title">About</h2> <p className="description">{about.details}</p> </div> <div className="row mt--30 mt_sm--10"> <div className="col-lg-6 col-md-12 col-sm-12 col-12"> <div className="about-us-list"> <h3 className="title">Our Commitment</h3> <p>{about.whoWeAre}</p> </div> </div> <div className="col-lg-6 col-md-12 col-sm-12 col-12"> <div className="about-us-list"> <h3 className="title">Our Philosophy</h3> <p>{about.whatWeDo}</p> </div> </div> </div> </div> </div> </div> </div> </div> </> ); }; export default About;
import { createStore } from "redux"; const INITIAL_STATE = { email: "", }; function reducer(state = INITIAL_STATE, action) { if (action.type === "Set_Email") { return { ...state, email: action.value }; } return state; } const store = createStore(reducer); export default store;
import React from 'react' import Link from 'gatsby-link' const IndexPage = () => ( <div> <form name="contact" method="POST" data-netlify="true" data-netlify-honeypot="bot-field" data-netlify-recaptcha="true"> <p> <label>Your Name: <input type="text" name="name" /></label> </p> <p> <label>Your Email: <input type="email" name="email" /></label> </p> <p> <label>Message: <textarea name="message"></textarea></label> </p> <div data-netlify-recaptcha="true"></div> <p> <button type="submit" to="/thankYouPage/" >Send</button> </p> </form> </div> ) export default IndexPage
/** * Computes trigonometric functions using state-of-the-art algorithms */ var fastSin = function(th){ // taylor series if(th === 0) return 0; var pi = 3.141592653589793 var magnitude = Math.abs(th); var sign = th / magnitude; var magnitude = magnitude % (2*pi); var sin = 0; var factorial = function(n) { if(n === 0) return 1; else return n * factorial(n - 1); } var power = function(x, n) { if(n === 0) return 1; else return x * factorial(n - 1); } for(var i = 0; i < 100; i++) { sin += power(-1,i) * power(magnitude, 2*i+1) / factorial(2*i + 1); } return sin; } var fastCos = function(th) { var pi = 3.141592653589793 return fastSin(th - pi/2); } var fasterSin = function(th) { // small-angle approximation return th; } anything.prototype.fastSin = fastSin; anything.prototype.fastCos = fastCos; anything.prototype.fasterSin = fasterSin;
import { StyleSheet } from 'react-native'; import Constants from 'expo-constants'; const styles = StyleSheet.create({ container: { flex: 1, paddingHorizontal: 24, paddingTop: Constants.statusBarHeight + 20 }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }, headerText: { fontSize: 15, color: '#737380' }, headerTextBold: { fontWeight: 'bold' }, title: { fontSize: 30, marginBottom: 16, marginTop: 48, color: '#13131a', fontWeight: 'bold' }, description: { fontSize: 16, lineHeight: 24, color: '#737380' }, incidentList: { marginTop: 32 }, incident: { padding: 24, borderRadius: 10, backgroundColor: '#fff', marginBottom: 16 }, incidentProperty: { fontSize: 14, color: '#41414d', fontWeight: 'bold' }, incidentValue: { marginTop: 8, fontSize: 15, marginBottom: 24, color: '#737380' }, detailsButton: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: '#e02041', padding: 10, borderRadius: 5 }, detailsButtonText: { color: '#fff', fontSize: 15, fontWeight: 'bold' } }); export default styles;
// slick.js // General configuration and initiation of the 'slick' image carousel. $(document).ready(function() { $('.single-item').slick({ autoplay: false, autoplaySpeed: 5000, slidesToShow: 1, slidesToScroll: 1, dots: true, }); })
const { resolve } = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { optimization: { splitChunks: { chunks: 'all' } }, entry: { main: resolve(__dirname, './src/index.js'), login: resolve(__dirname, './src/login.js') }, output: { filename: 'js/[name].js', path: resolve(__dirname, './dist'), chunkFilename: 'js/[name].js' }, plugins: [ new CopyWebpackPlugin([ { from: resolve(__dirname, './public'), to: 'public' } ]), new HtmlWebpackPlugin({ chunks: [ 'main' ], title: 'Devconf 2020', favicon: './public/favicon.ico', template: resolve(__dirname, './src/index.html') }), new HtmlWebpackPlugin({ inject: false, title: 'Devconf 2020 - 404', favicon: './public/favicon.ico', template: resolve(__dirname, './src/404.html'), filename: '404.html' }), new HtmlWebpackPlugin({ chunks: [ 'login' ], title: 'Devconf 2020 - log me in', favicon: './public/favicon.ico', template: resolve(__dirname, './src/index.html'), filename: 'login.html' }), new MiniCssExtractPlugin() ], module: { rules: [{ test: /src\/.*\.js$/, exclude: /(node_modules|bower_components)/i, use: [{ loader: 'source-map-loader' }, { loader: 'babel-loader' }, { loader: 'eslint-loader' }] }, { test: /\.s?[ac]ss$/, use: [ process.env.NODE_ENV === 'production' ? 'style-loader' : MiniCssExtractPlugin.loader, { loader: 'css-loader' }, { loader: 'sass-loader' } ] }, { test: /\.(woff(2)?|ttf|jpg|png|eot|gif|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [{ loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'fonts/' } }] }, { test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto' }] }, devServer: { contentBase: resolve(__dirname, './dist'), hot: true, port: 8002, https: false, inline: true, disableHostCheck: true, historyApiFallback: true }, }
(function(d){d['gu']=Object.assign(d['gu']||{},{a:"ફાઇલ અપલોડ ન થઇ શકી",b:"Image toolbar",c:"Table toolbar",d:"ઘાટુ - બોલ્ડ્",e:"ત્રાંસુ - ઇટલિક્",f:" વિચાર ટાંકો",g:"Insert image or file",h:"Choose heading",i:"Heading",j:"image widget",k:"Full size image",l:"Side image",m:"Left aligned image",n:"Centered image",o:"Right aligned image",p:"Insert image",q:"Increase indent",r:"Decrease indent",s:"Numbered List",t:"Bulleted List",u:"Insert table",v:"Header column",w:"Insert column left",x:"Insert column right",y:"Delete column",z:"Column",aa:"Header row",ab:"Insert row below",ac:"Insert row above",ad:"Delete row",ae:"Row",af:"Merge cell up",ag:"Merge cell right",ah:"Merge cell down",ai:"Merge cell left",aj:"Split cell vertically",ak:"Split cell horizontally",al:"Merge cells",am:"Enter image caption",an:"Upload failed",ao:"Insert media",ap:"The URL must not be empty.",aq:"This media URL is not supported.",ar:"media widget",as:"Link",at:"Widget toolbar",au:"Upload in progress",av:"Open in a new tab",aw:"Downloadable",ax:"Unlink",ay:"Edit link",az:"Open link in new tab",ba:"This link has no URL",bb:"Save",bc:"Cancel",bd:"Paste the media URL in the input.",be:"Tip: Paste the URL into the content to embed faster.",bf:"Media URL",bg:"Link URL",bh:"Dropdown toolbar",bi:"%0 of %1",bj:"Previous",bk:"Next",bl:"Undo",bm:"Redo",bn:"Editor toolbar",bo:"Show more items",bp:"Change image text alternative",bq:"Paragraph",br:"Heading 1",bs:"Heading 2",bt:"Heading 3",bu:"Heading 4",bv:"Heading 5",bw:"Heading 6",bx:"Rich Text Editor, %0",by:"Could not obtain resized image URL.",bz:"Selecting resized image failed",ca:"Could not insert image at the current position.",cb:"Inserting image failed",cc:"Text alternative"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
import React from 'react'; var AnnounceSlide = function AnnounceSlide(_ref) { var message = _ref.message; var styles = { position: 'absolute', left: '-10000px', top: 'auto', width: '1px', height: '1px', overflow: 'hidden' }; return React.createElement("div", { "aria-live": "polite", "aria-atomic": "true", style: styles, tabIndex: -1 }, message); }; export var defaultRenderAnnounceSlideMessage = function defaultRenderAnnounceSlideMessage(_ref2) { var currentSlide = _ref2.currentSlide, slideCount = _ref2.slideCount; return "Slide ".concat(currentSlide + 1, " of ").concat(slideCount); }; export default AnnounceSlide;
const Command = require("../../base/Command.js"); const Discord = require("discord.js") const axios = require('axios') class Avatar extends Command { constructor(client) { super(client, { name: "avatar", usage: ".avatar [@user]", category: "Global", description: "Belirttiğiniz kullanıcının avatarını görüntülersiniz.", aliases: ["av", "pp"] }); } // async run(message, args, data) { //if(!message.member.permissions.has("VIEW_AUDIT_LOG")) return let user = message.mentions.users.first() || this.client.users.cache.get(args[0]) || (args[0] && args[0].length ? this.client.users.cache.find(x => x.username.match(new RegExp(args.join(" "), "mgi"))) : null) || null; if (!user) try { user = await this.client.users.fetch(args[0]); } catch (err) { user = message.author; } const row = new Discord.MessageActionRow() .addComponents( new Discord.MessageSelectMenu() .setCustomId('banner') .setPlaceholder('Kullanıcının bannerini görüntülemek için tıkla!') .addOptions([ { label: 'Banner', description: 'Kullanıcının bannerini görüntüleyin.', value: 'banner', } ]), ); /*let embed = new Discord.MessageEmbed() .setDescription(`**${user.tag}** adlı kullanıcının profil fotoğrafı!`) .setImage(user.displayAvatarURL({dynamic: true, size: 2048})) .setFooter({ text: `${message.author.tag} tarafından istendi!` }) */ const avatar = `${user.displayAvatarURL({ dynamic: true, size: 4096 })}` let msg = await message.channel.send({ content: avatar, components: [row] }) var filter = (menu) => menu.user.id === message.author.id; const collector = msg.createMessageComponentCollector({ filter, max: 1, time: 30000 }) collector.on("collect", async (menu) => { if(menu.values[0] === "banner") { async function bannerURL(user, client) { const response = await axios.get(`https://discord.com/api/v9/users/${user}`, { headers: { 'Authorization': `Bot ${client.token}` } }); if(!response.data.banner) return "Kullanıcının banneri bulunmamakta!" if(response.data.banner.startsWith('a_')) return `https://cdn.discordapp.com/banners/${response.data.id}/${response.data.banner}.gif?size=512` else return(`https://cdn.discordapp.com/banners/${response.data.id}/${response.data.banner}.png?size=512`) } let bannerurl = await bannerURL(user.id,this.client) menu.reply({content: `> ${Discord.Formatters.hyperlink(`${user.tag}`, `${bannerurl}`, "Resimi büyütmek için tıkla")}`, ephemeral: true}) } }) } } module.exports = Avatar;
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.undefined = mod.exports; } })(this, function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { "name": "--pf-c-form-control--BorderWidth", "value": "1px", "var": "var(--pf-c-form-control--BorderWidth)" }; });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'far'; var iconName = 'toolbox'; var width = 512; var height = 512; var ligatures = []; var unicode = 'f552'; var svgPathData = 'M512 237.25c0-8.49-3.37-16.62-9.37-22.63l-45.26-45.26c-6-6-14.14-9.37-22.63-9.37H384V80c0-26.51-21.49-48-48-48H176c-26.51 0-48 21.49-48 48v80H77.26c-8.49 0-16.63 3.37-22.63 9.37L9.37 214.63c-6 6-9.37 14.14-9.37 22.63L.01 304 0 448c0 17.67 14.33 32 32 32h448c17.67 0 32-14.33 32-32V237.25zM176 80h160v80H176V80zM48 243.88L83.88 208h344.23L464 243.88l.01 60.12H376v-16c0-8.84-7.16-16-16-16h-16c-8.84 0-16 7.16-16 16v16H184v-16c0-8.84-7.16-16-16-16h-16c-8.84 0-16 7.16-16 16v16H48.01L48 243.88zM464 432H48v-80h88v16c0 8.84 7.16 16 16 16h16c8.84 0 16-7.16 16-16v-16h144v16c0 8.84 7.16 16 16 16h16c8.84 0 16-7.16 16-16v-16h88v80z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faToolbox = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <App />, document.getElementById("root") );
/* eslint-env mocha */ /* eslint-disable import/no-named-as-default-member */ import { Readable, Writable } from 'stream'; import chai from 'chai'; import mock, { ReadableMock as RM, WritableMock as WM } from '../main'; import ReadableMock from '../main/readable-mock'; import WritableMock from '../main/writable-mock'; chai.should(); describe('Main module', () => { it('should export ReadableMock', () => { // Given const rm = new RM([]); // Then rm.should.be.an.instanceOf(ReadableMock); rm.should.be.an.instanceOf(Readable); }); it('should export WritableMock', () => { // Given const wm = new WM(); // Then wm.should.be.an.instanceOf(WritableMock); wm.should.be.an.instanceOf(Writable); }); it('should export {ReadableMock, WritableMock} as default', () => { (new mock.ReadableMock([])).should.be.an.instanceOf(ReadableMock); (new mock.WritableMock()).should.be.an.instanceOf(WritableMock); }); });
//= require jquery.rating //= require spree/frontend //= require spree/frontend/spree_auth // Navigating to a page with ratings via TurboLinks shows the radio buttons $(document).on('page:load', function () { $('input[type=radio].star').rating(); });
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import _ from 'lodash'; import { Control, noValuesDisableMsg, noIndexPatternMsg, } from './control'; import { RangeFilterManager } from './filter_manager/range_filter_manager'; import { createSearchSource } from './create_search_source'; const minMaxAgg = (field) => { const aggBody = {}; if (field.scripted) { aggBody.script = { inline: field.script, lang: field.lang }; } else { aggBody.field = field.name; } return { maxAgg: { max: aggBody }, minAgg: { min: aggBody } }; }; class RangeControl extends Control { async fetch() { const indexPattern = this.filterManager.getIndexPattern(); if (!indexPattern) { this.disable(noIndexPatternMsg(this.controlParams.indexPattern)); return; } const fieldName = this.filterManager.fieldName; const aggs = minMaxAgg(indexPattern.fields.byName[fieldName]); const searchSource = createSearchSource(this.kbnApi, null, indexPattern, aggs, this.useTimeFilter); const resp = await searchSource.fetch(); let minMaxReturnedFromAggregation = true; let min = _.get(resp, 'aggregations.minAgg.value'); let max = _.get(resp, 'aggregations.maxAgg.value'); if (min === null || max === null) { min = 0; max = 1; minMaxReturnedFromAggregation = false; } if (!minMaxReturnedFromAggregation) { this.disable(noValuesDisableMsg(fieldName, indexPattern.title)); } else { this.unsetValue = { min: min, max: min }; this.min = min; this.max = max; this.enable = true; } return 'done'; } } export async function rangeControlFactory(controlParams, kbnApi, useTimeFilter) { let indexPattern; try { indexPattern = await kbnApi.indexPatterns.get(controlParams.indexPattern); } catch (err) { // ignore not found error and return control so it can be displayed in disabled state. } const unsetValue = { min: 0, max: 1 }; return new RangeControl( controlParams, new RangeFilterManager(controlParams.id, controlParams.fieldName, indexPattern, kbnApi.queryFilter, unsetValue), kbnApi, useTimeFilter ); }
const DomainResource = require('./DomainResource'); const Identifier = require('./Identifier'); const CodeableConcept = require('./CodeableConcept'); const Reference = require('./Reference'); const DocumentManifest_Content = require('./DocumentManifest_Content'); const DocumentManifest_Related = require('./DocumentManifest_Related'); class DocumentManifest extends DomainResource { constructor ( opts ) { super(); Object.assign(this, opts); } static get __resourceType () { return 'DocumentManifest'; } // This is a DocumentManifest resource get resourceType () { return this._resourceType; } set resourceType ( new_value ) { // Throw if new value is not in the allowed values let allowed_values = ['DocumentManifest']; if ( allowed_values.indexOf(new_value) === -1 ) { throw new Error(`Expected one of ${allowed_values}, got ${new_value} for field resourceType`); } this._resourceType = new_value; } // A single identifier that uniquely identifies this manifest. Principally used to refer to the manifest in non-FHIR contexts. get masterIdentifier () { return this._masterIdentifier; } set masterIdentifier ( new_value ) { this._masterIdentifier = new Identifier(new_value); } // Other identifiers associated with the document manifest, including version independent identifiers. get identifier () { return this._identifier; } set identifier ( new_value ) { this._identifier = Array.isArray(new_value) ? new_value.map(val => new Identifier(val)) : [new Identifier(new_value)]; } // The status of this document manifest. get status () { return this._status; } set status ( new_value ) { // Throw if new value is not in the allowed values let allowed_values = ['current', 'superseded', 'entered-in-error']; if ( allowed_values.indexOf(new_value) === -1 ) { throw new Error(`Expected one of ${allowed_values}, got ${new_value} for field status`); } this._status = new_value; } // Specifies the kind of this set of documents (e.g. Patient Summary, Discharge Summary, Prescription, etc.). The type of a set of documents may be the same as one of the documents in it - especially if there is only one - but it may be wider. get type () { return this._type; } set type ( new_value ) { this._type = new CodeableConcept(new_value); } // Who or what the set of documents is about. The documents can be about a person, (patient or healthcare practitioner), a device (i.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure). If the documents cross more than one subject, then more than one subject is allowed here (unusual use case). get subject () { return this._subject; } set subject ( new_value ) { this._subject = new Reference(new_value); } // When the document manifest was created for submission to the server (not necessarily the same thing as the actual resource last modified time, since it may be modified, replicated, etc.). get created () { return this._created; } set created ( new_value ) { // Throw if new value does not match the pattern let pattern = /-?[0-9]{4}(-(0[1-9]|1[0-2])(-(0[0-9]|[1-2][0-9]|3[0-1])(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00)))?)?)?/; if ( !pattern.test(new_value) ) { throw new Error(`Invalid format for ${new_value} on field created`); } this._created = new_value; } // Identifies who is responsible for creating the manifest, and adding documents to it. get author () { return this._author; } set author ( new_value ) { this._author = Array.isArray(new_value) ? new_value.map(val => new Reference(val)) : [new Reference(new_value)]; } // A patient, practitioner, or organization for which this set of documents is intended. get recipient () { return this._recipient; } set recipient ( new_value ) { this._recipient = Array.isArray(new_value) ? new_value.map(val => new Reference(val)) : [new Reference(new_value)]; } // Identifies the source system, application, or software that produced the document manifest. get source () { return this._source; } set source ( new_value ) { this._source = new_value; } // Human-readable description of the source document. This is sometimes known as the "title". get description () { return this._description; } set description ( new_value ) { this._description = new_value; } // The list of Documents included in the manifest. get content () { return this._content; } set content ( new_value ) { this._content = Array.isArray(new_value) ? new_value.map(val => new DocumentManifest_Content(val)) : [new DocumentManifest_Content(new_value)]; } // Related identifiers or resources associated with the DocumentManifest. get related () { return this._related; } set related ( new_value ) { this._related = Array.isArray(new_value) ? new_value.map(val => new DocumentManifest_Related(val)) : [new DocumentManifest_Related(new_value)]; } toJSON () { return Object.assign(super.toJSON(), { resourceType: this._resourceType, masterIdentifier: this._masterIdentifier, identifier: this._identifier, status: this._status, type: this._type, subject: this._subject, created: this._created, author: this._author, recipient: this._recipient, source: this._source, description: this._description, content: this._content, related: this._related }); } } module.exports = DocumentManifest;
!function(a,b,c,d,e){"use strict";var f=0,g=function(){var b,c=d.userAgent,e=/msie\s\d+/i;return c.search(e)>0&&(b=e.exec(c).toString(),b=b.split(" ")[1],b<9)&&(a("html").addClass("lt-ie9"),!0)}();Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=[].slice;if("function"!=typeof b)throw new TypeError;var d=c.call(arguments,1),e=function(){if(this instanceof e){var f=function(){};f.prototype=b.prototype;var g=new f,h=b.apply(g,d.concat(c.call(arguments)));return Object(h)===h?h:g}return b.apply(a,d.concat(c.call(arguments)))};return e}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null==this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);c<e;){if(c in d&&d[c]===a)return c;c++}return-1});var h='<span class="irs"><span class="irs-line" tabindex="-1"><span class="irs-line-left"></span><span class="irs-line-mid"></span><span class="irs-line-right"></span></span><span class="irs-min">0</span><span class="irs-max">1</span><span class="irs-from">0</span><span class="irs-to">0</span><span class="irs-single">0</span></span><span class="irs-grid"></span><span class="irs-bar"></span>',i='<span class="irs-bar-edge"></span><span class="irs-shadow shadow-single"></span><span class="irs-slider single"></span>',j='<span class="irs-shadow shadow-from"></span><span class="irs-shadow shadow-to"></span><span class="irs-slider from"></span><span class="irs-slider to"></span>',k='<span class="irs-disable-mask"></span>',l=function(d,e,f){this.VERSION="2.1.2",this.input=d,this.plugin_count=f,this.current_plugin=0,this.calc_count=0,this.update_tm=0,this.old_from=0,this.old_to=0,this.old_min_interval=null,this.raf_id=null,this.dragging=!1,this.force_redraw=!1,this.no_diapason=!1,this.is_key=!1,this.is_update=!1,this.is_start=!0,this.is_finish=!1,this.is_active=!1,this.is_resize=!1,this.is_click=!1,this.$cache={win:a(c),body:a(b.body),input:a(d),cont:null,rs:null,min:null,max:null,from:null,to:null,single:null,bar:null,line:null,s_single:null,s_from:null,s_to:null,shad_single:null,shad_from:null,shad_to:null,edge:null,grid:null,grid_labels:[]},this.coords={x_gap:0,x_pointer:0,w_rs:0,w_rs_old:0,w_handle:0,p_gap:0,p_gap_left:0,p_gap_right:0,p_step:0,p_pointer:0,p_handle:0,p_single_fake:0,p_single_real:0,p_from_fake:0,p_from_real:0,p_to_fake:0,p_to_real:0,p_bar_x:0,p_bar_w:0,grid_gap:0,big_num:0,big:[],big_w:[],big_p:[],big_x:[]},this.labels={w_min:0,w_max:0,w_from:0,w_to:0,w_single:0,p_min:0,p_max:0,p_from_fake:0,p_from_left:0,p_to_fake:0,p_to_left:0,p_single_fake:0,p_single_left:0};var g,h,i,j=this.$cache.input,k=j.prop("value");g={type:"single",min:10,max:100,from:null,to:null,step:1,min_interval:0,max_interval:0,drag_interval:!1,values:[],p_values:[],from_fixed:!1,from_min:null,from_max:null,from_shadow:!1,to_fixed:!1,to_min:null,to_max:null,to_shadow:!1,prettify_enabled:!0,prettify_separator:" ",prettify:null,force_edges:!1,keyboard:!1,keyboard_step:5,grid:!1,grid_margin:!0,grid_num:4,grid_snap:!1,hide_min_max:!1,hide_from_to:!1,prefix:"",postfix:"",max_postfix:"",decorate_both:!0,values_separator:" — ",input_values_separator:";",disable:!1,onStart:null,onChange:null,onFinish:null,onUpdate:null},h={type:j.data("type"),min:j.data("min"),max:j.data("max"),from:j.data("from"),to:j.data("to"),step:j.data("step"),min_interval:j.data("minInterval"),max_interval:j.data("maxInterval"),drag_interval:j.data("dragInterval"),values:j.data("values"),from_fixed:j.data("fromFixed"),from_min:j.data("fromMin"),from_max:j.data("fromMax"),from_shadow:j.data("fromShadow"),to_fixed:j.data("toFixed"),to_min:j.data("toMin"),to_max:j.data("toMax"),to_shadow:j.data("toShadow"),prettify_enabled:j.data("prettifyEnabled"),prettify_separator:j.data("prettifySeparator"),force_edges:j.data("forceEdges"),keyboard:j.data("keyboard"),keyboard_step:j.data("keyboardStep"),grid:j.data("grid"),grid_margin:j.data("gridMargin"),grid_num:j.data("gridNum"),grid_snap:j.data("gridSnap"),hide_min_max:j.data("hideMinMax"),hide_from_to:j.data("hideFromTo"),prefix:j.data("prefix"),postfix:j.data("postfix"),max_postfix:j.data("maxPostfix"),decorate_both:j.data("decorateBoth"),values_separator:j.data("valuesSeparator"),input_values_separator:j.data("inputValuesSeparator"),disable:j.data("disable")},h.values=h.values&&h.values.split(",");for(i in h)h.hasOwnProperty(i)&&(h[i]||0===h[i]||delete h[i]);k&&(k=k.split(h.input_values_separator||e.input_values_separator||";"),k[0]&&k[0]==+k[0]&&(k[0]=+k[0]),k[1]&&k[1]==+k[1]&&(k[1]=+k[1]),e&&e.values&&e.values.length?(g.from=k[0]&&e.values.indexOf(k[0]),g.to=k[1]&&e.values.indexOf(k[1])):(g.from=k[0]&&+k[0],g.to=k[1]&&+k[1])),a.extend(g,e),a.extend(g,h),this.options=g,this.validate(),this.result={input:this.$cache.input,slider:null,min:this.options.min,max:this.options.max,from:this.options.from,from_percent:0,from_value:null,to:this.options.to,to_percent:0,to_value:null},this.init()};l.prototype={init:function(a){this.no_diapason=!1,this.coords.p_step=this.convertToPercent(this.options.step,!0),this.target="base",this.toggleInput(),this.append(),this.setMinMax(),a?(this.force_redraw=!0,this.calc(!0),this.callOnUpdate()):(this.force_redraw=!0,this.calc(!0),this.callOnStart()),this.updateScene()},append:function(){var a='<span class="irs js-irs-'+this.plugin_count+'"></span>';this.$cache.input.before(a),this.$cache.input.prop("readonly",!0),this.$cache.cont=this.$cache.input.prev(),this.result.slider=this.$cache.cont,this.$cache.cont.html(h),this.$cache.rs=this.$cache.cont.find(".irs"),this.$cache.min=this.$cache.cont.find(".irs-min"),this.$cache.max=this.$cache.cont.find(".irs-max"),this.$cache.from=this.$cache.cont.find(".irs-from"),this.$cache.to=this.$cache.cont.find(".irs-to"),this.$cache.single=this.$cache.cont.find(".irs-single"),this.$cache.bar=this.$cache.cont.find(".irs-bar"),this.$cache.line=this.$cache.cont.find(".irs-line"),this.$cache.grid=this.$cache.cont.find(".irs-grid"),"single"===this.options.type?(this.$cache.cont.append(i),this.$cache.edge=this.$cache.cont.find(".irs-bar-edge"),this.$cache.s_single=this.$cache.cont.find(".single"),this.$cache.from[0].style.visibility="hidden",this.$cache.to[0].style.visibility="hidden",this.$cache.shad_single=this.$cache.cont.find(".shadow-single")):(this.$cache.cont.append(j),this.$cache.s_from=this.$cache.cont.find(".from"),this.$cache.s_to=this.$cache.cont.find(".to"),this.$cache.shad_from=this.$cache.cont.find(".shadow-from"),this.$cache.shad_to=this.$cache.cont.find(".shadow-to"),this.setTopHandler()),this.options.hide_from_to&&(this.$cache.from[0].style.display="none",this.$cache.to[0].style.display="none",this.$cache.single[0].style.display="none"),this.appendGrid(),this.options.disable?(this.appendDisableMask(),this.$cache.input[0].disabled=!0):(this.$cache.cont.removeClass("irs-disabled"),this.$cache.input[0].disabled=!1,this.bindEvents()),this.options.drag_interval&&(this.$cache.bar[0].style.cursor="ew-resize")},setTopHandler:function(){var a=this.options.min,b=this.options.max,c=this.options.from,d=this.options.to;c>a&&d===b?this.$cache.s_from.addClass("type_last"):d<b&&this.$cache.s_to.addClass("type_last")},changeLevel:function(a){switch(a){case"single":this.coords.p_gap=this.toFixed(this.coords.p_pointer-this.coords.p_single_fake);break;case"from":this.coords.p_gap=this.toFixed(this.coords.p_pointer-this.coords.p_from_fake),this.$cache.s_from.addClass("state_hover"),this.$cache.s_from.addClass("type_last"),this.$cache.s_to.removeClass("type_last");break;case"to":this.coords.p_gap=this.toFixed(this.coords.p_pointer-this.coords.p_to_fake),this.$cache.s_to.addClass("state_hover"),this.$cache.s_to.addClass("type_last"),this.$cache.s_from.removeClass("type_last");break;case"both":this.coords.p_gap_left=this.toFixed(this.coords.p_pointer-this.coords.p_from_fake),this.coords.p_gap_right=this.toFixed(this.coords.p_to_fake-this.coords.p_pointer),this.$cache.s_to.removeClass("type_last"),this.$cache.s_from.removeClass("type_last")}},appendDisableMask:function(){this.$cache.cont.append(k),this.$cache.cont.addClass("irs-disabled")},remove:function(){this.$cache.cont.remove(),this.$cache.cont=null,this.$cache.line.off("keydown.irs_"+this.plugin_count),this.$cache.body.off("touchmove.irs_"+this.plugin_count),this.$cache.body.off("mousemove.irs_"+this.plugin_count),this.$cache.win.off("touchend.irs_"+this.plugin_count),this.$cache.win.off("mouseup.irs_"+this.plugin_count),g&&(this.$cache.body.off("mouseup.irs_"+this.plugin_count),this.$cache.body.off("mouseleave.irs_"+this.plugin_count)),this.$cache.grid_labels=[],this.coords.big=[],this.coords.big_w=[],this.coords.big_p=[],this.coords.big_x=[],cancelAnimationFrame(this.raf_id)},bindEvents:function(){this.no_diapason||(this.$cache.body.on("touchmove.irs_"+this.plugin_count,this.pointerMove.bind(this)),this.$cache.body.on("mousemove.irs_"+this.plugin_count,this.pointerMove.bind(this)),this.$cache.win.on("touchend.irs_"+this.plugin_count,this.pointerUp.bind(this)),this.$cache.win.on("mouseup.irs_"+this.plugin_count,this.pointerUp.bind(this)),this.$cache.line.on("touchstart.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.line.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.options.drag_interval&&"double"===this.options.type?(this.$cache.bar.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"both")),this.$cache.bar.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"both"))):(this.$cache.bar.on("touchstart.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.bar.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click"))),"single"===this.options.type?(this.$cache.single.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"single")),this.$cache.s_single.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"single")),this.$cache.shad_single.on("touchstart.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.single.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"single")),this.$cache.s_single.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"single")),this.$cache.edge.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.shad_single.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click"))):(this.$cache.single.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,null)),this.$cache.single.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,null)),this.$cache.from.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"from")),this.$cache.s_from.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"from")),this.$cache.to.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"to")),this.$cache.s_to.on("touchstart.irs_"+this.plugin_count,this.pointerDown.bind(this,"to")),this.$cache.shad_from.on("touchstart.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.shad_to.on("touchstart.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.from.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"from")),this.$cache.s_from.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"from")),this.$cache.to.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"to")),this.$cache.s_to.on("mousedown.irs_"+this.plugin_count,this.pointerDown.bind(this,"to")),this.$cache.shad_from.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click")),this.$cache.shad_to.on("mousedown.irs_"+this.plugin_count,this.pointerClick.bind(this,"click"))),this.options.keyboard&&this.$cache.line.on("keydown.irs_"+this.plugin_count,this.key.bind(this,"keyboard")),g&&(this.$cache.body.on("mouseup.irs_"+this.plugin_count,this.pointerUp.bind(this)),this.$cache.body.on("mouseleave.irs_"+this.plugin_count,this.pointerUp.bind(this))))},pointerMove:function(a){if(this.dragging){var b=a.pageX||a.originalEvent.touches&&a.originalEvent.touches[0].pageX;this.coords.x_pointer=b-this.coords.x_gap,this.calc()}},pointerUp:function(b){this.current_plugin===this.plugin_count&&this.is_active&&(this.is_active=!1,this.$cache.cont.find(".state_hover").removeClass("state_hover"),this.force_redraw=!0,g&&a("*").prop("unselectable",!1),this.updateScene(),this.restoreOriginalMinInterval(),(a.contains(this.$cache.cont[0],b.target)||this.dragging)&&(this.is_finish=!0,this.callOnFinish()),this.dragging=!1)},pointerDown:function(b,c){c.preventDefault(),c.stopPropagation();var d=c.pageX||c.originalEvent.touches&&c.originalEvent.touches[0].pageX;2!==c.button&&("both"===b&&this.setTempMinInterval(),b||(b=this.target),this.current_plugin=this.plugin_count,this.target=b,this.is_active=!0,this.dragging=!0,this.coords.x_gap=this.$cache.rs.offset().left,this.coords.x_pointer=d-this.coords.x_gap,this.calcPointerPercent(),this.changeLevel(b),g&&a("*").prop("unselectable",!0),this.$cache.line.trigger("focus"),this.updateScene())},pointerClick:function(a,b){b.preventDefault(),b.stopPropagation();var c=b.pageX||b.originalEvent.touches&&b.originalEvent.touches[0].pageX;2!==b.button&&(this.current_plugin=this.plugin_count,this.target=a,this.is_click=!0,this.coords.x_gap=this.$cache.rs.offset().left,this.coords.x_pointer=+(c-this.coords.x_gap).toFixed(),this.force_redraw=!0,this.calc(),this.$cache.line.trigger("focus"))},key:function(a,b){if(!(this.current_plugin!==this.plugin_count||b.altKey||b.ctrlKey||b.shiftKey||b.metaKey)){switch(b.which){case 83:case 65:case 40:case 37:b.preventDefault(),this.moveByKey(!1);break;case 87:case 68:case 38:case 39:b.preventDefault(),this.moveByKey(!0)}return!0}},moveByKey:function(a){var b=this.coords.p_pointer;a?b+=this.options.keyboard_step:b-=this.options.keyboard_step,this.coords.x_pointer=this.toFixed(this.coords.w_rs/100*b),this.is_key=!0,this.calc()},setMinMax:function(){if(this.options){if(this.options.hide_min_max)return this.$cache.min[0].style.display="none",void(this.$cache.max[0].style.display="none");this.options.values.length?(this.$cache.min.html(this.decorate(this.options.p_values[this.options.min])),this.$cache.max.html(this.decorate(this.options.p_values[this.options.max]))):(this.$cache.min.html(this.decorate(this._prettify(this.options.min),this.options.min)),this.$cache.max.html(this.decorate(this._prettify(this.options.max),this.options.max))),this.labels.w_min=this.$cache.min.outerWidth(!1),this.labels.w_max=this.$cache.max.outerWidth(!1)}},setTempMinInterval:function(){var a=this.result.to-this.result.from;null===this.old_min_interval&&(this.old_min_interval=this.options.min_interval),this.options.min_interval=a},restoreOriginalMinInterval:function(){null!==this.old_min_interval&&(this.options.min_interval=this.old_min_interval,this.old_min_interval=null)},calc:function(a){if(this.options&&(this.calc_count++,(10===this.calc_count||a)&&(this.calc_count=0,this.coords.w_rs=this.$cache.rs.outerWidth(!1),this.calcHandlePercent()),this.coords.w_rs)){this.calcPointerPercent();var b=this.getHandleX();switch("click"===this.target&&(this.coords.p_gap=this.coords.p_handle/2,b=this.getHandleX(),this.options.drag_interval?this.target="both_one":this.target=this.chooseHandle(b)),this.target){case"base":var c=(this.options.max-this.options.min)/100,d=(this.result.from-this.options.min)/c,e=(this.result.to-this.options.min)/c;this.coords.p_single_real=this.toFixed(d),this.coords.p_from_real=this.toFixed(d),this.coords.p_to_real=this.toFixed(e),this.coords.p_single_real=this.checkDiapason(this.coords.p_single_real,this.options.from_min,this.options.from_max),this.coords.p_from_real=this.checkDiapason(this.coords.p_from_real,this.options.from_min,this.options.from_max),this.coords.p_to_real=this.checkDiapason(this.coords.p_to_real,this.options.to_min,this.options.to_max),this.coords.p_single_fake=this.convertToFakePercent(this.coords.p_single_real),this.coords.p_from_fake=this.convertToFakePercent(this.coords.p_from_real),this.coords.p_to_fake=this.convertToFakePercent(this.coords.p_to_real),this.target=null;break;case"single":if(this.options.from_fixed)break;this.coords.p_single_real=this.convertToRealPercent(b),this.coords.p_single_real=this.calcWithStep(this.coords.p_single_real),this.coords.p_single_real=this.checkDiapason(this.coords.p_single_real,this.options.from_min,this.options.from_max),this.coords.p_single_fake=this.convertToFakePercent(this.coords.p_single_real);break;case"from":if(this.options.from_fixed)break;this.coords.p_from_real=this.convertToRealPercent(b),this.coords.p_from_real=this.calcWithStep(this.coords.p_from_real),this.coords.p_from_real>this.coords.p_to_real&&(this.coords.p_from_real=this.coords.p_to_real),this.coords.p_from_real=this.checkDiapason(this.coords.p_from_real,this.options.from_min,this.options.from_max),this.coords.p_from_real=this.checkMinInterval(this.coords.p_from_real,this.coords.p_to_real,"from"),this.coords.p_from_real=this.checkMaxInterval(this.coords.p_from_real,this.coords.p_to_real,"from"),this.coords.p_from_fake=this.convertToFakePercent(this.coords.p_from_real);break;case"to":if(this.options.to_fixed)break;this.coords.p_to_real=this.convertToRealPercent(b),this.coords.p_to_real=this.calcWithStep(this.coords.p_to_real),this.coords.p_to_real<this.coords.p_from_real&&(this.coords.p_to_real=this.coords.p_from_real),this.coords.p_to_real=this.checkDiapason(this.coords.p_to_real,this.options.to_min,this.options.to_max),this.coords.p_to_real=this.checkMinInterval(this.coords.p_to_real,this.coords.p_from_real,"to"),this.coords.p_to_real=this.checkMaxInterval(this.coords.p_to_real,this.coords.p_from_real,"to"),this.coords.p_to_fake=this.convertToFakePercent(this.coords.p_to_real);break;case"both":if(this.options.from_fixed||this.options.to_fixed)break;b=this.toFixed(b+.1*this.coords.p_handle),this.coords.p_from_real=this.convertToRealPercent(b)-this.coords.p_gap_left,this.coords.p_from_real=this.calcWithStep(this.coords.p_from_real),this.coords.p_from_real=this.checkDiapason(this.coords.p_from_real,this.options.from_min,this.options.from_max),this.coords.p_from_real=this.checkMinInterval(this.coords.p_from_real,this.coords.p_to_real,"from"),this.coords.p_from_fake=this.convertToFakePercent(this.coords.p_from_real),this.coords.p_to_real=this.convertToRealPercent(b)+this.coords.p_gap_right,this.coords.p_to_real=this.calcWithStep(this.coords.p_to_real),this.coords.p_to_real=this.checkDiapason(this.coords.p_to_real,this.options.to_min,this.options.to_max),this.coords.p_to_real=this.checkMinInterval(this.coords.p_to_real,this.coords.p_from_real,"to"),this.coords.p_to_fake=this.convertToFakePercent(this.coords.p_to_real);break;case"both_one":if(this.options.from_fixed||this.options.to_fixed)break;var f=this.convertToRealPercent(b),g=this.result.from_percent,h=this.result.to_percent,i=h-g,j=i/2,k=f-j,l=f+j;k<0&&(k=0,l=k+i),l>100&&(l=100,k=l-i),this.coords.p_from_real=this.calcWithStep(k),this.coords.p_from_real=this.checkDiapason(this.coords.p_from_real,this.options.from_min,this.options.from_max),this.coords.p_from_fake=this.convertToFakePercent(this.coords.p_from_real),this.coords.p_to_real=this.calcWithStep(l),this.coords.p_to_real=this.checkDiapason(this.coords.p_to_real,this.options.to_min,this.options.to_max),this.coords.p_to_fake=this.convertToFakePercent(this.coords.p_to_real)}"single"===this.options.type?(this.coords.p_bar_x=this.coords.p_handle/2,this.coords.p_bar_w=this.coords.p_single_fake,this.result.from_percent=this.coords.p_single_real,this.result.from=this.convertToValue(this.coords.p_single_real),this.options.values.length&&(this.result.from_value=this.options.values[this.result.from])):(this.coords.p_bar_x=this.toFixed(this.coords.p_from_fake+this.coords.p_handle/2),this.coords.p_bar_w=this.toFixed(this.coords.p_to_fake-this.coords.p_from_fake),this.result.from_percent=this.coords.p_from_real,this.result.from=this.convertToValue(this.coords.p_from_real),this.result.to_percent=this.coords.p_to_real,this.result.to=this.convertToValue(this.coords.p_to_real),this.options.values.length&&(this.result.from_value=this.options.values[this.result.from],this.result.to_value=this.options.values[this.result.to])),this.calcMinMax(),this.calcLabels()}},calcPointerPercent:function(){return this.coords.w_rs?(this.coords.x_pointer<0||isNaN(this.coords.x_pointer)?this.coords.x_pointer=0:this.coords.x_pointer>this.coords.w_rs&&(this.coords.x_pointer=this.coords.w_rs),void(this.coords.p_pointer=this.toFixed(this.coords.x_pointer/this.coords.w_rs*100))):void(this.coords.p_pointer=0)},convertToRealPercent:function(a){var b=100-this.coords.p_handle;return a/b*100},convertToFakePercent:function(a){var b=100-this.coords.p_handle;return a/100*b},getHandleX:function(){var a=100-this.coords.p_handle,b=this.toFixed(this.coords.p_pointer-this.coords.p_gap);return b<0?b=0:b>a&&(b=a),b},calcHandlePercent:function(){"single"===this.options.type?this.coords.w_handle=this.$cache.s_single.outerWidth(!1):this.coords.w_handle=this.$cache.s_from.outerWidth(!1),this.coords.p_handle=this.toFixed(this.coords.w_handle/this.coords.w_rs*100)},chooseHandle:function(a){if("single"===this.options.type)return"single";var b=this.coords.p_from_real+(this.coords.p_to_real-this.coords.p_from_real)/2;return a>=b?this.options.to_fixed?"from":"to":this.options.from_fixed?"to":"from"},calcMinMax:function(){this.coords.w_rs&&(this.labels.p_min=this.labels.w_min/this.coords.w_rs*100,this.labels.p_max=this.labels.w_max/this.coords.w_rs*100)},calcLabels:function(){this.coords.w_rs&&!this.options.hide_from_to&&("single"===this.options.type?(this.labels.w_single=this.$cache.single.outerWidth(!1),this.labels.p_single_fake=this.labels.w_single/this.coords.w_rs*100,this.labels.p_single_left=this.coords.p_single_fake+this.coords.p_handle/2-this.labels.p_single_fake/2,this.labels.p_single_left=this.checkEdges(this.labels.p_single_left,this.labels.p_single_fake)):(this.labels.w_from=this.$cache.from.outerWidth(!1),this.labels.p_from_fake=this.labels.w_from/this.coords.w_rs*100,this.labels.p_from_left=this.coords.p_from_fake+this.coords.p_handle/2-this.labels.p_from_fake/2,this.labels.p_from_left=this.toFixed(this.labels.p_from_left),this.labels.p_from_left=this.checkEdges(this.labels.p_from_left,this.labels.p_from_fake),this.labels.w_to=this.$cache.to.outerWidth(!1),this.labels.p_to_fake=this.labels.w_to/this.coords.w_rs*100,this.labels.p_to_left=this.coords.p_to_fake+this.coords.p_handle/2-this.labels.p_to_fake/2,this.labels.p_to_left=this.toFixed(this.labels.p_to_left),this.labels.p_to_left=this.checkEdges(this.labels.p_to_left,this.labels.p_to_fake),this.labels.w_single=this.$cache.single.outerWidth(!1),this.labels.p_single_fake=this.labels.w_single/this.coords.w_rs*100,this.labels.p_single_left=(this.labels.p_from_left+this.labels.p_to_left+this.labels.p_to_fake)/2-this.labels.p_single_fake/2,this.labels.p_single_left=this.toFixed(this.labels.p_single_left),this.labels.p_single_left=this.checkEdges(this.labels.p_single_left,this.labels.p_single_fake)))},updateScene:function(){this.raf_id&&(cancelAnimationFrame(this.raf_id),this.raf_id=null),clearTimeout(this.update_tm),this.update_tm=null,this.options&&(this.drawHandles(),this.is_active?this.raf_id=requestAnimationFrame(this.updateScene.bind(this)):this.update_tm=setTimeout(this.updateScene.bind(this),300))},drawHandles:function(){this.coords.w_rs=this.$cache.rs.outerWidth(!1),this.coords.w_rs&&(this.coords.w_rs!==this.coords.w_rs_old&&(this.target="base",this.is_resize=!0),(this.coords.w_rs!==this.coords.w_rs_old||this.force_redraw)&&(this.setMinMax(),this.calc(!0),this.drawLabels(),this.options.grid&&(this.calcGridMargin(),this.calcGridLabels()),this.force_redraw=!0,this.coords.w_rs_old=this.coords.w_rs,this.drawShadow()),this.coords.w_rs&&(this.dragging||this.force_redraw||this.is_key)&&((this.old_from!==this.result.from||this.old_to!==this.result.to||this.force_redraw||this.is_key)&&(this.drawLabels(),this.$cache.bar[0].style.left=this.coords.p_bar_x+"%",this.$cache.bar[0].style.width=this.coords.p_bar_w+"%","single"===this.options.type?(this.$cache.s_single[0].style.left=this.coords.p_single_fake+"%",this.$cache.single[0].style.left=this.labels.p_single_left+"%",this.options.values.length?this.$cache.input.prop("value",this.result.from_value):this.$cache.input.prop("value",this.result.from),this.$cache.input.data("from",this.result.from)):(this.$cache.s_from[0].style.left=this.coords.p_from_fake+"%",this.$cache.s_to[0].style.left=this.coords.p_to_fake+"%",(this.old_from!==this.result.from||this.force_redraw)&&(this.$cache.from[0].style.left=this.labels.p_from_left+"%"),(this.old_to!==this.result.to||this.force_redraw)&&(this.$cache.to[0].style.left=this.labels.p_to_left+"%"),this.$cache.single[0].style.left=this.labels.p_single_left+"%",this.options.values.length?this.$cache.input.prop("value",this.result.from_value+this.options.input_values_separator+this.result.to_value):this.$cache.input.prop("value",this.result.from+this.options.input_values_separator+this.result.to),this.$cache.input.data("from",this.result.from),this.$cache.input.data("to",this.result.to)),this.old_from===this.result.from&&this.old_to===this.result.to||this.is_start||this.$cache.input.trigger("change"),this.old_from=this.result.from,this.old_to=this.result.to,this.is_resize||this.is_update||this.is_start||this.is_finish||this.callOnChange(),(this.is_key||this.is_click)&&(this.is_key=!1,this.is_click=!1,this.callOnFinish()),this.is_update=!1,this.is_resize=!1,this.is_finish=!1),this.is_start=!1,this.is_key=!1,this.is_click=!1,this.force_redraw=!1))},drawLabels:function(){if(this.options){var a,b,c,d=this.options.values.length,e=this.options.p_values;if(!this.options.hide_from_to)if("single"===this.options.type)d?(a=this.decorate(e[this.result.from]),this.$cache.single.html(a)):(a=this.decorate(this._prettify(this.result.from),this.result.from),this.$cache.single.html(a)),this.calcLabels(),this.labels.p_single_left<this.labels.p_min+1?this.$cache.min[0].style.visibility="hidden":this.$cache.min[0].style.visibility="visible",this.labels.p_single_left+this.labels.p_single_fake>100-this.labels.p_max-1?this.$cache.max[0].style.visibility="hidden":this.$cache.max[0].style.visibility="visible";else{d?(this.options.decorate_both?(a=this.decorate(e[this.result.from]),a+=this.options.values_separator,a+=this.decorate(e[this.result.to])):a=this.decorate(e[this.result.from]+this.options.values_separator+e[this.result.to]),b=this.decorate(e[this.result.from]),c=this.decorate(e[this.result.to]),this.$cache.single.html(a),this.$cache.from.html(b),this.$cache.to.html(c)):(this.options.decorate_both?(a=this.decorate(this._prettify(this.result.from),this.result.from),a+=this.options.values_separator,a+=this.decorate(this._prettify(this.result.to),this.result.to)):a=this.decorate(this._prettify(this.result.from)+this.options.values_separator+this._prettify(this.result.to),this.result.to),b=this.decorate(this._prettify(this.result.from),this.result.from),c=this.decorate(this._prettify(this.result.to),this.result.to),this.$cache.single.html(a),this.$cache.from.html(b),this.$cache.to.html(c)),this.calcLabels();var f=Math.min(this.labels.p_single_left,this.labels.p_from_left),g=this.labels.p_single_left+this.labels.p_single_fake,h=this.labels.p_to_left+this.labels.p_to_fake,i=Math.max(g,h);this.labels.p_from_left+this.labels.p_from_fake>=this.labels.p_to_left?(this.$cache.from[0].style.visibility="hidden",this.$cache.to[0].style.visibility="hidden",this.$cache.single[0].style.visibility="visible",this.result.from===this.result.to?("from"===this.target?this.$cache.from[0].style.visibility="visible":"to"===this.target&&(this.$cache.to[0].style.visibility="visible"),this.$cache.single[0].style.visibility="hidden",i=h):(this.$cache.from[0].style.visibility="hidden",this.$cache.to[0].style.visibility="hidden",this.$cache.single[0].style.visibility="visible",i=Math.max(g,h))):(this.$cache.from[0].style.visibility="visible",this.$cache.to[0].style.visibility="visible",this.$cache.single[0].style.visibility="hidden"),f<this.labels.p_min+1?this.$cache.min[0].style.visibility="hidden":this.$cache.min[0].style.visibility="visible",i>100-this.labels.p_max-1?this.$cache.max[0].style.visibility="hidden":this.$cache.max[0].style.visibility="visible"}}},drawShadow:function(){var a,b,c,d,e=this.options,f=this.$cache,g="number"==typeof e.from_min&&!isNaN(e.from_min),h="number"==typeof e.from_max&&!isNaN(e.from_max),i="number"==typeof e.to_min&&!isNaN(e.to_min),j="number"==typeof e.to_max&&!isNaN(e.to_max);"single"===e.type?e.from_shadow&&(g||h)?(a=this.convertToPercent(g?e.from_min:e.min),b=this.convertToPercent(h?e.from_max:e.max)-a,a=this.toFixed(a-this.coords.p_handle/100*a),b=this.toFixed(b-this.coords.p_handle/100*b),a+=this.coords.p_handle/2,f.shad_single[0].style.display="block",f.shad_single[0].style.left=a+"%",f.shad_single[0].style.width=b+"%"):f.shad_single[0].style.display="none":(e.from_shadow&&(g||h)?(a=this.convertToPercent(g?e.from_min:e.min),b=this.convertToPercent(h?e.from_max:e.max)-a,a=this.toFixed(a-this.coords.p_handle/100*a),b=this.toFixed(b-this.coords.p_handle/100*b),a+=this.coords.p_handle/2,f.shad_from[0].style.display="block",f.shad_from[0].style.left=a+"%",f.shad_from[0].style.width=b+"%"):f.shad_from[0].style.display="none",e.to_shadow&&(i||j)?(c=this.convertToPercent(i?e.to_min:e.min),d=this.convertToPercent(j?e.to_max:e.max)-c,c=this.toFixed(c-this.coords.p_handle/100*c),d=this.toFixed(d-this.coords.p_handle/100*d),c+=this.coords.p_handle/2,f.shad_to[0].style.display="block",f.shad_to[0].style.left=c+"%",f.shad_to[0].style.width=d+"%"):f.shad_to[0].style.display="none")},callOnStart:function(){this.options.onStart&&"function"==typeof this.options.onStart&&this.options.onStart(this.result)},callOnChange:function(){this.options.onChange&&"function"==typeof this.options.onChange&&this.options.onChange(this.result)},callOnFinish:function(){this.options.onFinish&&"function"==typeof this.options.onFinish&&this.options.onFinish(this.result)},callOnUpdate:function(){this.options.onUpdate&&"function"==typeof this.options.onUpdate&&this.options.onUpdate(this.result)},toggleInput:function(){this.$cache.input.toggleClass("irs-hidden-input")},convertToPercent:function(a,b){var c,d,e=this.options.max-this.options.min,f=e/100;return e?(c=b?a:a-this.options.min,d=c/f,this.toFixed(d)):(this.no_diapason=!0,0)},convertToValue:function(a){var b,c,d=this.options.min,e=this.options.max,f=d.toString().split(".")[1],g=e.toString().split(".")[1],h=0,i=0;if(0===a)return this.options.min;if(100===a)return this.options.max;f&&(b=f.length,h=b),g&&(c=g.length,h=c),b&&c&&(h=b>=c?b:c),d<0&&(i=Math.abs(d),d=+(d+i).toFixed(h),e=+(e+i).toFixed(h));var j,k=(e-d)/100*a+d,l=this.options.step.toString().split(".")[1];return l?k=+k.toFixed(l.length):(k/=this.options.step,k*=this.options.step,k=+k.toFixed(0)),i&&(k-=i),j=l?+k.toFixed(l.length):this.toFixed(k),j<this.options.min?j=this.options.min:j>this.options.max&&(j=this.options.max),j},calcWithStep:function(a){var b=Math.round(a/this.coords.p_step)*this.coords.p_step;return b>100&&(b=100),100===a&&(b=100),this.toFixed(b)},checkMinInterval:function(a,b,c){var d,e,f=this.options;return f.min_interval?(d=this.convertToValue(a),e=this.convertToValue(b),"from"===c?e-d<f.min_interval&&(d=e-f.min_interval):d-e<f.min_interval&&(d=e+f.min_interval),this.convertToPercent(d)):a},checkMaxInterval:function(a,b,c){var d,e,f=this.options;return f.max_interval?(d=this.convertToValue(a),e=this.convertToValue(b),"from"===c?e-d>f.max_interval&&(d=e-f.max_interval):d-e>f.max_interval&&(d=e+f.max_interval),this.convertToPercent(d)):a},checkDiapason:function(a,b,c){var d=this.convertToValue(a),e=this.options;return"number"!=typeof b&&(b=e.min),"number"!=typeof c&&(c=e.max), d<b&&(d=b),d>c&&(d=c),this.convertToPercent(d)},toFixed:function(a){return a=a.toFixed(9),+a},_prettify:function(a){return this.options.prettify_enabled?this.options.prettify&&"function"==typeof this.options.prettify?this.options.prettify(a):this.prettify(a):a},prettify:function(a){var b=a.toString();return b.replace(/(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g,"$1"+this.options.prettify_separator)},checkEdges:function(a,b){return this.options.force_edges?(a<0?a=0:a>100-b&&(a=100-b),this.toFixed(a)):this.toFixed(a)},validate:function(){var a,b,c=this.options,d=this.result,e=c.values,f=e.length;if("string"==typeof c.min&&(c.min=+c.min),"string"==typeof c.max&&(c.max=+c.max),"string"==typeof c.from&&(c.from=+c.from),"string"==typeof c.to&&(c.to=+c.to),"string"==typeof c.step&&(c.step=+c.step),"string"==typeof c.from_min&&(c.from_min=+c.from_min),"string"==typeof c.from_max&&(c.from_max=+c.from_max),"string"==typeof c.to_min&&(c.to_min=+c.to_min),"string"==typeof c.to_max&&(c.to_max=+c.to_max),"string"==typeof c.keyboard_step&&(c.keyboard_step=+c.keyboard_step),"string"==typeof c.grid_num&&(c.grid_num=+c.grid_num),c.max<c.min&&(c.max=c.min),f)for(c.p_values=[],c.min=0,c.max=f-1,c.step=1,c.grid_num=c.max,c.grid_snap=!0,b=0;b<f;b++)a=+e[b],isNaN(a)?a=e[b]:(e[b]=a,a=this._prettify(a)),c.p_values.push(a);("number"!=typeof c.from||isNaN(c.from))&&(c.from=c.min),("number"!=typeof c.to||isNaN(c.from))&&(c.to=c.max),"single"===c.type?(c.from<c.min&&(c.from=c.min),c.from>c.max&&(c.from=c.max)):((c.from<c.min||c.from>c.max)&&(c.from=c.min),(c.to>c.max||c.to<c.min)&&(c.to=c.max),c.from>c.to&&(c.from=c.to)),("number"!=typeof c.step||isNaN(c.step)||!c.step||c.step<0)&&(c.step=1),("number"!=typeof c.keyboard_step||isNaN(c.keyboard_step)||!c.keyboard_step||c.keyboard_step<0)&&(c.keyboard_step=5),"number"==typeof c.from_min&&c.from<c.from_min&&(c.from=c.from_min),"number"==typeof c.from_max&&c.from>c.from_max&&(c.from=c.from_max),"number"==typeof c.to_min&&c.to<c.to_min&&(c.to=c.to_min),"number"==typeof c.to_max&&c.from>c.to_max&&(c.to=c.to_max),d&&(d.min!==c.min&&(d.min=c.min),d.max!==c.max&&(d.max=c.max),(d.from<d.min||d.from>d.max)&&(d.from=c.from),(d.to<d.min||d.to>d.max)&&(d.to=c.to)),("number"!=typeof c.min_interval||isNaN(c.min_interval)||!c.min_interval||c.min_interval<0)&&(c.min_interval=0),("number"!=typeof c.max_interval||isNaN(c.max_interval)||!c.max_interval||c.max_interval<0)&&(c.max_interval=0),c.min_interval&&c.min_interval>c.max-c.min&&(c.min_interval=c.max-c.min),c.max_interval&&c.max_interval>c.max-c.min&&(c.max_interval=c.max-c.min)},decorate:function(a,b){var c="",d=this.options;return d.prefix&&(c+=d.prefix),c+=a,d.max_postfix&&(d.values.length&&a===d.p_values[d.max]?(c+=d.max_postfix,d.postfix&&(c+=" ")):b===d.max&&(c+=d.max_postfix,d.postfix&&(c+=" "))),d.postfix&&(c+=d.postfix),c},updateFrom:function(){this.result.from=this.options.from,this.result.from_percent=this.convertToPercent(this.result.from),this.options.values&&(this.result.from_value=this.options.values[this.result.from])},updateTo:function(){this.result.to=this.options.to,this.result.to_percent=this.convertToPercent(this.result.to),this.options.values&&(this.result.to_value=this.options.values[this.result.to])},updateResult:function(){this.result.min=this.options.min,this.result.max=this.options.max,this.updateFrom(),this.updateTo()},appendGrid:function(){if(this.options.grid){var a,b,c,d,e,f=this.options,g=f.max-f.min,h=f.grid_num,i=0,j=0,k=4,l=0,m="";for(this.calcGridMargin(),f.grid_snap?(h=g/f.step,i=this.toFixed(f.step/(g/100))):i=this.toFixed(100/h),h>4&&(k=3),h>7&&(k=2),h>14&&(k=1),h>28&&(k=0),a=0;a<h+1;a++){for(c=k,j=this.toFixed(i*a),j>100&&(j=100,c-=2,c<0&&(c=0)),this.coords.big[a]=j,d=(j-i*(a-1))/(c+1),b=1;b<=c&&0!==j;b++)l=this.toFixed(j-d*b),m+='<span class="irs-grid-pol small" style="left: '+l+'%"></span>';m+='<span class="irs-grid-pol" style="left: '+j+'%"></span>',e=this.convertToValue(j),e=f.values.length?f.p_values[e]:this._prettify(e),m+='<span class="irs-grid-text js-grid-text-'+a+'" style="left: '+j+'%">'+e+"</span>"}this.coords.big_num=Math.ceil(h+1),this.$cache.cont.addClass("irs-with-grid"),this.$cache.grid.html(m),this.cacheGridLabels()}},cacheGridLabels:function(){var a,b,c=this.coords.big_num;for(b=0;b<c;b++)a=this.$cache.grid.find(".js-grid-text-"+b),this.$cache.grid_labels.push(a);this.calcGridLabels()},calcGridLabels:function(){var a,b,c=[],d=[],e=this.coords.big_num;for(a=0;a<e;a++)this.coords.big_w[a]=this.$cache.grid_labels[a].outerWidth(!1),this.coords.big_p[a]=this.toFixed(this.coords.big_w[a]/this.coords.w_rs*100),this.coords.big_x[a]=this.toFixed(this.coords.big_p[a]/2),c[a]=this.toFixed(this.coords.big[a]-this.coords.big_x[a]),d[a]=this.toFixed(c[a]+this.coords.big_p[a]);for(this.options.force_edges&&(c[0]<-this.coords.grid_gap&&(c[0]=-this.coords.grid_gap,d[0]=this.toFixed(c[0]+this.coords.big_p[0]),this.coords.big_x[0]=this.coords.grid_gap),d[e-1]>100+this.coords.grid_gap&&(d[e-1]=100+this.coords.grid_gap,c[e-1]=this.toFixed(d[e-1]-this.coords.big_p[e-1]),this.coords.big_x[e-1]=this.toFixed(this.coords.big_p[e-1]-this.coords.grid_gap))),this.calcGridCollision(2,c,d),this.calcGridCollision(4,c,d),a=0;a<e;a++)b=this.$cache.grid_labels[a][0],b.style.marginLeft=-this.coords.big_x[a]+"%"},calcGridCollision:function(a,b,c){var d,e,f,g=this.coords.big_num;for(d=0;d<g&&(e=d+a/2,!(e>=g));d+=a)f=this.$cache.grid_labels[e][0],c[d]<=b[e]?f.style.visibility="visible":f.style.visibility="hidden"},calcGridMargin:function(){this.options.grid_margin&&(this.coords.w_rs=this.$cache.rs.outerWidth(!1),this.coords.w_rs&&("single"===this.options.type?this.coords.w_handle=this.$cache.s_single.outerWidth(!1):this.coords.w_handle=this.$cache.s_from.outerWidth(!1),this.coords.p_handle=this.toFixed(this.coords.w_handle/this.coords.w_rs*100),this.coords.grid_gap=this.toFixed(this.coords.p_handle/2-.1),this.$cache.grid[0].style.width=this.toFixed(100-this.coords.p_handle)+"%",this.$cache.grid[0].style.left=this.coords.grid_gap+"%"))},update:function(b){this.input&&(this.is_update=!0,this.options.from=this.result.from,this.options.to=this.result.to,this.options=a.extend(this.options,b),this.validate(),this.updateResult(b),this.toggleInput(),this.remove(),this.init(!0))},reset:function(){this.input&&(this.updateResult(),this.update())},destroy:function(){this.input&&(this.toggleInput(),this.$cache.input.prop("readonly",!1),a.data(this.input,"ionRangeSlider",null),this.remove(),this.input=null,this.options=null)}},a.fn.ionRangeSlider=function(b){return this.each(function(){a.data(this,"ionRangeSlider")||a.data(this,"ionRangeSlider",new l(this,b,(f++)))})},function(){for(var a=0,b=["ms","moz","webkit","o"],d=0;d<b.length&&!c.requestAnimationFrame;++d)c.requestAnimationFrame=c[b[d]+"RequestAnimationFrame"],c.cancelAnimationFrame=c[b[d]+"CancelAnimationFrame"]||c[b[d]+"CancelRequestAnimationFrame"];c.requestAnimationFrame||(c.requestAnimationFrame=function(b,d){var e=(new Date).getTime(),f=Math.max(0,16-(e-a)),g=c.setTimeout(function(){b(e+f)},f);return a=e+f,g}),c.cancelAnimationFrame||(c.cancelAnimationFrame=function(a){clearTimeout(a)})}()}(jQuery,document,window,navigator);
'use strict' module.exports={ mailer:{ service:'Gmail', //host: 'smtp.gmail.com', // port: 465, // secure: true, auth:{ user:'updeshumrao@gmail.com', pass:'updesh1212' } }, dbConnectstring:'mongodb://127.0.0.1:27017/codeshare', sessionKey:'HaloCode4Share' }
import Room from './Room'; import { LicodeEvent, RoomEvent, StreamEvent } from './Events'; import Stream from './Stream'; import Logger from './utils/Logger'; // eslint-disable-next-line require('expose-loader?adapter!../lib/adapter.js'); // eslint-disable-next-line require('script-loader!./utils/L.Resizer.js'); const Erizo = { Room: Room.bind(null, undefined, undefined), LicodeEvent, RoomEvent, StreamEvent, Stream: Stream.bind(null, undefined), Logger, }; export default Erizo;
import _ from 'lodash'; import React from 'react'; import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines'; function average(data) { return _.round(_.sum(data)/data.length); } export default (props) => { return ( <div> <Sparklines height={120} width={180} data={props.data}> <SparklinesLine color = {props.color} /> <SparklinesReferenceLine type = "avg" /> </Sparklines> <div>{average(props.data)} {props.units}</div> </div> ) }
import React from 'react'; import {Card, Button} from 'react-bootstrap'; const Post = (props) => { return ( <div className="p-3"> <Card > <Card.Img variant="top" src="gatsby-cheers.jpg" /> <Card.Body> <Card.Title>{props.Title}</Card.Title> <Card.Text> Some quick example text to build on the card title and make up the bulk of the card's content. </Card.Text> <Button variant="primary">Go somewhere</Button> </Card.Body> </Card> </div> ); }; export default Post;
// Let's define a console if none exist so those pesky debug statements don't // cause errors when Firebug is not open. if (!console) { var console = { log:function() {} }; } function openCallback(input) { console.log('openCallback: ', input); } function saveCallback() { console.log('saveCallback'); var txt = controller.getTextForSaving(); console.log('save text = ', txt); return txt; } // Init our application when the dom is ready. window.addEvent('domready', function() { controller = new Controller('#canvas', '#grid', '#toolbar'); var config = new FileDialogsConfig(); config.width = 45; config.height = 16; config.padding = 5; config.open.image = "images/folder_page_white.png"; config.open.handler = "openCallback"; config.save.image = "images/page_save.png"; config.save.handler = "saveCallback"; new FileDialogs("openClosePlaceholder", config); });
const express = require('express'); const router = express.Router(); const app = express(); const BASE_PATH = 'v1_0-citizen/6-current-employment'; const ABS_BASE_PATH = `/${BASE_PATH}`; const NEXT_PATH = '/v1_0-citizen/7-previous-employment'; const MAX_PREVIOUS_JOBS = 4; // Redirect /current-employment to first question in sequence router.all('/', function (req, res) { res.redirect(`${ABS_BASE_PATH}/guard`); }); router.post('/guard', function (req, res) { const answer = req.body.ceCurrentlyWorking; app.locals.currentJobCount = 1; if (typeof answer !== 'undefined') { if (answer === 'ce-currently-working-yes') { res.redirect(`${ABS_BASE_PATH}/type?job=1`); } else if (answer === 'ce-currently-working-no') { res.redirect(NEXT_PATH); } } else { res.redirect(`${ABS_BASE_PATH}/guard`); } }); router.post('/type', function (req, res) { const answer = req.body.ceCurrentWorkType; if (answer === 'Paid') { res.redirect(`${ABS_BASE_PATH}/payment-frequency`); } else if (answer === 'Voluntary') { res.redirect(`${ABS_BASE_PATH}/choose-to-be-paid`); } else { res.redirect(`${ABS_BASE_PATH}/payment-frequency`); } }); router.post('/choose-to-be-paid', function (req, res) { res.redirect(`${ABS_BASE_PATH}/get-paid`); }); router.post('/get-paid', function (req, res) { const answer = req.body.ceGetPaid; if (answer === 'ce-get-paid-no') { res.redirect(`${ABS_BASE_PATH}/employer-name`); } else { res.redirect(`${ABS_BASE_PATH}/payment-frequency`); } }); router.post('/payment-frequency', function (req, res) { res.redirect(`${ABS_BASE_PATH}/employer-name`); }); router.post('/employer-name', function (req, res) { res.redirect(`${ABS_BASE_PATH}/employer-address`); }); router.post('/employer-address', function (req, res) { res.redirect(`${ABS_BASE_PATH}/employer-contact`); }); router.post('/employer-contact', function (req, res) { res.redirect(`${ABS_BASE_PATH}/hours`); }); router.post('/hours', function (req, res) { res.redirect(`${ABS_BASE_PATH}/self-employed-or-company-director`); }); router.post('/self-employed-or-company-director', function (req, res) { res.redirect(`${ABS_BASE_PATH}/another-one`); }); router.post('/another-one', function (req, res) { const answer = req.body.ceAnotherJob; if (answer === 'ce-another-job-yes') { app.locals.currentJobCount = typeof app.locals.currentJobCount === 'undefined' ? 1 : ++app.locals.currentJobCount; if (app.locals.currentJobCount === MAX_PREVIOUS_JOBS) { res.redirect(`${ABS_BASE_PATH}/employer-limit-warning`); } else { res.redirect(`${ABS_BASE_PATH}/type?job=` + app.locals.currentJobCount); } } else { res.redirect(NEXT_PATH); } }); router.get('/employer-limit-warning', function (req, res) { res.render(`${BASE_PATH}/employer-limit-warning`, { maxPreviousJobs: MAX_PREVIOUS_JOBS.toString() }); }); router.post('/employer-limit-warning', function (req, res) { res.redirect(NEXT_PATH); }); module.exports = router;
/** * jBility * jBility is a free set of accessibility functions that uses JQuery. * By: Uriel Cairê Balan Calvi * Available on: https://github.com/urielcaire/jBility */ jQuery(document).ready(function( $ ){ /*=================================================================== * jBility uses JsCookie to manager cookies. * JsCookie is available on: https://github.com/urielcaire/jscookie *====================================================================*/ function createCookie(name, value, days){ var expires = ""; if(days){ var time = new Date(); time.setTime(time.getTime()+(days*24*60*60*1000)); } document.cookie = name+"="+value+expires+"; path=/"; } function getCookie(name){ var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return ""; } function deleteCookie(name) { createCookie(name,"",-1); } function checkCookie(name){ var check = getCookie(name); if(check != "") return true; return false; } /*====================================== * jBility functions *======================================*/ function addConstrast(){ console.log('addConstrast'); $('*').addClass('pagina-acessivel'); $('.acess-container').addClass('f-transparent'); $('#botao').addClass('f-transparent'); $('#acess-icons').addClass('f-transparent'); $('.acess-icon').addClass('f-transparent'); $('img').addClass('f-transparent'); $('#jbbutton').addClass('f-transparent'); } function removeConstrast(){ console.log('removeConstrast'); $('*').removeClass('pagina-acessivel'); $('.acess-container').removeClass('f-transparent'); $('#botao').removeClass('f-transparent'); $('#acess-icons').removeClass('f-transparent'); $('.acess-icon').removeClass('f-transparent'); $('img').removeClass('f-transparent'); $('#jbbutton').removeClass('f-transparent'); } if(checkCookie('ccontrast')){ addConstrast(); } $('#contrast').click(function(){ var ck = checkCookie('ccontrast'); if(ck){ deleteCookie('ccontrast'); removeConstrast(); }else{ createCookie('ccontrast', 'cookieContrast'); addConstrast(); } }); var $cElements = $("body").find("*"); var fonts = []; function getFontSize() { for (var i = 0; i < $cElements.length; i++) { fonts.push(parseFloat($cElements.eq(i).css('font-size'))); } } getFontSize(); $("#increaseFont").on('click', function() { for (var i = 0; i < $cElements.length; i++) { ++fonts[i]; $cElements.eq(i).css('font-size', fonts[i]); } }); $("#decreaseFont").on('click', function() { for (var i = 0; i < $cElements.length; i++) { --fonts[i]; $cElements.eq(i).css('font-size', fonts[i]); } }); $('#jbbutton').click(function(){ $('#acess-icons').toggle(150); }); });
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.6.2 (2020-12-08) */ !function(){"use strict";var t,e,n,r,l=function(t){var e=t;return{get:function(){return e},set:function(t){e=t}}},o=tinymce.util.Tools.resolve("tinymce.PluginManager"),d=tinymce.util.Tools.resolve("tinymce.util.Tools"),i=function(){},u=function(t){return function(){return t}},a=u(!1),c=u(!0),f=function(){return s},s=(t=function(t){return t.isNone()},{fold:function(t,e){return t()},is:a,isSome:a,isNone:c,getOr:n=function(t){return t},getOrThunk:e=function(t){return t()},getOrDie:function(t){throw new Error(t||"error: getOrDie called on none.")},getOrNull:u(null),getOrUndefined:u(undefined),or:n,orThunk:e,map:f,each:i,bind:f,exists:a,forall:c,filter:f,equals:t,equals_:t,toArray:function(){return[]},toString:u("none()")}),m=function(n){var t=u(n),e=function(){return o},r=function(t){return t(n)},o={fold:function(t,e){return e(n)},is:function(t){return n===t},isSome:c,isNone:a,getOr:t,getOrThunk:t,getOrDie:t,getOrNull:t,getOrUndefined:t,or:e,orThunk:e,map:function(t){return m(t(n))},each:function(t){t(n)},bind:r,exists:r,forall:r,filter:function(t){return t(n)?o:s},toArray:function(){return[n]},toString:function(){return"some("+n+")"},equals:function(t){return t.is(n)},equals_:function(t,e){return t.fold(a,function(t){return e(n,t)})}};return o},g={some:m,none:f,from:function(t){return null===t||t===undefined?s:m(t)}},h=function(t){return!(null===(e=t)||e===undefined);var e},v=(r="function",function(t){return typeof t===r});function p(t,e){return b(document.createElement("canvas"),t,e)}function y(t){var e=p(t.width,t.height);return w(e).drawImage(t,0,0),e}function w(t){return t.getContext("2d")}function b(t,e,n){return t.width=e,t.height=n,t}var I,T,_,R,U=window.Promise?window.Promise:(I=function(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],C(t,A(E,this),A(L,this))},T=window,_=I.immediateFn||"function"==typeof T.setImmediate&&T.setImmediate||function(t){setTimeout(t,1)},R=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},I.prototype["catch"]=function(t){return this.then(null,t)},I.prototype.then=function(n,r){var o=this;return new I(function(t,e){x.call(o,new k(n,r,t,e))})},I.all=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var c=Array.prototype.slice.call(1===t.length&&R(t[0])?t[0]:t);return new I(function(o,i){if(0===c.length)return o([]);for(var u=c.length,t=0;t<c.length;t++)!function a(e,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if("function"==typeof n)return void n.call(t,function(t){a(e,t)},i)}c[e]=t,0==--u&&o(c)}catch(r){i(r)}}(t,c[t])})},I.resolve=function(e){return e&&"object"==typeof e&&e.constructor===I?e:new I(function(t){t(e)})},I.reject=function(n){return new I(function(t,e){e(n)})},I.race=function(o){return new I(function(t,e){for(var n=0,r=o;n<r.length;n++)r[n].then(t,e)})},I);function A(t,e){return function(){return t.apply(e,arguments)}}function x(r){var o=this;null!==this._state?_(function(){var t,e=o._state?r.onFulfilled:r.onRejected;if(null!==e){try{t=e(o._value)}catch(n){return void r.reject(n)}r.resolve(t)}else(o._state?r.resolve:r.reject)(o._value)}):this._deferreds.push(r)}function E(t){try{if(t===this)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var e=t.then;if("function"==typeof e)return void C(A(e,t),A(E,this),A(L,this))}this._state=!0,this._value=t,j.call(this)}catch(n){L.call(this,n)}}function L(t){this._state=!1,this._value=t,j.call(this)}function j(){for(var t=0,e=this._deferreds;t<e.length;t++){var n=e[t];x.call(this,n)}this._deferreds=[]}function k(t,e,n,r){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.resolve=n,this.reject=r}function C(t,e,n){var r=!1;try{t(function(t){r||(r=!0,e(t))},function(t){r||(r=!0,n(t))})}catch(o){if(r)return;r=!0,n(o)}}function O(t){var r,e=t.src;return 0===e.indexOf("data:")?S(e):(r=e,new U(function(t,n){var e=new XMLHttpRequest;e.open("GET",r,!0),e.responseType="blob",e.onload=function(){200===this.status&&t(this.response)},e.onerror=function(){var t,e=this;n(0===this.status?((t=new Error("No access to download image")).code=18,t.name="SecurityError",t):new Error("Error "+e.status+" downloading image"))},e.send()}))}function P(a){return new U(function(t,e){var n=URL.createObjectURL(a),r=new Image,o=function(){r.removeEventListener("load",i),r.removeEventListener("error",u)};function i(){o(),t(r)}function u(){o(),e("Unable to load data of type "+a.type+": "+n)}r.addEventListener("load",i),r.addEventListener("error",u),r.src=n,r.complete&&i()})}function S(n){return new U(function(t,e){(function(t){var e=t.split(","),n=/data:([^;]+)/.exec(e[0]);if(!n)return g.none();for(var r=n[1],o=e[1],i=atob(o),u=i.length,a=Math.ceil(u/1024),c=new Array(a),f=0;f<a;++f){for(var s=1024*f,l=Math.min(1024+s,u),d=new Array(l-s),m=s,h=0;m<l;++h,++m)d[h]=i[m].charCodeAt(0);c[f]=new Uint8Array(d)}return g.some(new Blob(c,{type:r}))})(n).fold(function(){e("uri is not base64: "+n)},t)})}function M(t,r,o){return r=r||"image/png",v(HTMLCanvasElement.prototype.toBlob)?new U(function(e,n){t.toBlob(function(t){t?e(t):n()},r,o)}):S(t.toDataURL(r,o))}function B(t){return P(t).then(function(t){var e;e=t,URL.revokeObjectURL(e.src);var n,r,o=p((r=t).naturalWidth||r.width,(n=t).naturalHeight||n.height);return w(o).drawImage(t,0,0),o})}var N=P,D=O,F=function(t,e){return function(t,e,n){for(var r=0,o=t.length;r<o;r++){var i=t[r];if(e(i,r))return g.some(i);if(n(i,r))break}return g.none()}(t,e,a)};function H(t,e,n){var r=e.type;function o(r,o){return t.then(function(t){return n=o,e=(e=r)||"image/png",t.toDataURL(e,n);var e,n})}return{getType:u(r),toBlob:function(){return U.resolve(e)},toDataURL:u(n),toBase64:function(){return n.split(",")[1]},toAdjustedBlob:function(e,n){return t.then(function(t){return M(t,e,n)})},toAdjustedDataURL:o,toAdjustedBase64:function(t,e){return o(t,e).then(function(t){return t.split(",")[1]})},toCanvas:function(){return t.then(y)}}}function q(e){return n=e,new U(function(t){var e=new FileReader;e.onloadend=function(){t(e.result)},e.readAsDataURL(n)}).then(function(t){return H(B(e),e,t)});var n}function z(e,t){return M(e,t).then(function(t){return H(U.resolve(e),t,e.toDataURL())})}function $(e,n){return e.toCanvas().then(function(t){return function(t,e,n){var r=p(t.width,t.height),o=w(r),i=0,u=0;90!==(n=n<0?360+n:n)&&270!==n||b(r,r.height,r.width);90!==n&&180!==n||(i=r.width);270!==n&&180!==n||(u=r.height);return o.translate(i,u),o.rotate(n*Math.PI/180),o.drawImage(t,0,0),z(r,e)}(t,e.getType(),n)})}function G(e,n){return e.toCanvas().then(function(t){return function(t,e,n){var r=p(t.width,t.height),o=w(r);"v"===n?(o.scale(1,-1),o.drawImage(t,0,-r.height)):(o.scale(-1,1),o.drawImage(t,-r.width,0));return z(r,e)}(t,e.getType(),n)})}var J=G,K=$,V=Object.keys,W=function(e,r,o){return void 0===o&&(o=!1),new U(function(t){var n=new XMLHttpRequest;n.onreadystatechange=function(){4===n.readyState&&t({status:n.status,blob:n.response})},n.open("GET",e,!0),n.withCredentials=o,function(t,e){for(var n=V(t),r=0,o=n.length;r<o;r++){var i=n[r];e(t[i],i)}}(r,function(t,e){n.setRequestHeader(e,t)}),n.responseType="blob",n.send()})},X=[{code:404,message:"Could not find Image Proxy"},{code:403,message:"Rejected request"},{code:0,message:"Incorrect Image Proxy URL"}],Q=[{type:"not_found",message:"Failed to load image."},{type:"key_missing",message:"The request did not include an api key."},{type:"key_not_found",message:"The provided api key could not be found."},{type:"domain_not_trusted",message:"The api key is not valid for the request origins."}],Y=function(t,e){var n,r,o=(n=function(t,e){return h(t)?t[e]:undefined},r=t,function(t,e){for(var n=0,r=t.length;n<r;n++)e(t[n],n)}(e,function(t){r=n(r,t)}),r);return g.from(o)},Z=function(t){var e,n=(e=t,"ImageProxy HTTP error: "+F(X,function(t){return e===t.code}).fold(u("Unknown ImageProxy error"),function(t){return t.message}));return U.reject(n)},tt=function(e){return F(Q,function(t){return t.type===e}).fold(u("Unknown service error"),function(t){return t.message})},et=function(t){return"ImageProxy Service error: "+function(t){try{return g.some(JSON.parse(t))}catch(e){return g.none()}}(t).bind(function(t){return Y(t,["error","type"]).map(tt)}).getOr("Invalid JSON in service error message")},nt=function(t){return r=t,new U(function(t,e){var n=new FileReader;n.onload=function(){t(n.result)},n.onerror=function(t){e(t)},n.readAsText(r)}).then(function(t){var e=et(t);return U.reject(e)});var r},rt=function(t){return t<200||300<=t},ot=function(t,e){var n,r,o,i={"Content-Type":"application/json;charset=UTF-8","tiny-api-key":e};return W((r=e,o=-1===(n=t).indexOf("?")?"?":"&",/[?&]apiKey=/.test(n)?n:n+o+"apiKey="+encodeURIComponent(r)),i).then(function(t){return rt(t.status)?(e=t.status,n=t.blob,r=e,"application/json"!==(null==(o=n)?void 0:o.type)||400!==r&&403!==r&&404!==r&&500!==r?Z(e):nt(n)):U.resolve(t.blob);var e,n,r,o})},it=function(t,e,n){return void 0===n&&(n=!1),e?ot(t,e):W(t,{},n).then(function(t){return rt(t.status)?Z(t.status):U.resolve(t.blob)})},ut=q,at=function(t){if(null===t||t===undefined)throw new Error("Node cannot be null or undefined");return{dom:t}},ct={fromHtml:function(t,e){var n=(e||document).createElement("div");if(n.innerHTML=t,!n.hasChildNodes()||1<n.childNodes.length)throw console.error("HTML does not have a single root node",t),new Error("HTML must have a single root node");return at(n.childNodes[0])},fromTag:function(t,e){var n=(e||document).createElement(t);return at(n)},fromText:function(t,e){var n=(e||document).createTextNode(t);return at(n)},fromDom:at,fromPoint:function(t,e,n){return g.from(t.dom.elementFromPoint(e,n)).map(at)}},ft=("undefined"!=typeof window||Function("return this;")(),function(t,e){return n=function(t){return function(t,e){var n=t.dom;if(1!==n.nodeType)return!1;var r=n;if(r.matches!==undefined)return r.matches(e);if(r.msMatchesSelector!==undefined)return r.msMatchesSelector(e);if(r.webkitMatchesSelector!==undefined)return r.webkitMatchesSelector(e);if(r.mozMatchesSelector!==undefined)return r.mozMatchesSelector(e);throw new Error("Browser lacks native selectors")}(t,e)},F(t.dom.childNodes,function(t){return n(ct.fromDom(t))}).map(ct.fromDom);var n}),st=tinymce.util.Tools.resolve("tinymce.util.Delay"),lt=tinymce.util.Tools.resolve("tinymce.util.Promise"),dt=tinymce.util.Tools.resolve("tinymce.util.URI"),mt=function(t){return t.getParam("imagetools_proxy")};function ht(t){var e,n;function r(t){return/^[0-9\.]+px$/.test(t)}return e=t.style.width,n=t.style.height,e||n?r(e)&&r(n)?{w:parseInt(e,10),h:parseInt(n,10)}:null:(e=t.width,n=t.height,e&&n?{w:parseInt(e,10),h:parseInt(n,10)}:null)}function gt(t){return{w:t.naturalWidth,h:t.naturalHeight}}var vt=0,pt=function(t){return ft(ct.fromDom(t),"img")},yt=function(t,e){return t.dom.is(e,"figure")},wt=function(t,e){return t.dom.is(e,"img:not([data-mce-object],[data-mce-placeholder])")},bt=function(e,t){var n=function(t){return wt(e,t)&&(Rt(e,t)||Ut(e,t)||h(mt(e)))};return yt(e,t)?pt(t).bind(function(t){return n(t.dom)?g.some(t.dom):g.none()}):n(t)?g.some(t):g.none()},It=function(t,e){t.notificationManager.open({text:e,type:"error"})},Tt=function(t){var e=t.selection.getNode(),n=t.dom.getParent(e,"figure.image");return null!==n&&yt(t,n)?pt(n):wt(t,e)?g.some(ct.fromDom(e)):g.none()},_t=function(t,e,n){var r=e.match(/(?:\/|^)(([^\/\?]+)\.(?:[a-z0-9.]+))(?:\?|$)/i);return h(r)?t.dom.encode(r[n]):null},Rt=function(t,e){var n=e.src;return 0===n.indexOf("data:")||0===n.indexOf("blob:")||new dt(n).host===t.documentBaseURI.host},Ut=function(t,e){return-1!==d.inArray(t.getParam("imagetools_cors_hosts",[],"string[]"),new dt(e.src).host)},At=function(t,e){if(Ut(t,e))return it(e.src,null,(n=t,r=e,-1!==d.inArray(n.getParam("imagetools_credentials_hosts",[],"string[]"),new dt(r.src).host)));var n,r,o;if(Rt(t,e))return D(e);var i=mt(t),u=i+(-1===i.indexOf("?")?"?":"&")+"url="+encodeURIComponent(e.src),a=(o=t).getParam("api_key",o.getParam("imagetools_api_key","","string"),"string");return it(u,a,!1)},xt=function(t,e){return n=t,g.from(n.getParam("imagetools_fetch_image",null,"function")).fold(function(){return At(t,e)},function(t){return t(e)});var n},Et=function(t,e){var n=t.editorUpload.blobCache.getByUri(e.src);return n?lt.resolve(n.blob()):xt(t,e)},Lt=function(t){st.clearTimeout(t.get())},jt=function(a,c,f,s,l,d,m){return f.toBlob().then(function(t){var e,n,o,r=a.editorUpload.blobCache,i=d.src,u=c.type===t.type;return a.getParam("images_reuse_filename",!1,"boolean")&&(o=r.getByUri(i),n=h(o)?(i=o.uri(),e=o.name(),o.filename()):(e=_t(a,i,2),_t(a,i,1))),o=r.create({id:"imagetools"+vt++,blob:t,base64:f.toBase64(),uri:i,name:e,filename:u?n:undefined}),r.add(o),a.undoManager.transact(function(){a.$(d).on("load",function r(){var t,e,n;a.$(d).off("load",r),a.nodeChanged(),s?a.editorUpload.uploadImagesAuto():(Lt(l),t=a,e=l,n=st.setEditorTimeout(t,function(){t.editorUpload.uploadImagesAuto()},t.getParam("images_upload_timeout",3e4,"number")),e.set(n))}),m&&a.$(d).attr({width:m.w,height:m.h}),a.$(d).attr({src:o.blobUri()}).removeAttr("data-mce-src")}),o})},kt=function(r,o,t,i){return function(){return Tt(r).fold(function(){It(r,"Could not find selected image")},function(n){return r._scanForImages().then(function(){return Et(r,n.dom)}).then(function(e){return ut(e).then(t).then(function(t){return jt(r,e,t,!1,o,n.dom,i)})})["catch"](function(t){It(r,t)})})}},Ct=function(e,n,r){return function(){var t=Tt(e).fold(function(){return null},function(t){var e=ht(t.dom);return e?{w:e.h,h:e.w}:null});return kt(e,n,function(t){return K(t,r)},t)()}},Ot=function(t,e,n){return function(){return kt(t,e,function(t){return J(t,n)})()}},Pt=function(e,n,u,a,c){return N(c).then(function(t){var e,n,r,o,i=gt(t);return a.w===i.w&&a.h===i.h||ht(u)&&(e=u,(n=i)&&(r=e.style.width,o=e.style.height,(r||o)&&(e.style.width=n.w+"px",e.style.height=n.h+"px",e.removeAttribute("data-mce-style")),r=e.width,o=e.height,(r||o)&&(e.setAttribute("width",String(n.w)),e.setAttribute("height",String(n.h))))),URL.revokeObjectURL(t.src),c}).then(ut).then(function(t){return jt(e,c,t,!0,n,u)})["catch"](function(){})},St=function(i,u){return function(){var r=Tt(i),o=r.map(function(t){return gt(t.dom)});r.each(function(e){bt(i,e.dom).each(function(t){Et(i,e.dom).then(function(t){var e,n={blob:e=t,url:URL.createObjectURL(e)};i.windowManager.open({title:"Edit Image",size:"large",body:{type:"panel",items:[{type:"imagetools",name:"imagetools",label:"Edit Image",currentState:n}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0,disabled:!0}],onSubmit:function(t){var n=t.getData().imagetools.blob;r.each(function(e){o.each(function(t){Pt(i,u,e.dom,t,n)})}),t.close()},onCancel:function(){},onAction:function(t,e){switch(e.name){case"save-state":e.value?t.enable("save"):t.disable("save");break;case"disable":t.disable("save"),t.disable("cancel");break;case"enable":t.enable("cancel")}}})})})})}};o.add("imagetools",function(t){var n,e,r,o,i,u,a,c,f=l(0),s=l(null);n=t,e=f,d.each({mceImageRotateLeft:Ct(n,e,-90),mceImageRotateRight:Ct(n,e,90),mceImageFlipVertical:Ot(n,e,"v"),mceImageFlipHorizontal:Ot(n,e,"h"),mceEditImage:St(n,e)},function(t,e){n.addCommand(e,t)}),o=function(t){return function(){return r.execCommand(t)}},(r=t).ui.registry.addButton("rotateleft",{tooltip:"Rotate counterclockwise",icon:"rotate-left",onAction:o("mceImageRotateLeft")}),r.ui.registry.addButton("rotateright",{tooltip:"Rotate clockwise",icon:"rotate-right",onAction:o("mceImageRotateRight")}),r.ui.registry.addButton("flipv",{tooltip:"Flip vertically",icon:"flip-vertically",onAction:o("mceImageFlipVertical")}),r.ui.registry.addButton("fliph",{tooltip:"Flip horizontally",icon:"flip-horizontally",onAction:o("mceImageFlipHorizontal")}),r.ui.registry.addButton("editimage",{tooltip:"Edit image",icon:"edit-image",onAction:o("mceEditImage"),onSetup:function(e){var t=function(){var t=Tt(r).forall(function(t){return bt(r,t.dom).isNone()});e.setDisabled(t)};return r.on("NodeChange",t),function(){r.off("NodeChange",t)}}}),r.ui.registry.addButton("imageoptions",{tooltip:"Image options",icon:"image",onAction:o("mceImage")}),r.ui.registry.addContextMenu("imagetools",{update:function(t){return bt(r,t).fold(function(){return[]},function(t){return[{text:"Edit image",icon:"edit-image",onAction:o("mceEditImage")}]})}}),(i=t).ui.registry.addContextToolbar("imagetools",{items:i.getParam("imagetools_toolbar","rotateleft rotateright flipv fliph editimage imageoptions"),predicate:function(t){return bt(i,t).isSome()},position:"node",scope:"node"}),a=f,c=s,(u=t).on("NodeChange",function(t){var e=c.get(),n=bt(u,t.element);e&&!n.exists(function(t){return e.src===t.src})&&(Lt(a),u.editorUpload.uploadImagesAuto(),c.set(null)),n.each(c.set)})})}();
'use strict'; exports.BattleAbilities = { /* Magic Healing This Pokemon heals 6% of their HP every turn. Ethereal Fist Punch Moves become Special and gain 1.2x damage (Same Moves effected as Iron Fist). Disperal Boosts Bullet Seed, Seed Bomb, and Seed Flare by 1.2x power, and Leech Seed deals 20% more damage and heals 30% more HP each turn. Housekeeping Removes hazards upon switch-in. Mind Trick Stat changes are received by the opposing pokemon and vice versa Flare Boost Doubles user's SpA when burned Knight's Blade Boosts the power of sword, cut, slash, and blade moves by 1.5x (List: Psycho Cut, Cut, Slash, Night Slash, Solar Blade, Leaf Blade, X-Scissor, Cross Poison, Air Slash, Air Cutter, Fury Cutter, Sacred Sword, Secret Sword, Razor Shell) Forecast If this Pokémon is holding a Weather Rock, its secondary typing becomes Water/Fire/Rock/Ice (depending on the rock) and summon the corresponding weather upon entering the field. Under Strong Winds, this mon gains the added Flying type. These items cannot be removed Time Warp Sets Trick Room upon entry Corrosion This Pokemon can poison any Pokemon, and attack any Pokemon with Poison moves, regardless of immunities. Air Stream Summons the new weather Air Current for 5 turns. In this weather, Flying-Types take 0.75* damage from Electric, Rock, and Ice-Type moves (kinda like Solid Rock), and the move Hurricane has perfect accuracy. Weather Ball doubles in power and becomes Flying-Type. Guard Up Upon switch-in, this Pokemon's Defense or Special Defense goes up by 1 stage depending on the opponent's higher attacking stat (Download clone). Scrappy Ignores every type inmunity when attacking. Technician This Pokemon's moves of 75 power or less have 1.5x power. Includes Struggle. */ };
import PortMessage from "./validatable/string/port"; import Port from "./validatable/port"; export default function String(value, message = PortMessage) { return Port(value, message); } //# sourceMappingURL=string.js.map
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // XML generation entry point. const $generatorSpring = {}; // Do XML escape. $generatorSpring.escape = function(s) { if (typeof (s) !== 'string') return s; return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }; // Add constructor argument $generatorSpring.constructorArg = function(res, ix, obj, propName, dflt, opt) { const v = (obj ? obj[propName] : null) || dflt; if ($generatorCommon.isDefinedAndNotEmpty(v)) res.line('<constructor-arg ' + (ix >= 0 ? 'index="' + ix + '" ' : '') + 'value="' + v + '"/>'); else if (!opt) { res.startBlock('<constructor-arg ' + (ix >= 0 ? 'index="' + ix + '"' : '') + '>'); res.line('<null/>'); res.endBlock('</constructor-arg>'); } }; // Add XML element. $generatorSpring.element = function(res, tag, attr1, val1, attr2, val2) { let elem = '<' + tag; if (attr1) elem += ' ' + attr1 + '="' + val1 + '"'; if (attr2) elem += ' ' + attr2 + '="' + val2 + '"'; elem += '/>'; res.emptyLineIfNeeded(); res.line(elem); }; // Add property. $generatorSpring.property = function(res, obj, propName, setterName, dflt) { if (!_.isNil(obj)) { const val = obj[propName]; if ($generatorCommon.isDefinedAndNotEmpty(val)) { const missDflt = _.isNil(dflt); // Add to result if no default provided or value not equals to default. if (missDflt || (!missDflt && val !== dflt)) { $generatorSpring.element(res, 'property', 'name', setterName ? setterName : propName, 'value', $generatorSpring.escape(val)); return true; } } } return false; }; // Add property for class name. $generatorSpring.classNameProperty = function(res, obj, propName) { const val = obj[propName]; if (!_.isNil(val)) $generatorSpring.element(res, 'property', 'name', propName, 'value', $generatorCommon.JavaTypes.fullClassName(val)); }; // Add list property. $generatorSpring.listProperty = function(res, obj, propName, listType, rowFactory) { const val = obj[propName]; if (val && val.length > 0) { res.emptyLineIfNeeded(); if (!listType) listType = 'list'; if (!rowFactory) rowFactory = (v) => '<value>' + $generatorSpring.escape(v) + '</value>'; res.startBlock('<property name="' + propName + '">'); res.startBlock('<' + listType + '>'); _.forEach(val, (v) => res.line(rowFactory(v))); res.endBlock('</' + listType + '>'); res.endBlock('</property>'); res.needEmptyLine = true; } }; // Add array property $generatorSpring.arrayProperty = function(res, obj, propName, descr, rowFactory) { const val = obj[propName]; if (val && val.length > 0) { res.emptyLineIfNeeded(); if (!rowFactory) rowFactory = (v) => '<bean class="' + v + '"/>'; res.startBlock('<property name="' + propName + '">'); res.startBlock('<list>'); _.forEach(val, (v) => res.append(rowFactory(v))); res.endBlock('</list>'); res.endBlock('</property>'); } }; /** * Add bean property with internal content. * * @param res Optional configuration presentation builder object. * @param bean Bean object for code generation. * @param beanPropName Name of property to set generated bean as value. * @param desc Bean metadata object. * @param createBeanAlthoughNoProps Always generate bean even it has no properties defined. */ $generatorSpring.beanProperty = function(res, bean, beanPropName, desc, createBeanAlthoughNoProps) { const props = desc.fields; if (bean && $generatorCommon.hasProperty(bean, props)) { if (!createBeanAlthoughNoProps) res.startSafeBlock(); res.emptyLineIfNeeded(); res.startBlock('<property name="' + beanPropName + '">'); if (createBeanAlthoughNoProps) res.startSafeBlock(); res.startBlock('<bean class="' + desc.className + '">'); let hasData = false; _.forIn(props, function(descr, propName) { if (props.hasOwnProperty(propName)) { if (descr) { switch (descr.type) { case 'list': $generatorSpring.listProperty(res, bean, propName, descr.setterName); break; case 'array': $generatorSpring.arrayProperty(res, bean, propName, descr); break; case 'propertiesAsList': const val = bean[propName]; if (val && val.length > 0) { res.startBlock('<property name="' + propName + '">'); res.startBlock('<props>'); _.forEach(val, function(nameAndValue) { const eqIndex = nameAndValue.indexOf('='); if (eqIndex >= 0) { res.line('<prop key="' + $generatorSpring.escape(nameAndValue.substring(0, eqIndex)) + '">' + $generatorSpring.escape(nameAndValue.substr(eqIndex + 1)) + '</prop>'); } }); res.endBlock('</props>'); res.endBlock('</property>'); hasData = true; } break; case 'bean': if ($generatorCommon.isDefinedAndNotEmpty(bean[propName])) { res.startBlock('<property name="' + propName + '">'); res.line('<bean class="' + bean[propName] + '"/>'); res.endBlock('</property>'); hasData = true; } break; default: if ($generatorSpring.property(res, bean, propName, descr.setterName, descr.dflt)) hasData = true; } } else if ($generatorSpring.property(res, bean, propName)) hasData = true; } }); res.endBlock('</bean>'); if (createBeanAlthoughNoProps && !hasData) { res.rollbackSafeBlock(); res.line('<bean class="' + desc.className + '"/>'); } res.endBlock('</property>'); if (!createBeanAlthoughNoProps && !hasData) res.rollbackSafeBlock(); } else if (createBeanAlthoughNoProps) { res.emptyLineIfNeeded(); res.startBlock('<property name="' + beanPropName + '">'); res.line('<bean class="' + desc.className + '"/>'); res.endBlock('</property>'); } }; /** * Add bean property without internal content. * * @param res Optional configuration presentation builder object. * @param obj Object to take bean class name. * @param propName Property name. */ $generatorSpring.simpleBeanProperty = function(res, obj, propName) { if (!_.isNil(obj)) { const val = obj[propName]; if ($generatorCommon.isDefinedAndNotEmpty(val)) { res.startBlock('<property name="' + propName + '">'); res.line('<bean class="' + val + '"/>'); res.endBlock('</property>'); } } return false; }; // Generate eviction policy. $generatorSpring.evictionPolicy = function(res, evtPlc, propName) { if (evtPlc && evtPlc.kind) { $generatorSpring.beanProperty(res, evtPlc[evtPlc.kind.toUpperCase()], propName, $generatorCommon.EVICTION_POLICIES[evtPlc.kind], true); } }; // Generate discovery. $generatorSpring.clusterGeneral = function(cluster, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cluster, 'name', 'gridName'); $generatorSpring.property(res, cluster, 'localHost'); if (cluster.discovery) { res.startBlock('<property name="discoverySpi">'); res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">'); res.startBlock('<property name="ipFinder">'); const d = cluster.discovery; switch (d.kind) { case 'Multicast': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">'); if (d.Multicast) { $generatorSpring.property(res, d.Multicast, 'multicastGroup'); $generatorSpring.property(res, d.Multicast, 'multicastPort'); $generatorSpring.property(res, d.Multicast, 'responseWaitTime'); $generatorSpring.property(res, d.Multicast, 'addressRequestAttempts'); $generatorSpring.property(res, d.Multicast, 'localAddress'); $generatorSpring.listProperty(res, d.Multicast, 'addresses'); } res.endBlock('</bean>'); break; case 'Vm': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">'); if (d.Vm) $generatorSpring.listProperty(res, d.Vm, 'addresses'); res.endBlock('</bean>'); break; case 'S3': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.s3.TcpDiscoveryS3IpFinder">'); if (d.S3) { if (d.S3.bucketName) res.line('<property name="bucketName" value="' + $generatorSpring.escape(d.S3.bucketName) + '"/>'); } res.endBlock('</bean>'); break; case 'Cloud': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.cloud.TcpDiscoveryCloudIpFinder">'); if (d.Cloud) { $generatorSpring.property(res, d.Cloud, 'credential'); $generatorSpring.property(res, d.Cloud, 'credentialPath'); $generatorSpring.property(res, d.Cloud, 'identity'); $generatorSpring.property(res, d.Cloud, 'provider'); $generatorSpring.listProperty(res, d.Cloud, 'regions'); $generatorSpring.listProperty(res, d.Cloud, 'zones'); } res.endBlock('</bean>'); break; case 'GoogleStorage': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.gce.TcpDiscoveryGoogleStorageIpFinder">'); if (d.GoogleStorage) { $generatorSpring.property(res, d.GoogleStorage, 'projectName'); $generatorSpring.property(res, d.GoogleStorage, 'bucketName'); $generatorSpring.property(res, d.GoogleStorage, 'serviceAccountP12FilePath'); $generatorSpring.property(res, d.GoogleStorage, 'serviceAccountId'); } res.endBlock('</bean>'); break; case 'Jdbc': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.jdbc.TcpDiscoveryJdbcIpFinder">'); if (d.Jdbc) { const datasource = d.Jdbc; res.line('<property name="initSchema" value="' + (!_.isNil(datasource.initSchema) && datasource.initSchema) + '"/>'); if (datasource.dataSourceBean && datasource.dialect) { res.line('<property name="dataSource" ref="' + datasource.dataSourceBean + '"/>'); if (!_.find(res.datasources, { dataSourceBean: datasource.dataSourceBean })) { res.datasources.push({ dataSourceBean: datasource.dataSourceBean, dialect: datasource.dialect }); } } } res.endBlock('</bean>'); break; case 'SharedFs': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.sharedfs.TcpDiscoverySharedFsIpFinder">'); if (d.SharedFs) $generatorSpring.property(res, d.SharedFs, 'path'); res.endBlock('</bean>'); break; case 'ZooKeeper': res.startBlock('<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.zk.TcpDiscoveryZookeeperIpFinder">'); if (d.ZooKeeper) { if ($generatorCommon.isDefinedAndNotEmpty(d.ZooKeeper.curator)) { res.startBlock('<property name="curator">'); res.line('<bean class="' + d.ZooKeeper.curator + '"/>'); res.endBlock('</property>'); } $generatorSpring.property(res, d.ZooKeeper, 'zkConnectionString'); if (d.ZooKeeper.retryPolicy && d.ZooKeeper.retryPolicy.kind) { const kind = d.ZooKeeper.retryPolicy.kind; const retryPolicy = d.ZooKeeper.retryPolicy[kind]; const customClassDefined = retryPolicy && $generatorCommon.isDefinedAndNotEmpty(retryPolicy.className); if (kind !== 'Custom' || customClassDefined) res.startBlock('<property name="retryPolicy">'); switch (kind) { case 'ExponentialBackoff': res.startBlock('<bean class="org.apache.curator.retry.ExponentialBackoffRetry">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'baseSleepTimeMs', 1000); $generatorSpring.constructorArg(res, 1, retryPolicy, 'maxRetries', 10); $generatorSpring.constructorArg(res, 2, retryPolicy, 'maxSleepMs', null, true); res.endBlock('</bean>'); break; case 'BoundedExponentialBackoff': res.startBlock('<bean class="org.apache.curator.retry.BoundedExponentialBackoffRetry">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'baseSleepTimeMs', 1000); $generatorSpring.constructorArg(res, 1, retryPolicy, 'maxSleepTimeMs', 2147483647); $generatorSpring.constructorArg(res, 2, retryPolicy, 'maxRetries', 10); res.endBlock('</bean>'); break; case 'UntilElapsed': res.startBlock('<bean class="org.apache.curator.retry.RetryUntilElapsed">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'maxElapsedTimeMs', 60000); $generatorSpring.constructorArg(res, 1, retryPolicy, 'sleepMsBetweenRetries', 1000); res.endBlock('</bean>'); break; case 'NTimes': res.startBlock('<bean class="org.apache.curator.retry.RetryNTimes">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'n', 10); $generatorSpring.constructorArg(res, 1, retryPolicy, 'sleepMsBetweenRetries', 1000); res.endBlock('</bean>'); break; case 'OneTime': res.startBlock('<bean class="org.apache.curator.retry.RetryOneTime">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'sleepMsBetweenRetry', 1000); res.endBlock('</bean>'); break; case 'Forever': res.startBlock('<bean class="org.apache.curator.retry.RetryForever">'); $generatorSpring.constructorArg(res, 0, retryPolicy, 'retryIntervalMs', 1000); res.endBlock('</bean>'); break; case 'Custom': if (customClassDefined) res.line('<bean class="' + retryPolicy.className + '"/>'); break; default: } if (kind !== 'Custom' || customClassDefined) res.endBlock('</property>'); } $generatorSpring.property(res, d.ZooKeeper, 'basePath', null, '/services'); $generatorSpring.property(res, d.ZooKeeper, 'serviceName', null, 'ignite'); $generatorSpring.property(res, d.ZooKeeper, 'allowDuplicateRegistrations', null, false); } res.endBlock('</bean>'); break; default: res.line('Unknown discovery kind: ' + d.kind); } res.endBlock('</property>'); $generatorSpring.clusterDiscovery(d, res); res.endBlock('</bean>'); res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate atomics group. $generatorSpring.clusterAtomics = function(atomics, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.hasAtLeastOneProperty(atomics, ['cacheMode', 'atomicSequenceReserveSize', 'backups'])) { res.startSafeBlock(); res.emptyLineIfNeeded(); res.startBlock('<property name="atomicConfiguration">'); res.startBlock('<bean class="org.apache.ignite.configuration.AtomicConfiguration">'); const cacheMode = atomics.cacheMode ? atomics.cacheMode : 'PARTITIONED'; let hasData = cacheMode !== 'PARTITIONED'; $generatorSpring.property(res, atomics, 'cacheMode', null, 'PARTITIONED'); hasData = $generatorSpring.property(res, atomics, 'atomicSequenceReserveSize', null, 1000) || hasData; if (cacheMode === 'PARTITIONED') hasData = $generatorSpring.property(res, atomics, 'backups', null, 0) || hasData; res.endBlock('</bean>'); res.endBlock('</property>'); res.needEmptyLine = true; if (!hasData) res.rollbackSafeBlock(); } return res; }; // Generate binary group. $generatorSpring.clusterBinary = function(binary, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.binaryIsDefined(binary)) { res.startBlock('<property name="binaryConfiguration">'); res.startBlock('<bean class="org.apache.ignite.configuration.BinaryConfiguration">'); $generatorSpring.simpleBeanProperty(res, binary, 'idMapper'); $generatorSpring.simpleBeanProperty(res, binary, 'nameMapper'); $generatorSpring.simpleBeanProperty(res, binary, 'serializer'); if ($generatorCommon.isDefinedAndNotEmpty(binary.typeConfigurations)) { res.startBlock('<property name="typeConfigurations">'); res.startBlock('<list>'); _.forEach(binary.typeConfigurations, function(type) { res.startBlock('<bean class="org.apache.ignite.binary.BinaryTypeConfiguration">'); $generatorSpring.property(res, type, 'typeName'); $generatorSpring.simpleBeanProperty(res, type, 'idMapper'); $generatorSpring.simpleBeanProperty(res, type, 'nameMapper'); $generatorSpring.simpleBeanProperty(res, type, 'serializer'); $generatorSpring.property(res, type, 'enum', null, false); res.endBlock('</bean>'); }); res.endBlock('</list>'); res.endBlock('</property>'); } $generatorSpring.property(res, binary, 'compactFooter', null, true); res.endBlock('</bean>'); res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate cache key configurations. $generatorSpring.clusterCacheKeyConfiguration = function(keyCfgs, res) { if (!res) res = $generatorCommon.builder(); keyCfgs = _.filter(keyCfgs, (cfg) => cfg.typeName && cfg.affinityKeyFieldName); if (_.isEmpty(keyCfgs)) return res; res.startBlock('<property name="cacheKeyConfiguration">'); res.startBlock('<array>'); _.forEach(keyCfgs, (cfg) => { res.startBlock('<bean class="org.apache.ignite.cache.CacheKeyConfiguration">'); $generatorSpring.constructorArg(res, -1, cfg, 'typeName'); $generatorSpring.constructorArg(res, -1, cfg, 'affinityKeyFieldName'); res.endBlock('</bean>'); }); res.endBlock('</array>'); res.endBlock('</property>'); return res; }; // Generate collision group. $generatorSpring.clusterCollision = function(collision, res) { if (!res) res = $generatorCommon.builder(); if (collision && collision.kind && collision.kind !== 'Noop') { const spi = collision[collision.kind]; if (collision.kind !== 'Custom' || (spi && $generatorCommon.isDefinedAndNotEmpty(spi.class))) { res.startBlock('<property name="collisionSpi">'); switch (collision.kind) { case 'JobStealing': res.startBlock('<bean class="org.apache.ignite.spi.collision.jobstealing.JobStealingCollisionSpi">'); $generatorSpring.property(res, spi, 'activeJobsThreshold', null, 95); $generatorSpring.property(res, spi, 'waitJobsThreshold', null, 0); $generatorSpring.property(res, spi, 'messageExpireTime', null, 1000); $generatorSpring.property(res, spi, 'maximumStealingAttempts', null, 5); $generatorSpring.property(res, spi, 'stealingEnabled', null, true); if ($generatorCommon.isDefinedAndNotEmpty(spi.externalCollisionListener)) { res.needEmptyLine = true; res.startBlock('<property name="externalCollisionListener">'); res.line('<bean class="' + spi.externalCollisionListener + ' "/>'); res.endBlock('</property>'); } if ($generatorCommon.isDefinedAndNotEmpty(spi.stealingAttributes)) { res.needEmptyLine = true; res.startBlock('<property name="stealingAttributes">'); res.startBlock('<map>'); _.forEach(spi.stealingAttributes, function(attr) { $generatorSpring.element(res, 'entry', 'key', attr.name, 'value', attr.value); }); res.endBlock('</map>'); res.endBlock('</property>'); } res.endBlock('</bean>'); break; case 'FifoQueue': res.startBlock('<bean class="org.apache.ignite.spi.collision.fifoqueue.FifoQueueCollisionSpi">'); $generatorSpring.property(res, spi, 'parallelJobsNumber'); $generatorSpring.property(res, spi, 'waitingJobsNumber'); res.endBlock('</bean>'); break; case 'PriorityQueue': res.startBlock('<bean class="org.apache.ignite.spi.collision.priorityqueue.PriorityQueueCollisionSpi">'); $generatorSpring.property(res, spi, 'parallelJobsNumber'); $generatorSpring.property(res, spi, 'waitingJobsNumber'); $generatorSpring.property(res, spi, 'priorityAttributeKey', null, 'grid.task.priority'); $generatorSpring.property(res, spi, 'jobPriorityAttributeKey', null, 'grid.job.priority'); $generatorSpring.property(res, spi, 'defaultPriority', null, 0); $generatorSpring.property(res, spi, 'starvationIncrement', null, 1); $generatorSpring.property(res, spi, 'starvationPreventionEnabled', null, true); res.endBlock('</bean>'); break; case 'Custom': res.line('<bean class="' + spi.class + '"/>'); break; default: } res.endBlock('</property>'); } } return res; }; // Generate communication group. $generatorSpring.clusterCommunication = function(cluster, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.beanProperty(res, cluster.communication, 'communicationSpi', $generatorCommon.COMMUNICATION_CONFIGURATION); $generatorSpring.property(res, cluster, 'networkTimeout', null, 5000); $generatorSpring.property(res, cluster, 'networkSendRetryDelay', null, 1000); $generatorSpring.property(res, cluster, 'networkSendRetryCount', null, 3); $generatorSpring.property(res, cluster, 'segmentCheckFrequency'); $generatorSpring.property(res, cluster, 'waitForSegmentOnStart', null, false); $generatorSpring.property(res, cluster, 'discoveryStartupDelay', null, 60000); res.needEmptyLine = true; return res; }; /** * XML generator for cluster's REST access configuration. * * @param connector Cluster REST connector configuration. * @param res Optional configuration presentation builder object. * @returns Configuration presentation builder object */ $generatorSpring.clusterConnector = function(connector, res) { if (!res) res = $generatorCommon.builder(); if (!_.isNil(connector) && connector.enabled) { const cfg = _.cloneDeep($generatorCommon.CONNECTOR_CONFIGURATION); if (connector.sslEnabled) { cfg.fields.sslClientAuth = {dflt: false}; cfg.fields.sslFactory = {type: 'bean'}; } $generatorSpring.beanProperty(res, connector, 'connectorConfiguration', cfg, true); res.needEmptyLine = true; } return res; }; // Generate deployment group. $generatorSpring.clusterDeployment = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if ($generatorSpring.property(res, cluster, 'deploymentMode', null, 'SHARED')) res.needEmptyLine = true; const p2pEnabled = cluster.peerClassLoadingEnabled; if (!_.isNil(p2pEnabled)) { $generatorSpring.property(res, cluster, 'peerClassLoadingEnabled', null, false); if (p2pEnabled) { $generatorSpring.property(res, cluster, 'peerClassLoadingMissedResourcesCacheSize', null, 100); $generatorSpring.property(res, cluster, 'peerClassLoadingThreadPoolSize', null, 2); $generatorSpring.listProperty(res, cluster, 'peerClassLoadingLocalClassPathExclude'); } res.needEmptyLine = true; } return res; }; // Generate discovery group. $generatorSpring.clusterDiscovery = function(disco, res) { if (!res) res = $generatorCommon.builder(); if (disco) { $generatorSpring.property(res, disco, 'localAddress'); $generatorSpring.property(res, disco, 'localPort', null, 47500); $generatorSpring.property(res, disco, 'localPortRange', null, 100); if ($generatorCommon.isDefinedAndNotEmpty(disco.addressResolver)) $generatorSpring.beanProperty(res, disco, 'addressResolver', {className: disco.addressResolver}, true); $generatorSpring.property(res, disco, 'socketTimeout', null, 5000); $generatorSpring.property(res, disco, 'ackTimeout', null, 5000); $generatorSpring.property(res, disco, 'maxAckTimeout', null, 600000); $generatorSpring.property(res, disco, 'networkTimeout', null, 5000); $generatorSpring.property(res, disco, 'joinTimeout', null, 0); $generatorSpring.property(res, disco, 'threadPriority', null, 10); $generatorSpring.property(res, disco, 'heartbeatFrequency', null, 2000); $generatorSpring.property(res, disco, 'maxMissedHeartbeats', null, 1); $generatorSpring.property(res, disco, 'maxMissedClientHeartbeats', null, 5); $generatorSpring.property(res, disco, 'topHistorySize', null, 1000); if ($generatorCommon.isDefinedAndNotEmpty(disco.listener)) $generatorSpring.beanProperty(res, disco, 'listener', {className: disco.listener}, true); if ($generatorCommon.isDefinedAndNotEmpty(disco.dataExchange)) $generatorSpring.beanProperty(res, disco, 'dataExchange', {className: disco.dataExchange}, true); if ($generatorCommon.isDefinedAndNotEmpty(disco.metricsProvider)) $generatorSpring.beanProperty(res, disco, 'metricsProvider', {className: disco.metricsProvider}, true); $generatorSpring.property(res, disco, 'reconnectCount', null, 10); $generatorSpring.property(res, disco, 'statisticsPrintFrequency', null, 0); $generatorSpring.property(res, disco, 'ipFinderCleanFrequency', null, 60000); if ($generatorCommon.isDefinedAndNotEmpty(disco.authenticator)) $generatorSpring.beanProperty(res, disco, 'authenticator', {className: disco.authenticator}, true); $generatorSpring.property(res, disco, 'forceServerMode', null, false); $generatorSpring.property(res, disco, 'clientReconnectDisabled', null, false); res.needEmptyLine = true; } return res; }; // Generate events group. $generatorSpring.clusterEvents = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if (cluster.includeEventTypes && cluster.includeEventTypes.length > 0) { res.emptyLineIfNeeded(); res.startBlock('<property name="includeEventTypes">'); const evtGrps = angular.element(document.getElementById('app')).injector().get('igniteEventGroups'); if (cluster.includeEventTypes.length === 1) { const evtGrp = _.find(evtGrps, {value: cluster.includeEventTypes[0]}); if (evtGrp) res.line('<util:constant static-field="' + evtGrp.class + '.' + evtGrp.value + '"/>'); } else { res.startBlock('<list>'); _.forEach(cluster.includeEventTypes, (item, ix) => { ix > 0 && res.line(); const evtGrp = _.find(evtGrps, {value: item}); if (evtGrp) { res.line('<!-- EventType.' + item + ' -->'); _.forEach(evtGrp.events, (event) => res.line('<util:constant static-field="' + evtGrp.class + '.' + event + '"/>')); } }); res.endBlock('</list>'); } res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate failover group. $generatorSpring.clusterFailover = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.isDefinedAndNotEmpty(cluster.failoverSpi) && _.findIndex(cluster.failoverSpi, function(spi) { return $generatorCommon.isDefinedAndNotEmpty(spi.kind) && (spi.kind !== 'Custom' || $generatorCommon.isDefinedAndNotEmpty(_.get(spi, spi.kind + '.class'))); }) >= 0) { res.startBlock('<property name="failoverSpi">'); res.startBlock('<list>'); _.forEach(cluster.failoverSpi, function(spi) { if (spi.kind && (spi.kind !== 'Custom' || $generatorCommon.isDefinedAndNotEmpty(_.get(spi, spi.kind + '.class')))) { const maxAttempts = _.get(spi, spi.kind + '.maximumFailoverAttempts'); if ((spi.kind === 'JobStealing' || spi.kind === 'Always') && $generatorCommon.isDefinedAndNotEmpty(maxAttempts) && maxAttempts !== 5) { res.startBlock('<bean class="' + $generatorCommon.failoverSpiClass(spi) + '">'); $generatorSpring.property(res, spi[spi.kind], 'maximumFailoverAttempts', null, 5); res.endBlock('</bean>'); } else res.line('<bean class="' + $generatorCommon.failoverSpiClass(spi) + '"/>'); res.needEmptyLine = true; } }); res.needEmptyLine = true; res.endBlock('</list>'); res.endBlock('</property>'); } return res; }; // Generate marshaller group. $generatorSpring.clusterLogger = function(logger, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.loggerConfigured(logger)) { res.startBlock('<property name="gridLogger">'); const log = logger[logger.kind]; switch (logger.kind) { case 'Log4j2': res.startBlock('<bean class="org.apache.ignite.logger.log4j2.Log4J2Logger">'); res.line('<constructor-arg value="' + $generatorSpring.escape(log.path) + '"/>'); $generatorSpring.property(res, log, 'level'); res.endBlock('</bean>'); break; case 'Null': res.line('<bean class="org.apache.ignite.logger.NullLogger"/>'); break; case 'Java': res.line('<bean class="org.apache.ignite.logger.java.JavaLogger"/>'); break; case 'JCL': res.line('<bean class="org.apache.ignite.logger.jcl.JclLogger"/>'); break; case 'SLF4J': res.line('<bean class="org.apache.ignite.logger.slf4j.Slf4jLogger"/>'); break; case 'Log4j': if (log.mode === 'Default' && !$generatorCommon.isDefinedAndNotEmpty(log.level)) res.line('<bean class="org.apache.ignite.logger.log4j.Log4JLogger"/>'); else { res.startBlock('<bean class="org.apache.ignite.logger.log4j.Log4JLogger">'); if (log.mode === 'Path') res.line('<constructor-arg value="' + $generatorSpring.escape(log.path) + '"/>'); $generatorSpring.property(res, log, 'level'); res.endBlock('</bean>'); } break; case 'Custom': res.line('<bean class="' + log.class + '"/>'); break; default: } res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate marshaller group. $generatorSpring.clusterMarshaller = function(cluster, res) { if (!res) res = $generatorCommon.builder(); const marshaller = cluster.marshaller; if (marshaller && marshaller.kind) $generatorSpring.beanProperty(res, marshaller[marshaller.kind], 'marshaller', $generatorCommon.MARSHALLERS[marshaller.kind], true); res.softEmptyLine(); $generatorSpring.property(res, cluster, 'marshalLocalJobs', null, false); $generatorSpring.property(res, cluster, 'marshallerCacheKeepAliveTime', null, 10000); $generatorSpring.property(res, cluster, 'marshallerCacheThreadPoolSize', 'marshallerCachePoolSize'); res.needEmptyLine = true; return res; }; // Generate metrics group. $generatorSpring.clusterMetrics = function(cluster, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cluster, 'metricsExpireTime'); $generatorSpring.property(res, cluster, 'metricsHistorySize', null, 10000); $generatorSpring.property(res, cluster, 'metricsLogFrequency', null, 60000); $generatorSpring.property(res, cluster, 'metricsUpdateFrequency', null, 2000); res.needEmptyLine = true; return res; }; // Generate swap group. $generatorSpring.clusterSwap = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if (cluster.swapSpaceSpi && cluster.swapSpaceSpi.kind === 'FileSwapSpaceSpi') { $generatorSpring.beanProperty(res, cluster.swapSpaceSpi.FileSwapSpaceSpi, 'swapSpaceSpi', $generatorCommon.SWAP_SPACE_SPI, true); res.needEmptyLine = true; } return res; }; // Generate time group. $generatorSpring.clusterTime = function(cluster, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cluster, 'clockSyncSamples', null, 8); $generatorSpring.property(res, cluster, 'clockSyncFrequency', null, 120000); $generatorSpring.property(res, cluster, 'timeServerPortBase', null, 31100); $generatorSpring.property(res, cluster, 'timeServerPortRange', null, 100); res.needEmptyLine = true; return res; }; // Generate OBC configuration group. $generatorSpring.clusterODBC = function(odbc, res) { if (!res) res = $generatorCommon.builder(); if (odbc && odbc.odbcEnabled) $generatorSpring.beanProperty(res, odbc, 'odbcConfiguration', $generatorCommon.ODBC_CONFIGURATION, true); res.needEmptyLine = true; return res; }; // Generate thread pools group. $generatorSpring.clusterPools = function(cluster, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cluster, 'publicThreadPoolSize'); $generatorSpring.property(res, cluster, 'systemThreadPoolSize'); $generatorSpring.property(res, cluster, 'managementThreadPoolSize'); $generatorSpring.property(res, cluster, 'igfsThreadPoolSize'); $generatorSpring.property(res, cluster, 'rebalanceThreadPoolSize'); res.needEmptyLine = true; return res; }; // Generate transactions group. $generatorSpring.clusterTransactions = function(transactionConfiguration, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.beanProperty(res, transactionConfiguration, 'transactionConfiguration', $generatorCommon.TRANSACTION_CONFIGURATION, false); res.needEmptyLine = true; return res; }; // Generate user attributes group. $generatorSpring.clusterUserAttributes = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.isDefinedAndNotEmpty(cluster.attributes)) { res.startBlock('<property name="userAttributes">'); res.startBlock('<map>'); _.forEach(cluster.attributes, function(attr) { $generatorSpring.element(res, 'entry', 'key', attr.name, 'value', attr.value); }); res.endBlock('</map>'); res.endBlock('</property>'); } res.needEmptyLine = true; return res; }; /** * XML generator for cluster's SSL configuration. * * @param cluster Cluster to get SSL configuration. * @param res Optional configuration presentation builder object. * @returns Configuration presentation builder object */ $generatorSpring.clusterSsl = function(cluster, res) { if (!res) res = $generatorCommon.builder(); if (cluster.sslEnabled && !_.isNil(cluster.sslContextFactory)) { let sslFactory; if (_.isEmpty(cluster.sslContextFactory.keyStoreFilePath) && _.isEmpty(cluster.sslContextFactory.trustStoreFilePath)) sslFactory = cluster.sslContextFactory; else { sslFactory = _.clone(cluster.sslContextFactory); sslFactory.keyStorePassword = _.isEmpty(cluster.sslContextFactory.keyStoreFilePath) ? null : '${ssl.key.storage.password}'; sslFactory.trustStorePassword = _.isEmpty(cluster.sslContextFactory.trustStoreFilePath) ? null : '${ssl.trust.storage.password}'; } const propsDesc = $generatorCommon.isDefinedAndNotEmpty(cluster.sslContextFactory.trustManagers) ? $generatorCommon.SSL_CONFIGURATION_TRUST_MANAGER_FACTORY : $generatorCommon.SSL_CONFIGURATION_TRUST_FILE_FACTORY; $generatorSpring.beanProperty(res, sslFactory, 'sslContextFactory', propsDesc, true); res.needEmptyLine = true; } return res; }; // Generate cache general group. $generatorSpring.cacheGeneral = function(cache, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cache, 'name'); $generatorSpring.property(res, cache, 'cacheMode'); $generatorSpring.property(res, cache, 'atomicityMode'); if (cache.cacheMode === 'PARTITIONED' && $generatorSpring.property(res, cache, 'backups')) $generatorSpring.property(res, cache, 'readFromBackup'); $generatorSpring.property(res, cache, 'copyOnRead'); if (cache.cacheMode === 'PARTITIONED' && cache.atomicityMode === 'TRANSACTIONAL') $generatorSpring.property(res, cache, 'invalidate'); res.needEmptyLine = true; return res; }; // Generate cache memory group. $generatorSpring.cacheMemory = function(cache, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cache, 'memoryMode', null, 'ONHEAP_TIERED'); if (cache.memoryMode !== 'OFFHEAP_VALUES') $generatorSpring.property(res, cache, 'offHeapMaxMemory', null, -1); res.softEmptyLine(); $generatorSpring.evictionPolicy(res, cache.evictionPolicy, 'evictionPolicy'); res.softEmptyLine(); $generatorSpring.property(res, cache, 'startSize', null, 1500000); $generatorSpring.property(res, cache, 'swapEnabled', null, false); res.needEmptyLine = true; return res; }; // Generate cache query & indexing group. $generatorSpring.cacheQuery = function(cache, domains, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cache, 'sqlSchema'); $generatorSpring.property(res, cache, 'sqlOnheapRowCacheSize', null, 10240); $generatorSpring.property(res, cache, 'longQueryWarningTimeout', null, 3000); const indexedTypes = _.filter(domains, (domain) => domain.queryMetadata === 'Annotations'); if (indexedTypes.length > 0) { res.softEmptyLine(); res.startBlock('<property name="indexedTypes">'); res.startBlock('<list>'); _.forEach(indexedTypes, function(domain) { res.line('<value>' + $generatorCommon.JavaTypes.fullClassName(domain.keyType) + '</value>'); res.line('<value>' + $generatorCommon.JavaTypes.fullClassName(domain.valueType) + '</value>'); }); res.endBlock('</list>'); res.endBlock('</property>'); } res.softEmptyLine(); $generatorSpring.listProperty(res, cache, 'sqlFunctionClasses'); res.softEmptyLine(); $generatorSpring.property(res, cache, 'snapshotableIndex', null, false); $generatorSpring.property(res, cache, 'sqlEscapeAll', null, false); res.needEmptyLine = true; return res; }; // Generate cache store group. $generatorSpring.cacheStore = function(cache, domains, res) { if (!res) res = $generatorCommon.builder(); if (cache.cacheStoreFactory && cache.cacheStoreFactory.kind) { const factoryKind = cache.cacheStoreFactory.kind; const storeFactory = cache.cacheStoreFactory[factoryKind]; if (storeFactory) { if (factoryKind === 'CacheJdbcPojoStoreFactory') { res.startBlock('<property name="cacheStoreFactory">'); res.startBlock('<bean class="org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreFactory">'); $generatorSpring.property(res, storeFactory, 'dataSourceBean'); res.startBlock('<property name="dialect">'); res.line('<bean class="' + $generatorCommon.jdbcDialectClassName(storeFactory.dialect) + '"/>'); res.endBlock('</property>'); if (storeFactory.sqlEscapeAll) $generatorSpring.property(res, storeFactory, 'sqlEscapeAll'); const domainConfigs = _.filter(domains, function(domain) { return $generatorCommon.isDefinedAndNotEmpty(domain.databaseTable); }); if ($generatorCommon.isDefinedAndNotEmpty(domainConfigs)) { res.startBlock('<property name="types">'); res.startBlock('<list>'); _.forEach(domainConfigs, function(domain) { res.startBlock('<bean class="org.apache.ignite.cache.store.jdbc.JdbcType">'); $generatorSpring.property(res, cache, 'name', 'cacheName'); $generatorSpring.classNameProperty(res, domain, 'keyType'); $generatorSpring.property(res, domain, 'valueType'); $generatorSpring.domainStore(domain, res); res.endBlock('</bean>'); }); res.endBlock('</list>'); res.endBlock('</property>'); } res.endBlock('</bean>'); res.endBlock('</property>'); } else if (factoryKind === 'CacheJdbcBlobStoreFactory') { res.startBlock('<property name="cacheStoreFactory">'); res.startBlock('<bean class="org.apache.ignite.cache.store.jdbc.CacheJdbcBlobStoreFactory">'); if (storeFactory.connectVia === 'DataSource') $generatorSpring.property(res, storeFactory, 'dataSourceBean'); else { $generatorSpring.property(res, storeFactory, 'connectionUrl'); $generatorSpring.property(res, storeFactory, 'user'); res.line('<property name="password" value="${ds.' + storeFactory.user + '.password}"/>'); } $generatorSpring.property(res, storeFactory, 'initSchema'); $generatorSpring.property(res, storeFactory, 'createTableQuery'); $generatorSpring.property(res, storeFactory, 'loadQuery'); $generatorSpring.property(res, storeFactory, 'insertQuery'); $generatorSpring.property(res, storeFactory, 'updateQuery'); $generatorSpring.property(res, storeFactory, 'deleteQuery'); res.endBlock('</bean>'); res.endBlock('</property>'); } else $generatorSpring.beanProperty(res, storeFactory, 'cacheStoreFactory', $generatorCommon.STORE_FACTORIES[factoryKind], true); if (storeFactory.dataSourceBean && (storeFactory.connectVia ? (storeFactory.connectVia === 'DataSource' ? storeFactory.dialect : null) : storeFactory.dialect)) { if (!_.find(res.datasources, { dataSourceBean: storeFactory.dataSourceBean})) { res.datasources.push({ dataSourceBean: storeFactory.dataSourceBean, dialect: storeFactory.dialect }); } } } } res.softEmptyLine(); $generatorSpring.property(res, cache, 'storeKeepBinary', null, false); $generatorSpring.property(res, cache, 'loadPreviousValue', null, false); $generatorSpring.property(res, cache, 'readThrough', null, false); $generatorSpring.property(res, cache, 'writeThrough', null, false); res.softEmptyLine(); if (cache.writeBehindEnabled) { $generatorSpring.property(res, cache, 'writeBehindEnabled', null, false); $generatorSpring.property(res, cache, 'writeBehindBatchSize', null, 512); $generatorSpring.property(res, cache, 'writeBehindFlushSize', null, 10240); $generatorSpring.property(res, cache, 'writeBehindFlushFrequency', null, 5000); $generatorSpring.property(res, cache, 'writeBehindFlushThreadCount', null, 1); } res.needEmptyLine = true; return res; }; // Generate cache node filter group. $generatorSpring.cacheNodeFilter = function(cache, igfss, res) { if (!res) res = $generatorCommon.builder(); const kind = _.get(cache, 'nodeFilter.kind'); if (_.isNil(kind) || _.isNil(cache.nodeFilter[kind])) return res; switch (kind) { case 'IGFS': const foundIgfs = _.find(igfss, (igfs) => igfs._id === cache.nodeFilter.IGFS.igfs); if (foundIgfs) { res.startBlock('<property name="nodeFilter">'); res.startBlock('<bean class="org.apache.ignite.internal.processors.igfs.IgfsNodePredicate">'); res.line('<constructor-arg value="' + foundIgfs.name + '"/>'); res.endBlock('</bean>'); res.endBlock('</property>'); } break; case 'OnNodes': const nodes = cache.nodeFilter.OnNodes.nodeIds; if ($generatorCommon.isDefinedAndNotEmpty(nodes)) { res.startBlock('<property name="nodeFilter">'); res.startBlock('<bean class="org.apache.ignite.internal.util.lang.GridNodePredicate">'); res.startBlock('<constructor-arg>'); res.startBlock('<list>'); _.forEach(nodes, (nodeId) => { res.startBlock('<bean class="java.util.UUID" factory-method="fromString">'); res.line('<constructor-arg value="' + nodeId + '"/>'); res.endBlock('</bean>'); }); res.endBlock('</list>'); res.endBlock('</constructor-arg>'); res.endBlock('</bean>'); res.endBlock('</property>'); } break; case 'Custom': res.startBlock('<property name="nodeFilter">'); res.line('<bean class="' + cache.nodeFilter.Custom.className + '"/>'); res.endBlock('</property>'); break; default: break; } res.needEmptyLine = true; return res; }; // Generate cache concurrency group. $generatorSpring.cacheConcurrency = function(cache, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cache, 'maxConcurrentAsyncOperations', null, 500); $generatorSpring.property(res, cache, 'defaultLockTimeout', null, 0); $generatorSpring.property(res, cache, 'atomicWriteOrderMode'); $generatorSpring.property(res, cache, 'writeSynchronizationMode', null, 'PRIMARY_SYNC'); res.needEmptyLine = true; return res; }; // Generate cache rebalance group. $generatorSpring.cacheRebalance = function(cache, res) { if (!res) res = $generatorCommon.builder(); if (cache.cacheMode !== 'LOCAL') { $generatorSpring.property(res, cache, 'rebalanceMode', null, 'ASYNC'); $generatorSpring.property(res, cache, 'rebalanceThreadPoolSize', null, 1); $generatorSpring.property(res, cache, 'rebalanceBatchSize', null, 524288); $generatorSpring.property(res, cache, 'rebalanceBatchesPrefetchCount', null, 2); $generatorSpring.property(res, cache, 'rebalanceOrder', null, 0); $generatorSpring.property(res, cache, 'rebalanceDelay', null, 0); $generatorSpring.property(res, cache, 'rebalanceTimeout', null, 10000); $generatorSpring.property(res, cache, 'rebalanceThrottle', null, 0); } res.softEmptyLine(); if (cache.igfsAffinnityGroupSize) { res.startBlock('<property name="affinityMapper">'); res.startBlock('<bean class="org.apache.ignite.igfs.IgfsGroupDataBlocksKeyMapper">'); $generatorSpring.constructorArg(res, -1, cache, 'igfsAffinnityGroupSize'); res.endBlock('</bean>'); res.endBlock('</property>'); } return res; }; // Generate cache server near cache group. $generatorSpring.cacheServerNearCache = function(cache, res) { if (!res) res = $generatorCommon.builder(); if (cache.cacheMode === 'PARTITIONED' && cache.nearCacheEnabled) { res.emptyLineIfNeeded(); res.startBlock('<property name="nearConfiguration">'); res.startBlock('<bean class="org.apache.ignite.configuration.NearCacheConfiguration">'); if (cache.nearConfiguration) { if (cache.nearConfiguration.nearStartSize) $generatorSpring.property(res, cache.nearConfiguration, 'nearStartSize', null, 375000); $generatorSpring.evictionPolicy(res, cache.nearConfiguration.nearEvictionPolicy, 'nearEvictionPolicy'); } res.endBlock('</bean>'); res.endBlock('</property>'); } res.needEmptyLine = true; return res; }; // Generate cache statistics group. $generatorSpring.cacheStatistics = function(cache, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, cache, 'statisticsEnabled', null, false); $generatorSpring.property(res, cache, 'managementEnabled', null, false); res.needEmptyLine = true; return res; }; // Generate domain model query fields. $generatorSpring.domainModelQueryFields = function(res, domain) { const fields = domain.fields; if (fields && fields.length > 0) { res.emptyLineIfNeeded(); res.startBlock('<property name="fields">'); res.startBlock('<map>'); _.forEach(fields, function(field) { $generatorSpring.element(res, 'entry', 'key', field.name, 'value', $generatorCommon.JavaTypes.fullClassName(field.className)); }); res.endBlock('</map>'); res.endBlock('</property>'); res.needEmptyLine = true; } }; // Generate domain model query fields. $generatorSpring.domainModelQueryAliases = function(res, domain) { const aliases = domain.aliases; if (aliases && aliases.length > 0) { res.emptyLineIfNeeded(); res.startBlock('<property name="aliases">'); res.startBlock('<map>'); _.forEach(aliases, function(alias) { $generatorSpring.element(res, 'entry', 'key', alias.field, 'value', alias.alias); }); res.endBlock('</map>'); res.endBlock('</property>'); res.needEmptyLine = true; } }; // Generate domain model indexes. $generatorSpring.domainModelQueryIndexes = function(res, domain) { const indexes = domain.indexes; if (indexes && indexes.length > 0) { res.emptyLineIfNeeded(); res.startBlock('<property name="indexes">'); res.startBlock('<list>'); _.forEach(indexes, function(index) { res.startBlock('<bean class="org.apache.ignite.cache.QueryIndex">'); $generatorSpring.property(res, index, 'name'); $generatorSpring.property(res, index, 'indexType'); const fields = index.fields; if (fields && fields.length > 0) { res.startBlock('<property name="fields">'); res.startBlock('<map>'); _.forEach(fields, function(field) { $generatorSpring.element(res, 'entry', 'key', field.name, 'value', field.direction); }); res.endBlock('</map>'); res.endBlock('</property>'); } res.endBlock('</bean>'); }); res.endBlock('</list>'); res.endBlock('</property>'); res.needEmptyLine = true; } }; // Generate domain model db fields. $generatorSpring.domainModelDatabaseFields = function(res, domain, fieldProp) { const fields = domain[fieldProp]; if (fields && fields.length > 0) { res.emptyLineIfNeeded(); res.startBlock('<property name="' + fieldProp + '">'); res.startBlock('<list>'); _.forEach(fields, function(field) { res.startBlock('<bean class="org.apache.ignite.cache.store.jdbc.JdbcTypeField">'); $generatorSpring.property(res, field, 'databaseFieldName'); res.startBlock('<property name="databaseFieldType">'); res.line('<util:constant static-field="java.sql.Types.' + field.databaseFieldType + '"/>'); res.endBlock('</property>'); $generatorSpring.property(res, field, 'javaFieldName'); $generatorSpring.classNameProperty(res, field, 'javaFieldType'); res.endBlock('</bean>'); }); res.endBlock('</list>'); res.endBlock('</property>'); res.needEmptyLine = true; } }; // Generate domain model general group. $generatorSpring.domainModelGeneral = function(domain, res) { if (!res) res = $generatorCommon.builder(); switch ($generatorCommon.domainQueryMetadata(domain)) { case 'Annotations': if ($generatorCommon.isDefinedAndNotEmpty(domain.keyType) || $generatorCommon.isDefinedAndNotEmpty(domain.valueType)) { res.startBlock('<property name="indexedTypes">'); res.startBlock('<list>'); if ($generatorCommon.isDefinedAndNotEmpty(domain.keyType)) res.line('<value>' + $generatorCommon.JavaTypes.fullClassName(domain.keyType) + '</value>'); else res.line('<value>???</value>'); if ($generatorCommon.isDefinedAndNotEmpty(domain.valueType)) res.line('<value>' + $generatorCommon.JavaTypes.fullClassName(domain.valueType) + '</value>'); else res.line('<value>>???</value>'); res.endBlock('</list>'); res.endBlock('</property>'); } break; case 'Configuration': $generatorSpring.classNameProperty(res, domain, 'keyType'); $generatorSpring.property(res, domain, 'valueType'); break; default: } res.needEmptyLine = true; return res; }; // Generate domain model for query group. $generatorSpring.domainModelQuery = function(domain, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.domainQueryMetadata(domain) === 'Configuration') { $generatorSpring.domainModelQueryFields(res, domain); $generatorSpring.domainModelQueryAliases(res, domain); $generatorSpring.domainModelQueryIndexes(res, domain); res.needEmptyLine = true; } return res; }; // Generate domain model for store group. $generatorSpring.domainStore = function(domain, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, domain, 'databaseSchema'); $generatorSpring.property(res, domain, 'databaseTable'); res.softEmptyLine(); $generatorSpring.domainModelDatabaseFields(res, domain, 'keyFields'); $generatorSpring.domainModelDatabaseFields(res, domain, 'valueFields'); res.needEmptyLine = true; return res; }; $generatorSpring.cacheQueryMetadata = function(domain, res) { if (!res) res = $generatorCommon.builder(); res.startBlock('<bean class="org.apache.ignite.cache.QueryEntity">'); $generatorSpring.classNameProperty(res, domain, 'keyType'); $generatorSpring.property(res, domain, 'valueType'); $generatorSpring.domainModelQuery(domain, res); res.endBlock('</bean>'); res.needEmptyLine = true; return res; }; // Generate domain models configs. $generatorSpring.cacheDomains = function(domains, res) { if (!res) res = $generatorCommon.builder(); const domainConfigs = _.filter(domains, function(domain) { return $generatorCommon.domainQueryMetadata(domain) === 'Configuration' && $generatorCommon.isDefinedAndNotEmpty(domain.fields); }); if ($generatorCommon.isDefinedAndNotEmpty(domainConfigs)) { res.emptyLineIfNeeded(); res.startBlock('<property name="queryEntities">'); res.startBlock('<list>'); _.forEach(domainConfigs, function(domain) { $generatorSpring.cacheQueryMetadata(domain, res); }); res.endBlock('</list>'); res.endBlock('</property>'); } return res; }; // Generate cache configs. $generatorSpring.cache = function(cache, res) { if (!res) res = $generatorCommon.builder(); res.startBlock('<bean class="org.apache.ignite.configuration.CacheConfiguration">'); $generatorSpring.cacheConfiguration(cache, res); res.endBlock('</bean>'); return res; }; // Generate cache configs. $generatorSpring.cacheConfiguration = function(cache, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.cacheGeneral(cache, res); $generatorSpring.cacheMemory(cache, res); $generatorSpring.cacheQuery(cache, cache.domains, res); $generatorSpring.cacheStore(cache, cache.domains, res); const igfs = _.get(cache, 'nodeFilter.IGFS.instance'); $generatorSpring.cacheNodeFilter(cache, igfs ? [igfs] : [], res); $generatorSpring.cacheConcurrency(cache, res); $generatorSpring.cacheRebalance(cache, res); $generatorSpring.cacheServerNearCache(cache, res); $generatorSpring.cacheStatistics(cache, res); $generatorSpring.cacheDomains(cache.domains, res); return res; }; // Generate caches configs. $generatorSpring.clusterCaches = function(caches, igfss, isSrvCfg, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.isDefinedAndNotEmpty(caches) || (isSrvCfg && $generatorCommon.isDefinedAndNotEmpty(igfss))) { res.emptyLineIfNeeded(); res.startBlock('<property name="cacheConfiguration">'); res.startBlock('<list>'); _.forEach(caches, function(cache) { $generatorSpring.cache(cache, res); res.needEmptyLine = true; }); if (isSrvCfg) { _.forEach(igfss, (igfs) => { $generatorSpring.cache($generatorCommon.igfsDataCache(igfs), res); res.needEmptyLine = true; $generatorSpring.cache($generatorCommon.igfsMetaCache(igfs), res); res.needEmptyLine = true; }); } res.endBlock('</list>'); res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate IGFSs configs. $generatorSpring.igfss = function(igfss, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.isDefinedAndNotEmpty(igfss)) { res.emptyLineIfNeeded(); res.startBlock('<property name="fileSystemConfiguration">'); res.startBlock('<list>'); _.forEach(igfss, function(igfs) { res.startBlock('<bean class="org.apache.ignite.configuration.FileSystemConfiguration">'); $generatorSpring.igfsGeneral(igfs, res); $generatorSpring.igfsIPC(igfs, res); $generatorSpring.igfsFragmentizer(igfs, res); $generatorSpring.igfsDualMode(igfs, res); $generatorSpring.igfsSecondFS(igfs, res); $generatorSpring.igfsMisc(igfs, res); res.endBlock('</bean>'); res.needEmptyLine = true; }); res.endBlock('</list>'); res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate IGFS IPC configuration. $generatorSpring.igfsIPC = function(igfs, res) { if (!res) res = $generatorCommon.builder(); if (igfs.ipcEndpointEnabled) { $generatorSpring.beanProperty(res, igfs.ipcEndpointConfiguration, 'ipcEndpointConfiguration', $generatorCommon.IGFS_IPC_CONFIGURATION, true); res.needEmptyLine = true; } return res; }; // Generate IGFS fragmentizer configuration. $generatorSpring.igfsFragmentizer = function(igfs, res) { if (!res) res = $generatorCommon.builder(); if (igfs.fragmentizerEnabled) { $generatorSpring.property(res, igfs, 'fragmentizerConcurrentFiles', null, 0); $generatorSpring.property(res, igfs, 'fragmentizerThrottlingBlockLength', null, 16777216); $generatorSpring.property(res, igfs, 'fragmentizerThrottlingDelay', null, 200); res.needEmptyLine = true; } else $generatorSpring.property(res, igfs, 'fragmentizerEnabled'); return res; }; // Generate IGFS dual mode configuration. $generatorSpring.igfsDualMode = function(igfs, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, igfs, 'dualModeMaxPendingPutsSize', null, 0); if ($generatorCommon.isDefinedAndNotEmpty(igfs.dualModePutExecutorService)) { res.startBlock('<property name="dualModePutExecutorService">'); res.line('<bean class="' + igfs.dualModePutExecutorService + '"/>'); res.endBlock('</property>'); } $generatorSpring.property(res, igfs, 'dualModePutExecutorServiceShutdown', null, false); res.needEmptyLine = true; return res; }; $generatorSpring.igfsSecondFS = function(igfs, res) { if (!res) res = $generatorCommon.builder(); if (igfs.secondaryFileSystemEnabled) { const secondFs = igfs.secondaryFileSystem || {}; res.startBlock('<property name="secondaryFileSystem">'); res.startBlock('<bean class="org.apache.ignite.hadoop.fs.IgniteHadoopIgfsSecondaryFileSystem">'); const nameDefined = $generatorCommon.isDefinedAndNotEmpty(secondFs.userName); const cfgDefined = $generatorCommon.isDefinedAndNotEmpty(secondFs.cfgPath); $generatorSpring.constructorArg(res, 0, secondFs, 'uri'); if (cfgDefined || nameDefined) $generatorSpring.constructorArg(res, 1, secondFs, 'cfgPath'); $generatorSpring.constructorArg(res, 2, secondFs, 'userName', null, true); res.endBlock('</bean>'); res.endBlock('</property>'); res.needEmptyLine = true; } return res; }; // Generate IGFS general configuration. $generatorSpring.igfsGeneral = function(igfs, res) { if (!res) res = $generatorCommon.builder(); if ($generatorCommon.isDefinedAndNotEmpty(igfs.name)) { igfs.dataCacheName = $generatorCommon.igfsDataCache(igfs).name; igfs.metaCacheName = $generatorCommon.igfsMetaCache(igfs).name; $generatorSpring.property(res, igfs, 'name'); $generatorSpring.property(res, igfs, 'dataCacheName'); $generatorSpring.property(res, igfs, 'metaCacheName'); $generatorSpring.property(res, igfs, 'defaultMode', null, 'DUAL_ASYNC'); res.needEmptyLine = true; } return res; }; // Generate IGFS misc configuration. $generatorSpring.igfsMisc = function(igfs, res) { if (!res) res = $generatorCommon.builder(); $generatorSpring.property(res, igfs, 'blockSize', null, 65536); $generatorSpring.property(res, igfs, 'streamBufferSize', null, 65536); $generatorSpring.property(res, igfs, 'maxSpaceSize', null, 0); $generatorSpring.property(res, igfs, 'maximumTaskRangeLength', null, 0); $generatorSpring.property(res, igfs, 'managementPort', null, 11400); $generatorSpring.property(res, igfs, 'perNodeBatchSize', null, 100); $generatorSpring.property(res, igfs, 'perNodeParallelBatchCount', null, 8); $generatorSpring.property(res, igfs, 'prefetchBlocks', null, 0); $generatorSpring.property(res, igfs, 'sequentialReadsBeforePrefetch', null, 0); $generatorSpring.property(res, igfs, 'trashPurgeTimeout', null, 1000); $generatorSpring.property(res, igfs, 'colocateMetadata', null, true); $generatorSpring.property(res, igfs, 'relaxedConsistency', null, true); res.softEmptyLine(); if (igfs.pathModes && igfs.pathModes.length > 0) { res.startBlock('<property name="pathModes">'); res.startBlock('<map>'); _.forEach(igfs.pathModes, function(pair) { res.line('<entry key="' + pair.path + '" value="' + pair.mode + '"/>'); }); res.endBlock('</map>'); res.endBlock('</property>'); } return res; }; // Generate DataSource beans. $generatorSpring.generateDataSources = function(datasources, res) { if (!res) res = $generatorCommon.builder(); if (datasources.length > 0) { res.line('<!-- Data source beans will be initialized from external properties file. -->'); _.forEach(datasources, (datasource) => $generatorSpring.generateDataSource(datasource, res)); res.needEmptyLine = true; res.emptyLineIfNeeded(); } return res; }; $generatorSpring.generateDataSource = function(datasource, res) { const beanId = datasource.dataSourceBean; res.startBlock('<bean id="' + beanId + '" class="' + $generatorCommon.DATA_SOURCES[datasource.dialect] + '">'); switch (datasource.dialect) { case 'Generic': res.line('<property name="jdbcUrl" value="${' + beanId + '.jdbc.url}"/>'); break; case 'DB2': res.line('<property name="serverName" value="${' + beanId + '.jdbc.server_name}"/>'); res.line('<property name="portNumber" value="${' + beanId + '.jdbc.port_number}"/>'); res.line('<property name="databaseName" value="${' + beanId + '.jdbc.database_name}"/>'); res.line('<property name="driverType" value="${' + beanId + '.jdbc.driver_type}"/>'); break; case 'PostgreSQL': res.line('<property name="url" value="${' + beanId + '.jdbc.url}"/>'); break; default: res.line('<property name="URL" value="${' + beanId + '.jdbc.url}"/>'); } res.line('<property name="user" value="${' + beanId + '.jdbc.username}"/>'); res.line('<property name="password" value="${' + beanId + '.jdbc.password}"/>'); res.endBlock('</bean>'); res.needEmptyLine = true; res.emptyLineIfNeeded(); }; $generatorSpring.clusterConfiguration = function(cluster, clientNearCfg, res) { const isSrvCfg = _.isNil(clientNearCfg); if (!isSrvCfg) { res.line('<property name="clientMode" value="true"/>'); res.needEmptyLine = true; } $generatorSpring.clusterGeneral(cluster, res); $generatorSpring.clusterAtomics(cluster.atomicConfiguration, res); $generatorSpring.clusterBinary(cluster.binaryConfiguration, res); $generatorSpring.clusterCacheKeyConfiguration(cluster.cacheKeyConfiguration, res); $generatorSpring.clusterCollision(cluster.collision, res); $generatorSpring.clusterCommunication(cluster, res); $generatorSpring.clusterConnector(cluster.connector, res); $generatorSpring.clusterDeployment(cluster, res); $generatorSpring.clusterEvents(cluster, res); $generatorSpring.clusterFailover(cluster, res); $generatorSpring.clusterLogger(cluster.logger, res); $generatorSpring.clusterODBC(cluster.odbc, res); $generatorSpring.clusterMarshaller(cluster, res); $generatorSpring.clusterMetrics(cluster, res); $generatorSpring.clusterSwap(cluster, res); $generatorSpring.clusterTime(cluster, res); $generatorSpring.clusterPools(cluster, res); $generatorSpring.clusterTransactions(cluster.transactionConfiguration, res); $generatorSpring.clusterCaches(cluster.caches, cluster.igfss, isSrvCfg, res); $generatorSpring.clusterSsl(cluster, res); if (isSrvCfg) $generatorSpring.igfss(cluster.igfss, res); $generatorSpring.clusterUserAttributes(cluster, res); return res; }; $generatorSpring.cluster = function(cluster, clientNearCfg) { if (cluster) { const res = $generatorCommon.builder(1); if (clientNearCfg) { res.startBlock('<bean id="nearCacheBean" class="org.apache.ignite.configuration.NearCacheConfiguration">'); if (clientNearCfg.nearStartSize) $generatorSpring.property(res, clientNearCfg, 'nearStartSize'); if (clientNearCfg.nearEvictionPolicy && clientNearCfg.nearEvictionPolicy.kind) $generatorSpring.evictionPolicy(res, clientNearCfg.nearEvictionPolicy, 'nearEvictionPolicy'); res.endBlock('</bean>'); res.needEmptyLine = true; res.emptyLineIfNeeded(); } // Generate Ignite Configuration. res.startBlock('<bean class="org.apache.ignite.configuration.IgniteConfiguration">'); $generatorSpring.clusterConfiguration(cluster, clientNearCfg, res); res.endBlock('</bean>'); // Build final XML: // 1. Add header. let xml = '<?xml version="1.0" encoding="UTF-8"?>\n\n'; xml += '<!-- ' + $generatorCommon.mainComment('configuration') + ' -->\n\n'; xml += '<beans xmlns="http://www.springframework.org/schema/beans"\n'; xml += ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n'; xml += ' xmlns:util="http://www.springframework.org/schema/util"\n'; xml += ' xsi:schemaLocation="http://www.springframework.org/schema/beans\n'; xml += ' http://www.springframework.org/schema/beans/spring-beans.xsd\n'; xml += ' http://www.springframework.org/schema/util\n'; xml += ' http://www.springframework.org/schema/util/spring-util.xsd">\n'; // 2. Add external property file if ($generatorCommon.secretPropertiesNeeded(cluster)) { xml += ' <!-- Load external properties file. -->\n'; xml += ' <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">\n'; xml += ' <property name="location" value="classpath:secret.properties"/>\n'; xml += ' </bean>\n\n'; } // 3. Add data sources. xml += $generatorSpring.generateDataSources(res.datasources, $generatorCommon.builder(1)).asString(); // 3. Add main content. xml += res.asString(); // 4. Add footer. xml += '\n</beans>'; return xml; } return ''; }; export default $generatorSpring;
StartTest(function (t) { //http://www.sencha.com/forum/showthread.php?268333-4.2.1-IE-quot-Focus-quot-method-can-break-on-destroyed-grid-views&p=982906#post982906 Ext.Component.override({ onDestroy : function () { if (this.focusTask) this.focusTask.cancel() this.callParent(arguments) } }) var calendarWidget, calendar, dayGrid, weekGrid, dayStore, weekStore var generateDataSet = function (activeTab, doNotReCreateCalendar) { var parentCalendar1 = new Gnt.data.Calendar({ name : 'Parent1', calendarId : 'Parent1' }), parentCalendar2 = new Gnt.data.calendar.BusinessTime({ name : 'Parent2', calendarId : 'Parent2' }); if (!doNotReCreateCalendar) calendar = new Gnt.data.calendar.BusinessTime({ name : 'Calendar', parent : parentCalendar1, data : [ { Id : 'initial', Date : new Date(2010, 0, 13), Name : 'foo', Cls : 'gnt-national-holiday' } ] }); if (calendarWidget) calendarWidget.destroy() calendarWidget = new Gnt.widget.calendar.Calendar({ calendar : calendar, height : 550, width : 600, renderTo : Ext.getBody() }); calendar = calendar dayGrid = calendarWidget.getDayGrid() weekGrid = calendarWidget.getWeekGrid() dayStore = dayGrid.getStore() weekStore = weekGrid.getStore() if (activeTab != null) dayGrid.ownerCt.getLayout().setActiveItem(activeTab) } var today = Ext.Date.clearTime(new Date()) var today1wp = Ext.Date.clearTime(Sch.util.Date.add(new Date(), Sch.util.Date.WEEK, 1)) var today1wm = Ext.Date.clearTime(Sch.util.Date.add(new Date(), Sch.util.Date.WEEK, -1)) t.it('Adding day override should work', function (t) { generateDataSet() t.is(dayStore.getCount(), 1, "1 day override should present already"); t.is(calendar.getCount(), 1, "1 day override should present already"); t.chain( // test adding day override { click : function () { return dayGrid.el.down('.gnt-action-add') } }, function (next) { t.is(dayStore.getCount(), 2, 'Day override successfully added.'); t.is(dayStore.getAt(0).get('Date'), today, 'and it has current date'); t.firesOk({ observable : calendar, events : { update : 0, add : 1, remove : 0 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getCount(), 2, 'Day override succcessfully added to the original calendar') var newOverride = calendar.getAt(1) t.is(newOverride.get('Date'), today, 'and it has current date'); t.notOk(newOverride.get('Id'), 'and it has empty Id'); t.is(newOverride.get('Type'), 'DAY', 'and it has default type'); } ) }) t.it('Editing day override name and date should work', function (t) { generateDataSet() t.chain( // test editing day override name and date { clickToEditCell : [ dayGrid, 0, 0 ] }, function (next) { //select input of the editor... var editor = dayGrid.editingPlugin.getActiveEditor(); editor.setValue('BAR'); editor.completeEdit(); next(); }, { clickToEditCell : [ dayGrid, 0, 1 ] }, function (next) { var editor = dayGrid.editingPlugin.getActiveEditor(); editor.setValue(Sch.util.Date.add(editor.getValue(), Sch.util.Date.DAY, 1)); editor.completeEdit(); t.firesOk({ observable : calendar, events : { update : 1, add : 0, remove : 0 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getById('initial').getName(), 'BAR', 'Name correctly changed') t.is(calendar.getById('initial').getDate(), new Date(2010, 0, 14), 'Date correctly incremented on 1 day') } ) }) t.it('Editing day override availability should work', function (t) { generateDataSet() var availabilityGrid t.chain( { click : function () { return t.getCell(dayGrid, 0, 0) } }, { click : function () { return dayGrid.el.down('.gnt-action-edit') } }, { click : function () { availabilityGrid = calendarWidget.currentDayOverrideEditor return availabilityGrid.down('radiogroup [inputValue=true]') } }, { click : function () { return availabilityGrid.addButton } }, { clickToEditCell : function () { return [ availabilityGrid, 0, 0 ] } }, function (next) { var editor = availabilityGrid.editingPlugin.getActiveEditor(); editor.setValue('12:00AM'); editor.completeEdit(); next() }, { clickToEditCell : function () { return [ availabilityGrid, 0, 1 ] } }, function (next) { var editor = availabilityGrid.editingPlugin.getActiveEditor(); editor.setValue('12:00AM'); editor.completeEdit(); next() }, { click : function () { return availabilityGrid.ownerCt.down('button[text=OK]') } }, function (next) { calendarWidget.applyChanges() t.isDeeply(calendar.getById('initial').getAvailability(), [ { startTime : new Date(0, 0, 0, 0, 0), endTime : new Date(0, 0, 1, 0, 0) } ], '24h availability correctly saved in the calendar') t.isDeeply(calendar.getById('initial').getAvailability(true), [ '00:00-24:00' ], '24h availability correctly saved in string form in the calendar') next() } ) }) t.it('Adding and removing day override should work', function (t) { generateDataSet() t.chain( // test adding and removing day override { click : function () { return dayGrid.el.down('.gnt-action-add') } }, { click : function () { return t.getCell(dayGrid, 1, 0) } }, { click : function () { return dayGrid.el.down('.gnt-action-remove') } }, function (next) { t.firesOk({ observable : calendar, events : { update : 0, add : 1, remove : 1 }, during : function () { calendarWidget.applyChanges() } }) } ) }) t.it('Adding empty week override should work', function (t) { generateDataSet(1) t.chain( // test adding empty week override { click : function () { return weekGrid.el.down('.gnt-action-add') } }, function (next) { t.is(weekStore.getCount(), 1, 'Week override successfully added.'); t.is(weekStore.getAt(0).get('startDate'), today, 'and it has correct start date'); t.is(weekStore.getAt(0).get('endDate'), today1wp, 'and it has correct end date'); t.firesOk({ observable : calendar, events : { update : 0, add : 1, remove : 0 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getCount(), 2, 'Since new week override is empty, only a its main day should be added to the calendar') var newOverride = calendar.getAt(1) t.notOk(newOverride.get('Id'), 'and it has empty Id'); t.notOk(newOverride.get('Date'), 'and it has empty Date'); t.is(newOverride.get('Type'), 'WEEKDAYOVERRIDE', 'and it has correct type of week day override'); t.is(newOverride.getOverrideStartDate(), today, 'and it has correct start date'); t.is(newOverride.getOverrideEndDate(), today1wp, 'and it has correct end date'); var nonStandardWeek = calendar.getNonStandardWeekByStartDate(new Date()) t.is(nonStandardWeek.startDate, today, 'correct start date for new week'); t.is(nonStandardWeek.endDate, today1wp, 'correct end date for new week'); t.is(nonStandardWeek.mainDay, newOverride, 'Main day correct set on the week object') } ) }) t.it('Adding week override with some re-defined days should work', function (t) { generateDataSet(1) t.chain( // test adding week override with some re-defined days { click : function () { return weekGrid.el.down('.gnt-action-add') } }, { click : function () { return t.getCell(weekGrid, 0, 0) } }, { click : function () { return weekGrid.el.down('.gnt-action-edit') } }, { click : function () { return t.cq1('calendarweekeditor').getDayTypeRadioGroup().el.query('input')[ 1 ] } }, { click : function () { return t.cq1('calendarweekeditor').ownerCt.query('button[action=ok]')[ 0 ] } }, function (next) { t.firesOk({ observable : calendar, events : { update : 0, add : 1, remove : 0 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getCount(), 3, 'Since new week override has 1 day, should be 3 days in the store: 1 original, 1 main + 1 week override day') var nonStandardWeek = calendar.getNonStandardWeekByStartDate(new Date()) t.is(nonStandardWeek.startDate, today, 'correct start date for new week'); t.is(nonStandardWeek.endDate, today1wp, 'correct end date for new week'); // monday var overridenDay = nonStandardWeek.weekAvailability[ 1 ] t.is(overridenDay.getType(), 'WEEKDAYOVERRIDE'); t.is(overridenDay.getName(), nonStandardWeek.name, 'Name of overriden day is the same with week object'); t.is(overridenDay.getName(), nonStandardWeek.mainDay.getName(), 'Name of overriden day is the same with the week main day'); t.is(overridenDay.getOverrideStartDate(), today) t.is(overridenDay.getOverrideEndDate(), today1wp) t.notOk(overridenDay.get('Id')); t.notOk(overridenDay.get('Date')); // keeps the current calendar - can't be in own "iit" generateDataSet(1, true) next() }, // test the editing of the week override created in the previous test function (next) { t.is(weekStore.getCount(), 1, '1 week override should present in the week grid from start - was created in the previous step') next() }, { // click on the row to select it click : function () { return t.getCell(weekGrid, 0, 0) } }, { click : function () { return weekGrid.el.down('.gnt-action-edit') } }, { // chaing the type of the Monday to "default" - should remove the according day from week availability click : function () { return t.cq1('calendarweekeditor').getDayTypeRadioGroup().el.query('input')[ 0 ] } }, function (next) { // selecting the Friday (by index in the store) t.cq1('calendarweekeditor').getWeekDaysGrid().getSelectionModel().select(4) next() }, { // chaing the type of the Friday to "non-working day" - should add availability day click : function () { return t.cq1('calendarweekeditor').getDayTypeRadioGroup().el.query('input')[ 2 ] } }, { click : function () { return t.cq1('calendarweekeditor').ownerCt.query('button[action=ok]')[ 0 ] } }, { clickToEditCell : function () { return [ weekGrid, 0, 0 ] } }, function (next) { var editor = weekGrid.editingPlugin.getActiveEditor(); editor.setValue('WEEKFOO'); editor.completeEdit(); next(); }, { clickToEditCell : function () { return [ weekGrid, 0, 1 ] } }, function (next) { var editor = weekGrid.editingPlugin.getActiveEditor(); editor.setValue(today1wm); editor.completeEdit(); next(); }, function (next) { // 1 update for main day // 1 removal of the Monday // 1 addition for the Friday t.firesOk({ observable : calendar, events : { update : 1, add : 1, remove : 1 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getCount(), 3, 'Since new week override has 1 day, should be 3 days in the store: 1 original, 1 main + 1 week override day') t.notOk(calendar.getNonStandardWeekByStartDate(new Date()), 'Should no longer find a non-standard week at the current date') var nonStandardWeek = calendar.getNonStandardWeekByStartDate(today1wm) t.is(nonStandardWeek.startDate, today1wm, 'correct start date for new week'); t.is(nonStandardWeek.endDate, today1wp, 'correct end date for new week'); t.notOk(nonStandardWeek.weekAvailability[ 1 ], 'Monday override was removed from the week availability') // friday var overridenDay = nonStandardWeek.weekAvailability[ 5 ] t.is(overridenDay.getType(), 'WEEKDAYOVERRIDE'); t.is(overridenDay.getName(), 'WEEKFOO', 'Found the newly entered name for the week override'); t.is(overridenDay.getName(), nonStandardWeek.name, 'Name of overriden day is the same with week object'); t.is(overridenDay.getName(), nonStandardWeek.mainDay.getName(), 'Name of overriden day is the same with the week main day'); t.is(overridenDay.getOverrideStartDate(), today1wm) t.is(overridenDay.getOverrideEndDate(), today1wp) t.notOk(overridenDay.get('Id')); t.notOk(overridenDay.get('Date')); // keeps the current calendar - can't be in own "iit" generateDataSet(1, true) next() }, // test the removal of the week override edited in the previous test function (next) { t.is(weekStore.getCount(), 1, '1 week override should present in the week grid from start - was created in the previous step') next() }, { // click on the row to select it click : function () { return t.getCell(weekGrid, 0, 0) } }, { click : function () { return weekGrid.el.down('.gnt-action-remove') } }, function (next) { // 0 update // 2 removal - 1 main + 1 override // 0 addition t.firesOk({ observable : calendar, events : { update : 0, add : 0, remove : 2 }, during : function () { calendarWidget.applyChanges() } }) t.is(calendar.getCount(), 1, 'Should remain only initial override') t.notOk(calendar.getNonStandardWeekByStartDate(new Date()), 'Should no longer find a non-standard week at the current date') t.notOk(calendar.getNonStandardWeekByStartDate(today1wm), 'Should no longer find a non-standard week at the current date - 1 week') } ) }) });
const { assertLogLength } = require('../../support/utils') const { stripIndent } = require('common-tags') const { _ } = Cypress const okResponse = { contents: 'contents', filePath: '/path/to/foo.json', } describe('src/cy/commands/files', () => { beforeEach(() => { // call through normally on everything cy.stub(Cypress, 'backend').callThrough() }) describe('#readFile', () => { it('triggers \'read:file\' with the right options', () => { Cypress.backend.resolves(okResponse) cy.readFile('foo.json').then(() => { expect(Cypress.backend).to.be.calledWith( 'read:file', 'foo.json', { encoding: 'utf8' }, ) }) }) it('can take encoding as second argument', () => { Cypress.backend.resolves(okResponse) cy.readFile('foo.json', 'ascii').then(() => { expect(Cypress.backend).to.be.calledWith( 'read:file', 'foo.json', { encoding: 'ascii' }, ) }) }) // https://github.com/cypress-io/cypress/issues/1558 it('passes explicit null encoding through to server and decodes response', () => { Cypress.backend.resolves({ contents: Buffer.from('\n'), filePath: '/path/to/foo.json', }) cy.readFile('foo.json', null).then(() => { expect(Cypress.backend).to.be.calledWith( 'read:file', 'foo.json', { encoding: null }, ) }).should('eql', Buffer.from('\n')) }) it('sets the contents as the subject', () => { Cypress.backend.resolves(okResponse) cy.readFile('foo.json').then((subject) => { expect(subject).to.equal('contents') }) }) it('retries to read when ENOENT', () => { const err = new Error('foo') err.code = 'ENOENT' let retries = 0 cy.on('command:retry', () => { retries += 1 }) Cypress.backend .onFirstCall() .rejects(err) .onSecondCall() .resolves(okResponse) cy.readFile('foo.json').then(() => { expect(retries).to.eq(1) }) }) it('retries assertions until they pass', () => { let retries = 0 cy.on('command:retry', () => { retries += 1 }) Cypress.backend .onFirstCall() .resolves({ contents: 'foobarbaz', }) .onSecondCall() .resolves({ contents: 'quux', }) cy.readFile('foo.json').should('eq', 'quux').then(() => { expect(retries).to.eq(1) }) }) it('really works', () => { cy.readFile('cypress.json').its('baseUrl').should('eq', 'http://localhost:3500') }) it('works when contents are supposed to be null', () => { cy.readFile('does-not-exist').should('be.null') }) describe('.log', () => { beforeEach(function () { this.logs = [] cy.on('log:added', (attrs, log) => { this.lastLog = log this.logs.push(log) }) return null }) it('can turn off logging', () => { Cypress.backend.resolves(okResponse) cy.readFile('foo.json', { log: false }).then(function () { const logs = _.filter(this.logs, (log) => { return log.get('name') === 'readFile' }) expect(logs.length).to.eq(0) }) }) it('logs immediately before resolving', function () { Cypress.backend.resolves(okResponse) cy.on('log:added', (attrs, log) => { if (attrs.name === 'readFile') { expect(log.get('state')).to.eq('pending') expect(log.get('message')).to.eq('foo.json') expect(log.get('timeout')).to.eq(Cypress.config('defaultCommandTimeout')) } }) cy.readFile('foo.json').then(() => { if (!this.lastLog) { throw new Error('failed to log before resolving') } }) }) }) describe('errors', { defaultCommandTimeout: 50, }, () => { beforeEach(function () { this.logs = [] cy.on('log:added', (attrs, log) => { if (attrs.name === 'readFile') { this.lastLog = log this.logs.push(log) } }) return null }) it('throws when file argument is absent', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.readFile()` must be passed a non-empty string as its 1st argument. You passed: `undefined`.') expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile() }) it('throws when file argument is not a string', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.readFile()` must be passed a non-empty string as its 1st argument. You passed: `2`.') expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile(2) }) it('throws when file argument is an empty string', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.readFile()` must be passed a non-empty string as its 1st argument. You passed: ``.') expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('') }) it('throws when there is an error reading the file', function (done) { const err = new Error('EISDIR: illegal operation on a directory, read') err.name = 'EISDIR' err.code = 'EISDIR' err.filePath = '/path/to/foo' Cypress.backend.rejects(err) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent`\ \`cy.readFile(\"foo\")\` failed while trying to read the file at the following path: \`/path/to/foo\` The following error occurred: > "EISDIR: illegal operation on a directory, read"`) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('foo') }) it('has implicit existence assertion and throws a specific error when file does not exist', function (done) { const err = new Error('ENOENT: no such file or directory, open \'foo.json\'') err.name = 'ENOENT' err.code = 'ENOENT' err.filePath = '/path/to/foo.json' Cypress.backend.rejects(err) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent` Timed out retrying after 50ms: \`cy.readFile(\"foo.json\")\` failed because the file does not exist at the following path: \`/path/to/foo.json\``) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('foo.json') }) // https://github.com/cypress-io/cypress/issues/20683 it('has implicit existence assertion, retries and throws a specific error when file does not exist for null encoding', function (done) { const err = new Error('ENOENT: no such file or directory, open \'foo.json\'') err.name = 'ENOENT' err.code = 'ENOENT' err.filePath = '/path/to/foo.json' Cypress.backend.rejects(err) let retries = 0 cy.on('command:retry', () => { retries += 1 }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent` Timed out retrying after 50ms: \`cy.readFile(\"foo.json\")\` failed because the file does not exist at the following path: \`/path/to/foo.json\``) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') expect(retries).to.eq(2) done() }) cy.readFile('foo.json', null) }) it('throws a specific error when file exists when it shouldn\'t', function (done) { Cypress.backend.resolves(okResponse) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent`\ Timed out retrying after 50ms: \`cy.readFile(\"foo.json\")\` failed because the file exists when expected not to exist at the following path: \`/path/to/foo.json\``) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('foo.json').should('not.exist') }) it('passes through assertion error when not about existence', function (done) { Cypress.backend.resolves({ contents: 'foo', }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('Timed out retrying after 50ms: expected \'foo\' to equal \'contents\'') done() }) cy.readFile('foo.json').should('equal', 'contents') }) it('throws when the read timeout expires', function (done) { Cypress.backend.callsFake(() => { return new Cypress.Promise(() => { /* Broken promise for timeout */ }) }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent`\ \`cy.readFile("foo")\` timed out after waiting \`10ms\`. `) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('foo', { timeout: 10 }) }) it('uses defaultCommandTimeout config value if option not provided', { defaultCommandTimeout: 42, }, function (done) { Cypress.backend.callsFake(() => { return new Cypress.Promise(() => { /* Broken promise for timeout */ }) }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent`\ \`cy.readFile("foo")\` timed out after waiting \`42ms\`. `) expect(err.docsUrl).to.eq('https://on.cypress.io/readfile') done() }) cy.readFile('foo') }) }) }) describe('#writeFile', () => { it('triggers \'write:file\' with the right options', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents').then(() => { expect(Cypress.backend).to.be.calledWith( 'write:file', 'foo.txt', 'contents', { encoding: 'utf8', flag: 'w', }, ) }) }) it('can take encoding as third argument', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents', 'ascii').then(() => { expect(Cypress.backend).to.be.calledWith( 'write:file', 'foo.txt', 'contents', { encoding: 'ascii', flag: 'w', }, ) }) }) // https://github.com/cypress-io/cypress/issues/1558 it('explicit null encoding is sent to server as Buffer', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', Buffer.from([0, 0, 54, 255]), null).then(() => { expect(Cypress.backend).to.be.calledWith( 'write:file', 'foo.txt', Buffer.from([0, 0, 54, 255]), { encoding: null, flag: 'w', }, ) }) }) it('can take encoding as part of options', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents', { encoding: 'ascii' }).then(() => { expect(Cypress.backend).to.be.calledWith( 'write:file', 'foo.txt', 'contents', { encoding: 'ascii', flag: 'w', }, ) }) }) it('yields null', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents').then((subject) => { expect(subject).to.eq(null) }) }) it('can write a string', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents') }) it('can write an array as json', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.json', []) }) it('can write an object as json', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.json', {}) }) it('writes the file to the filesystem, overwriting existing file', () => { cy .writeFile('cypress/fixtures/foo.txt', '') .writeFile('cypress/fixtures/foo.txt', 'bar') .readFile('cypress/fixtures/foo.txt').should('equal', 'bar') .exec('rm cypress/fixtures/foo.txt') }) describe('.flag', () => { it('sends a flag if specified', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents', { flag: 'a+' }).then(() => { expect(Cypress.backend).to.be.calledWith( 'write:file', 'foo.txt', 'contents', { encoding: 'utf8', flag: 'a+', }, ) }) }) it('appends content to existing file if specified', () => { cy .writeFile('cypress/fixtures/foo.txt', 'foo') .writeFile('cypress/fixtures/foo.txt', 'bar', { flag: 'a+' }) .readFile('cypress/fixtures/foo.txt').should('equal', 'foobar') .exec('rm cypress/fixtures/foo.txt') }) }) describe('.log', () => { beforeEach(function () { this.logs = [] cy.on('log:added', (attrs, log) => { this.lastLog = log this.logs.push(log) }) return null }) it('can turn off logging', () => { Cypress.backend.resolves(okResponse) cy.writeFile('foo.txt', 'contents', { log: false }).then(function () { const logs = _.filter(this.logs, (log) => { return log.get('name') === 'writeFile' }) expect(logs.length).to.eq(0) }) }) it('logs immediately before resolving', function () { Cypress.backend.resolves(okResponse) cy.on('log:added', (attrs, log) => { if (attrs.name === 'writeFile') { expect(log.get('state')).to.eq('pending') expect(log.get('message')).to.eq('foo.txt', 'contents') expect(log.get('timeout')).to.eq(Cypress.config('defaultCommandTimeout')) } }) cy.writeFile('foo.txt', 'contents').then(() => { if (!this.lastLog) { throw new Error('failed to log before resolving') } }) }) }) describe('errors', { defaultCommandTimeout: 50, }, () => { beforeEach(function () { this.logs = [] cy.on('log:added', (attrs, log) => { if (attrs.name === 'writeFile') { this.lastLog = log this.logs.push(log) } }) return null }) it('throws when file name argument is absent', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.writeFile()` must be passed a non-empty string as its 1st argument. You passed: `undefined`.') expect(err.docsUrl).to.eq('https://on.cypress.io/writefile') done() }) cy.writeFile() }) it('throws when file name argument is not a string', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.writeFile()` must be passed a non-empty string as its 1st argument. You passed: `2`.') expect(err.docsUrl).to.eq('https://on.cypress.io/writefile') done() }) cy.writeFile(2) }) it('throws when contents argument is absent', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.writeFile()` must be passed a non-empty string, an object, or an array as its 2nd argument. You passed: `undefined`.') done() }) cy.writeFile('foo.txt') }) it('throws when contents argument is not a string, object, or array', function (done) { cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq('`cy.writeFile()` must be passed a non-empty string, an object, or an array as its 2nd argument. You passed: `2`.') done() }) cy.writeFile('foo.txt', 2) }) it('throws when there is an error writing the file', function (done) { const err = new Error('WHOKNOWS: unable to write file') err.name = 'WHOKNOWS' err.code = 'WHOKNOWS' err.filePath = '/path/to/foo.txt' Cypress.backend.rejects(err) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent` \`cy.writeFile(\"foo.txt\")\` failed while trying to write the file at the following path: \`/path/to/foo.txt\` The following error occurred: > "WHOKNOWS: unable to write file"`) expect(err.docsUrl).to.eq('https://on.cypress.io/writefile') done() }) cy.writeFile('foo.txt', 'contents') }) it('throws when the write timeout expires', function (done) { Cypress.backend.callsFake(() => { return new Cypress.Promise(() => {}) }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent` \`cy.writeFile("foo.txt")\` timed out after waiting \`10ms\`. `) expect(err.docsUrl).to.eq('https://on.cypress.io/writefile') done() }) cy.writeFile('foo.txt', 'contents', { timeout: 10 }) }) it('uses defaultCommandTimeout config value if option not provided', { defaultCommandTimeout: 42, }, function (done) { Cypress.backend.callsFake(() => { return new Cypress.Promise(() => { /* Broken promise for timeout */ }) }) cy.on('fail', (err) => { const { lastLog } = this assertLogLength(this.logs, 1) expect(lastLog.get('error')).to.eq(err) expect(lastLog.get('state')).to.eq('failed') expect(err.message).to.eq(stripIndent` \`cy.writeFile("foo.txt")\` timed out after waiting \`42ms\`. `) expect(err.docsUrl).to.eq('https://on.cypress.io/writefile') done() }) cy.writeFile('foo.txt', 'contents') }) }) }) })
const express = require('express'); router = express.Router(); mongooseModel = require('../model/RegistrationModel'); multer = require('multer'); path = require('path') const { v4: uuidv4 } = require('uuid'); //storing our pdf file inside public folder const DIR = './public' const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, DIR); }, filename: (req, file, cb) => { const fileName = file.originalname.toLowerCase().split(' ').join('-'); cb(null, uuidv4() + '-' + fileName) } }); var upload = multer({ storage: storage, fileFilter: (req, file, cb) => { if (file.mimetype == "application/pdf") { cb(null, true); } else { cb(null, false); return cb(new Error('Only .pdf format allowed!')); } } }); //saving data to our database router.post('/signup', upload.single('cvlink'),(req, res, next) => { const url = req.protocol + '://' + req.get('host'); const signedUpUser = new mongooseModel({ fullname: req.body.fullname, birthday: req.body.birthday, gender: req.body.gender, pronouns: req.body.pronouns, nationality: req.body.nationality, ethnicity: req.body.ethnicity, onCampus: req.body.onCampus, college: req.body.college, room: req.body.room, street: req.body.street, zip: req.body.zip, city: req.body.city, country: req.body.country, email: req.body.email, phone: req.body.phone, university: req.body.university, degree: req.body.degree, major: req.body.major, gradYear: req.body.gradYear, exp: req.body.exp, prevHack: req.body.prevHack, whyApply: req.body.whyApply, drive: req.body.drive, creativity: req.body.creativity, role: req.body.role, strength: req.body.strength, weakness: req.body.weakness, built: req.body.built, achieve: req.body.achieve, partTeam: req.body.partTeam, team: req.body.team, teamMembers: req.body.teamMembers, diet: req.body.diet, tshirt: req.body.tshirt, needs: req.body.needs, questions: req.body.questions, linkedin: req.body.linkedin, github: req.body.github, cvlink: url + '/public/' + req.file.filename, terms: req.body.terms, mlh: req.body.mlh, privacy: req.body.privacy, }) signedUpUser.save() .then(result => { console.log("Data saved on the database!") res.sendStatus(201); }) .catch(error => { console.log(error); res.sendStatus(500); }) }) // //getting data from our database // router.get("/data", (req, res, next) => { // signedUpUser.find().then(data => { // res.status(200).json({ // message: "User data retrieved successfully!", // data: data, // }); // }); // }); module.exports = router;
'use strict' var request = require('../index') var tape = require('tape') // Run a querystring test. `options` can have the following keys: // - suffix : a string to be added to the URL // - qs : an object to be passed to request's `qs` option // - qsParseOptions : an object to be passed to request's `qsParseOptions` option // - qsStringifyOptions : an object to be passed to request's `qsStringifyOptions` option // - afterRequest : a function to execute after creating the request // - expected : the expected path of the request // - expectedQuerystring : expected path when using the querystring library function runTest (name, options) { var uri = 'http://www.google.com' + (options.suffix || '') var opts = { uri: uri, qsParseOptions: options.qsParseOptions, qsStringifyOptions: options.qsStringifyOptions } if (options.qs) { opts.qs = options.qs } tape(name + ' - using qs', function (t) { var r = request.get(opts) if (typeof options.afterRequest === 'function') { options.afterRequest(r) } process.nextTick(function () { t.equal(r.path, options.expected) r.abort() t.end() }) }) tape(name + ' - using querystring', function (t) { opts.useQuerystring = true var r = request.get(opts) if (typeof options.afterRequest === 'function') { options.afterRequest(r) } process.nextTick(function () { t.equal(r.path, options.expectedQuerystring || options.expected) r.abort() t.end() }) }) } function esc (str) { return str .replace(/\[/g, '%5B') .replace(/\]/g, '%5D') } runTest('adding a querystring', { qs: { q: 'search' }, expected: '/?q=search' }) runTest('replacing a querystring value', { suffix: '?q=abc', qs: { q: 'search' }, expected: '/?q=search' }) runTest('appending a querystring value to the ones present in the uri', { suffix: '?x=y', qs: { q: 'search' }, expected: '/?x=y&q=search' }) runTest('leaving a querystring alone', { suffix: '?x=y', expected: '/?x=y' }) runTest('giving empty qs property', { qs: {}, expected: '/' }) runTest('modifying the qs after creating the request', { qs: {}, afterRequest: function (r) { r.qs({ q: 'test' }) }, expected: '/?q=test' }) runTest('a query with an object for a value', { qs: { where: { foo: 'bar' } }, expected: esc('/?where[foo]=bar'), expectedQuerystring: '/?where=' }) runTest('a query with an array for a value', { qs: { order: ['bar', 'desc'] }, expected: esc('/?order[0]=bar&order[1]=desc'), expectedQuerystring: '/?order=bar&order=desc' }) runTest('pass options to the qs module via the qsParseOptions key', { suffix: '?a=1;b=2', qs: {}, qsParseOptions: { delimiter: ';' }, qsStringifyOptions: { delimiter: ';' }, expected: esc('/?a=1;b=2'), expectedQuerystring: '/?a=1%3Bb%3D2' }) runTest('pass options to the qs module via the qsStringifyOptions key', { qs: { order: ['bar', 'desc'] }, qsStringifyOptions: { arrayFormat: 'brackets' }, expected: esc('/?order[]=bar&order[]=desc'), expectedQuerystring: '/?order=bar&order=desc' }) runTest('pass options to the querystring module via the qsParseOptions key', { suffix: '?a=1;b=2', qs: {}, qsParseOptions: { sep: ';' }, qsStringifyOptions: { sep: ';' }, expected: esc('/?a=1%3Bb%3D2'), expectedQuerystring: '/?a=1;b=2' }) runTest('pass options to the querystring module via the qsStringifyOptions key', { qs: { order: ['bar', 'desc'] }, qsStringifyOptions: { sep: ';' }, expected: esc('/?order[0]=bar&order[1]=desc'), expectedQuerystring: '/?order=bar;order=desc' })
/** * SyntaxHighlighter * http://alexgorbatchev.com/SyntaxHighlighter * * SyntaxHighlighter is donationware. If you are using it, please donate. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html * * @version * 3.0.83 (July 02 2010) * * @copyright * Copyright (C) 2004-2010 Alex Gorbatchev. * * @license * Dual licensed under the MIT and GPL licenses. */ ;(function() { // CommonJS typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; function Brush() { // Contributed by Jen // http://www.jensbits.com/2009/05/14/coldfusion-brush-for-syntaxhighlighter-plus var funcs = 'Abs ACos AddSOAPRequestHeader AddSOAPResponseHeader AjaxLink AjaxOnLoad ArrayAppend ArrayAvg ArrayClear ArrayDeleteAt ' + 'ArrayInsertAt ArrayIsDefined ArrayIsEmpty ArrayLen ArrayMax ArrayMin ArraySet ArraySort ArraySum ArraySwap ArrayToList ' + 'Asc ASin Atn BinaryDecode BinaryEncode BitAnd BitMaskClear BitMaskRead BitMaskSet BitNot BitOr BitSHLN BitSHRN BitXor ' + 'Ceiling CharsetDecode CharsetEncode Chr CJustify Compare CompareNoCase Cos CreateDate CreateDateTime CreateObject ' + 'CreateODBCDate CreateODBCDateTime CreateODBCTime CreateTime CreateTimeSpan CreateUUID DateAdd DateCompare DateConvert ' + 'DateDiff DateFormat DatePart Day DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear DE DecimalFormat DecrementValue ' + 'Decrypt DecryptBinary DeleteClientVariable DeserializeJSON DirectoryExists DollarFormat DotNetToCFType Duplicate Encrypt ' + 'EncryptBinary Evaluate Exp ExpandPath FileClose FileCopy FileDelete FileExists FileIsEOF FileMove FileOpen FileRead ' + 'FileReadBinary FileReadLine FileSetAccessMode FileSetAttribute FileSetLastModified FileWrite Find FindNoCase FindOneOf ' + 'FirstDayOfMonth Fix FormatBaseN GenerateSecretKey GetAuthUser GetBaseTagData GetBaseTagList GetBaseTemplatePath ' + 'GetClientVariablesList GetComponentMetaData GetContextRoot GetCurrentTemplatePath GetDirectoryFromPath GetEncoding ' + 'GetException GetFileFromPath GetFileInfo GetFunctionList GetGatewayHelper GetHttpRequestData GetHttpTimeString ' + 'GetK2ServerDocCount GetK2ServerDocCountLimit GetLocale GetLocaleDisplayName GetLocalHostIP GetMetaData GetMetricData ' + 'GetPageContext GetPrinterInfo GetProfileSections GetProfileString GetReadableImageFormats GetSOAPRequest GetSOAPRequestHeader ' + 'GetSOAPResponse GetSOAPResponseHeader GetTempDirectory GetTempFile GetTemplatePath GetTickCount GetTimeZoneInfo GetToken ' + 'GetUserRoles GetWriteableImageFormats Hash Hour HTMLCodeFormat HTMLEditFormat IIf ImageAddBorder ImageBlur ImageClearRect ' + 'ImageCopy ImageCrop ImageDrawArc ImageDrawBeveledRect ImageDrawCubicCurve ImageDrawLine ImageDrawLines ImageDrawOval ' + 'ImageDrawPoint ImageDrawQuadraticCurve ImageDrawRect ImageDrawRoundRect ImageDrawText ImageFlip ImageGetBlob ImageGetBufferedImage ' + 'ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageGrayscale ImageInfo ImageNegative ImageNew ImageOverlay ImagePaste ' + 'ImageRead ImageReadBase64 ImageResize ImageRotate ImageRotateDrawingAxis ImageScaleToFit ImageSetAntialiasing ImageSetBackgroundColor ' + 'ImageSetDrawingColor ImageSetDrawingStroke ImageSetDrawingTransparency ImageSharpen ImageShear ImageShearDrawingAxis ImageTranslate ' + 'ImageTranslateDrawingAxis ImageWrite ImageWriteBase64 ImageXORDrawingMode IncrementValue InputBaseN Insert Int IsArray IsBinary ' + 'IsBoolean IsCustomFunction IsDate IsDDX IsDebugMode IsDefined IsImage IsImageFile IsInstanceOf IsJSON IsLeapYear IsLocalHost ' + 'IsNumeric IsNumericDate IsObject IsPDFFile IsPDFObject IsQuery IsSimpleValue IsSOAPRequest IsStruct IsUserInAnyRole IsUserInRole ' + 'IsUserLoggedIn IsValid IsWDDX IsXML IsXmlAttribute IsXmlDoc IsXmlElem IsXmlNode IsXmlRoot JavaCast JSStringFormat LCase Left Len ' + 'ListAppend ListChangeDelims ListContains ListContainsNoCase ListDeleteAt ListFind ListFindNoCase ListFirst ListGetAt ListInsertAt ' + 'ListLast ListLen ListPrepend ListQualify ListRest ListSetAt ListSort ListToArray ListValueCount ListValueCountNoCase LJustify Log ' + 'Log10 LSCurrencyFormat LSDateFormat LSEuroCurrencyFormat LSIsCurrency LSIsDate LSIsNumeric LSNumberFormat LSParseCurrency LSParseDateTime ' + 'LSParseEuroCurrency LSParseNumber LSTimeFormat LTrim Max Mid Min Minute Month MonthAsString Now NumberFormat ParagraphFormat ParseDateTime ' + 'Pi PrecisionEvaluate PreserveSingleQuotes Quarter QueryAddColumn QueryAddRow QueryConvertForGrid QueryNew QuerySetCell QuotedValueList Rand ' + 'Randomize RandRange REFind REFindNoCase ReleaseComObject REMatch REMatchNoCase RemoveChars RepeatString Replace ReplaceList ReplaceNoCase ' + 'REReplace REReplaceNoCase Reverse Right RJustify Round RTrim Second SendGatewayMessage SerializeJSON SetEncoding SetLocale SetProfileString ' + 'SetVariable Sgn Sin Sleep SpanExcluding SpanIncluding Sqr StripCR StructAppend StructClear StructCopy StructCount StructDelete StructFind ' + 'StructFindKey StructFindValue StructGet StructInsert StructIsEmpty StructKeyArray StructKeyExists StructKeyList StructKeyList StructNew ' + 'StructSort StructUpdate Tan TimeFormat ToBase64 ToBinary ToScript ToString Trim UCase URLDecode URLEncodedFormat URLSessionFormat Val ' + 'ValueList VerifyClient Week Wrap Wrap WriteOutput XmlChildPos XmlElemNew XmlFormat XmlGetNodeType XmlNew XmlParse XmlSearch XmlTransform ' + 'XmlValidate Year YesNoFormat'; var keywords = 'cfabort cfajaximport cfajaxproxy cfapplet cfapplication cfargument cfassociate cfbreak cfcache cfcalendar ' + 'cfcase cfcatch cfchart cfchartdata cfchartseries cfcol cfcollection cfcomponent cfcontent cfcookie cfdbinfo ' + 'cfdefaultcase cfdirectory cfdiv cfdocument cfdocumentitem cfdocumentsection cfdump cfelse cfelseif cferror ' + 'cfexchangecalendar cfexchangeconnection cfexchangecontact cfexchangefilter cfexchangemail cfexchangetask ' + 'cfexecute cfexit cffeed cffile cfflush cfform cfformgroup cfformitem cfftp cffunction cfgrid cfgridcolumn ' + 'cfgridrow cfgridupdate cfheader cfhtmlhead cfhttp cfhttpparam cfif cfimage cfimport cfinclude cfindex ' + 'cfinput cfinsert cfinterface cfinvoke cfinvokeargument cflayout cflayoutarea cfldap cflocation cflock cflog ' + 'cflogin cfloginuser cflogout cfloop cfmail cfmailparam cfmailpart cfmenu cfmenuitem cfmodule cfNTauthenticate ' + 'cfobject cfobjectcache cfoutput cfparam cfpdf cfpdfform cfpdfformparam cfpdfparam cfpdfsubform cfpod cfpop ' + 'cfpresentation cfpresentationslide cfpresenter cfprint cfprocessingdirective cfprocparam cfprocresult ' + 'cfproperty cfquery cfqueryparam cfregistry cfreport cfreportparam cfrethrow cfreturn cfsavecontent cfschedule ' + 'cfscript cfsearch cfselect cfset cfsetting cfsilent cfslider cfsprydataset cfstoredproc cfswitch cftable ' + 'cftextarea cfthread cfthrow cftimer cftooltip cftrace cftransaction cftree cftreeitem cftry cfupdate cfwddx ' + 'cfwindow cfxml cfzip cfzipparam'; var operators = 'all and any between cross in join like not null or outer some'; this.regexList = [ { regex: new RegExp('--(.*)$', 'gm'), css: 'comments' }, // one line and multiline comments { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // single quoted strings { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // functions { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword ]; } Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['coldfusion','cf']; SyntaxHighlighter.brushes.ColdFusion = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
var jsc = require("jsverify"); const _ = require('lodash'); const mutil = require('../mock/mockutils.js'); const mapmov = require('../mock/mapmov.js'); const menv = require('../mock/mockenvironment.js'); const mt = require('mathjs'); const Stream = require("stream"); const streamers = require('../mock/streamers.js'); var assert = require('assert'); let np; let savePlot = false; if( savePlot ) { np = require('../mock/nplot.js'); } describe("mock environment", function () { it('accepts stream', (done) => { menv.reset(); // let feed = new MockReadable({highWaterMark:64}, 0.1); let r0_tx = new streamers.CF64StreamSin({}, {theta:0.1,count:3,chunk:16} ); let r0_rx = new streamers.F64CaptureStream({}); menv.attachRadio(r0_tx, r0_rx); let r1_tx = new streamers.CF64StreamSin({}, {theta:0.33,count:3,chunk:16} ); let r1_rx = new streamers.F64CaptureStream({}); menv.attachRadio(r1_tx, r1_rx); // let got_out0 = mapmov.accept(in0); // assert(_.isEqual(got_out0,ideal_out0)); setTimeout(() => { console.log("r0 got " + r0_rx.capture.length); let ascomplex0 = _.chunk(r0_rx.capture,2).map((e,i)=>mt.complex(e[0],e[1])); let asmag0 = ascomplex0.map((e,i)=>mt.abs(e)); let asreal0 = ascomplex0.map((e,i)=>e.re); if( savePlot ) { setTimeout(() => { np.plot(asreal0, "test_env_r0_out.png"); }, 0); } let ascomplex1 = _.chunk(r1_rx.capture,2).map((e,i)=>mt.complex(e[0],e[1])); let asmag1 = ascomplex1.map((e,i)=>mt.abs(e)); let asreal1 = ascomplex1.map((e,i)=>e.re); if( savePlot ){ setTimeout(() => { np.plot(asreal1, "test_env_r1_out.png"); }, 3000); } done(); }, 200); // done(); }); it('accepts gain stream', (done) => { menv.reset(); // let feed = new streamers.CF64StreamSin({highWaterMark:64}, 0.1); let r0_tx = new streamers.CF64StreamSin({}, {theta:0.1,count:3,chunk:16} ); let r0_rx = new streamers.F64CaptureStream({}); let r0_gain = new streamers.F64GainStream({}, {gain:2.0}); r0_tx.pipe(r0_gain); menv.attachRadio(r0_gain, r0_rx); let r1_tx = new streamers.CF64StreamSin({}, {theta:0.33,count:3,chunk:16} ); let r1_rx = new streamers.F64CaptureStream({}); menv.attachRadio(r1_tx, r1_rx); // let got_out0 = mapmov.accept(in0); // assert(_.isEqual(got_out0,ideal_out0)); setTimeout(() => { console.log("r0 got " + r0_rx.capture.length); let ascomplex0 = _.chunk(r0_rx.capture,2).map((e,i)=>mt.complex(e[0],e[1])); let asmag0 = ascomplex0.map((e,i)=>mt.abs(e)); let asreal0 = ascomplex0.map((e,i)=>e.re); if( savePlot ) { setTimeout(() => { np.plot(asreal0, "test_env_gain_r0_out.png"); }, 0); } let ascomplex1 = _.chunk(r1_rx.capture,2).map((e,i)=>mt.complex(e[0],e[1])); let asmag1 = ascomplex1.map((e,i)=>mt.abs(e)); let asreal1 = ascomplex1.map((e,i)=>e.re); if( savePlot ){ setTimeout(() => { np.plot(asreal1, "test_env_gain_r1_out.png"); }, 3000); } done(); }, 200); // done(); }); });
export default class UserNewViewModel { constructor(ctx) { this.user = ctx.user } }
// // Component <h1></h1> // import React from 'react'; /* eslint-disable react/prefer-stateless-function */ export default class H1 extends React.Component { render() { return ( <h1>{this.props.title}</h1> ); } } H1.propTypes = { title: React.PropTypes.string.isRequired, };
export default { a: 1, };
const Math = artifacts.require('Math') const CategoricalEvent = artifacts.require('CategoricalEvent') const ScalarEvent = artifacts.require('ScalarEvent') const OutcomeToken = artifacts.require('OutcomeToken') const EventFactory = artifacts.require('EventFactory') module.exports = function (deployer) { deployer.link(Math, EventFactory) deployer.deploy(EventFactory, CategoricalEvent.address, ScalarEvent.address, OutcomeToken.address) }
import { typeOf } from '@ember/utils'; import { A } from '@ember/array'; import DS from 'ember-data'; export default DS.JSONSerializer.extend({ /** * Invokes the new serializer API. * This should be removed in 2.0 */ isNewSerializerAPI: true, serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; var payloadKey = this.keyForRelationship ? this.keyForRelationship(key, "hasMany") : key; var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') { json[payloadKey] = snapshot.hasMany(key, { ids: true }); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** * Extracts whatever was returned from the adapter. * * If the adapter returns relationships in an embedded way, such as follows: * * ```js * { * "id": 1, * "title": "Rails Rambo", * * "_embedded": { * "comment": [{ * "id": 1, * "comment_title": "FIRST" * }, { * "id": 2, * "comment_title": "Rails is unagi" * }] * } * } * * this method will create separated JSON for each resource and then combine * the data and the embed payload into the JSON.Api spec for included objects * returning a single object. * * @method extractSingle * @private * @param {DS.Store} store the returned store * @param {DS.Model} type the type/model * @param {Object} payload returned JSON */ normalizeSingleResponse: function(store, type, payload) { var included = A([]); if (payload && payload._embedded) { var forEachFunc = (record) => { included.pushObject(this.normalize(relType,record).data); }; for (var relation in payload._embedded) { var relType = type.typeForRelationship(relation,store); var embeddedPayload = payload._embedded[relation]; if (embeddedPayload) { if (typeOf(embeddedPayload) === 'array') { embeddedPayload.forEach(forEachFunc); } else { included.pushObject(this.normalize(relType, embeddedPayload).data); } } } delete payload._embedded; } var normalPayload = this.normalize(type, payload); if(included.length > 0){ normalPayload.included = included; } return normalPayload; }, /** * This is exactly the same as extractSingle, but used in an array. * * @method extractSingle * @private * @param {DS.Store} store the returned store * @param {DS.Model} type the type/model * @param {Array} payload returned JSONs */ normalizeArrayResponse: function(store, type, payload) { var response = { data: A([]), included: A([]) }; payload.forEach((json) => { var normalized = this.normalizeSingleResponse(store, type, json); response.data.pushObject(normalized.data); if(normalized.included){ normalized.included.forEach(function(included){ if(!response.included.includes(included.id)){ response.included.addObject(included); } }); } }); return response; } });
const config = require("./config"); const bank_blocks = require("./bank_blocks"); module.exports = { config, bank_blocks };
// package metadata file for Meteor.js Package.describe({ name: 'materialize:materialize', // http://atmospherejs.com/materialize/materialize summary: 'Materialize (official): A modern responsive front-end framework based on Material Design', version: '0.99.0', git: 'https://github.com/Dogfalo/materialize.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('fourseven:scss@3.10.0'); api.use('jquery', 'client'); api.imply('jquery', 'client'); var assets = [ 'fonts/roboto/Roboto-Bold.woff', 'fonts/roboto/Roboto-Bold.woff2', 'fonts/roboto/Roboto-Light.woff', 'fonts/roboto/Roboto-Light.woff2', 'fonts/roboto/Roboto-Medium.woff', 'fonts/roboto/Roboto-Medium.woff2', 'fonts/roboto/Roboto-Regular.woff', 'fonts/roboto/Roboto-Regular.woff2', 'fonts/roboto/Roboto-Thin.woff', 'fonts/roboto/Roboto-Thin.woff2', ]; addAssets(api, assets); api.addFiles([ 'dist/js/materialize.js' ], 'client'); var scssFiles = [ 'sass/components/date_picker/_default.date.scss', 'sass/components/date_picker/_default.scss', 'sass/components/date_picker/_default.time.scss', 'sass/components/forms/_checkboxes.scss', 'sass/components/forms/_file-input.scss', 'sass/components/forms/_forms.scss', 'sass/components/forms/_input-fields.scss', 'sass/components/forms/_radio-buttons.scss', 'sass/components/forms/_range.scss', 'sass/components/forms/_select.scss', 'sass/components/forms/_switches.scss', 'sass/components/_badges.scss', 'sass/components/_buttons.scss', 'sass/components/_cards.scss', 'sass/components/_carousel.scss', 'sass/components/_chips.scss', 'sass/components/_collapsible.scss', 'sass/components/_color.scss', 'sass/components/_dropdown.scss', 'sass/components/_global.scss', 'sass/components/_grid.scss', 'sass/components/_icons-material-design.scss', 'sass/components/_materialbox.scss', 'sass/components/_mixins.scss', 'sass/components/_modal.scss', 'sass/components/_navbar.scss', 'sass/components/_normalize.scss', 'sass/components/_preloader.scss', 'sass/components/_pulse.scss', 'sass/components/_roboto.scss', 'sass/components/_sideNav.scss', 'sass/components/_slider.scss', 'sass/components/_table_of_contents.scss', 'sass/components/_tabs.scss', 'sass/components/_tapTarget.scss', 'sass/components/_toast.scss', 'sass/components/_tooltip.scss', 'sass/components/_transitions.scss', 'sass/components/_typography.scss', 'sass/components/_variables.scss', 'sass/components/_waves.scss', 'sass/materialize.scss' ]; api.addFiles(scssFiles, 'client'); api.export('Materialize', 'client'); }); function addAssets(api, assets){ if(api.addAssets){ api.addAssets(assets, 'client'); } else { api.addFiles(assets, 'client', {isAsset: true}); } }
import PiechartAjsModule from './piechartAjs' import PiechartAjsController from './piechartAjs.controller'; import PiechartAjsComponent from './piechartAjs.component'; import PiechartAjsTemplate from './piechartAjs.html'; describe('PiechartAjs', () => { let $rootScope, makeController; beforeEach(window.module(PiechartAjsModule)); beforeEach(inject((_$rootScope_) => { $rootScope = _$rootScope_; makeController = () => { return new PiechartAjsController(); }; })); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Component', () => { // component/directive specs let component = PiechartAjsComponent; it('includes the intended template',() => { expect(component.template).to.equal(PiechartAjsTemplate); }); }); });
(function ($) { "use strict"; var $document = $(document), $window = $(window), $body = $('body'), $html = $('html'), $ttPageContent = $('#tt-pageContent'), $ttFooter = $('footer'), $ttHeader = $('header'), $ttLeftColumnAside = $ttPageContent.find('.leftColumn.aside'), $ttFilterOptions = $ttPageContent.find('.tt-filters-options'), /* menu setting*/ header_menu_timeout = 200, header_menu_delay = 200, //header $ttTopPanel = $('.tt-top-panel'), //header stuck $stucknav = $ttHeader.find('.tt-stuck-nav'), //header menu $ttDesctopMenu = $ttHeader.find('.tt-desctop-menu'), $ttDesctopParentMenu = $ttHeader.find('.tt-desctop-parent-menu'), $ttMobileParentMenu = $ttHeader.find('.tt-mobile-parent-menu'), $ttMobileParentMenuChildren = $ttMobileParentMenu.children(), $ttStuckParentMenu = $ttHeader.find('.tt-stuck-parent-menu'), //header search $ttSearchObj = $ttHeader.find('.tt-search'), $ttDesctopParentSearch = $ttHeader.find('.tt-desctop-parent-search'), $ttMobileParentSearch = $ttHeader.find('.tt-mobile-parent-search'), $ttStuckParentSearch = $ttHeader.find('.tt-stuck-parent-search'), $ttSearchObjPopupInput = $ttSearchObj.find('.tt-search-input'), $ttSearchObjPopupResults = $ttSearchObj.find('.search-results'), //header cart $ttcartObj = $ttHeader.find('.tt-cart'), $ttDesctopParentCart = $ttHeader.find('.tt-desctop-parent-cart'), $ttMobileParentCart = $ttHeader.find('.tt-mobile-parent-cart'), $ttStuckParentCart = $ttHeader.find('.tt-stuck-parent-cart'), //header account $ttAccountObj = $ttHeader.find('.tt-account'), $ttDesctopParentAccount = $ttHeader.find('.tt-desctop-parent-account'), $ttMobileParentAccount = $ttHeader.find('.tt-mobile-parent-account'), $ttStuckParentAccount = $ttHeader.find('.tt-stuck-parent-account'), //header langue and currency(*all in one module) $ttMultiObj = $ttHeader.find('.tt-multi-obj'), $ttDesctopParentMulti = $ttHeader.find('.tt-desctop-parent-multi'), $ttMobileParentMulti = $ttHeader.find('.tt-mobile-parent-multi'), $ttStuckParentMulti = $ttHeader.find('.tt-stuck-parent-multi'), // Template Blocks blocks = { ttCalendarDatepicker: $ttPageContent.find('.calendarDatepicker'), ttSliderBlog: $ttPageContent.find('.tt-slider-blog'), ttSliderBlogSingle: $ttPageContent.find('.tt-slider-blog-single'), ttVideoBlock: $('.tt-video-block'), ttBlogMasonry: $ttPageContent.find('.tt-blog-masonry'), ttPortfolioMasonry: $ttPageContent.find('.tt-portfolio-masonry'), ttProductMasonry: $ttPageContent.find('.tt-product-listing-masonry'), ttLookBookMasonry: $ttPageContent.find('.tt-lookbook-masonry'), // ttInputCounter: $('.tt-input-counter'), ttCollapseBlock: $('.tt-collapse-block'), modalVideoProduct: $('#modalVideoProduct'), modalAddToCart: $('#modalAddToCartProduct'), ttMobileProductSlider: $('.tt-mobile-product-slider'), ttCollapse: $ttPageContent.find('.tt-collapse'), ttProductListing: $ttPageContent.find('.tt-product-listing'), ttCountdown: $ttPageContent.find('.tt-countdown'), ttBtnColumnClose: $ttLeftColumnAside.find('.tt-btn-col-close'), ttBtnToggle: $ttFilterOptions.find('.tt-btn-toggle a'), ttBtnAddProduct: $ttPageContent.find('.tt_product_showmore'), ttOptionsSwatch: $ttPageContent.find('.tt-options-swatch'), ttProductItem: $ttPageContent.find('.tt-product, .tt-product-design02'), ttProductDesign02: $ttPageContent.find('.tt-product-design02'), ttProductDesign01: $ttPageContent.find('.tt-product'), ttFilterDetachOption: $ttLeftColumnAside.find('.tt-filter-detach-option'), ttFilterSort: $ttFilterOptions.find('.tt-sort'), ttShopCart: $ttPageContent.find('.tt-shopcart-table, .tt-shopcart-table-02'), ttSliderLookbook: $ttPageContent.find('.tt-slider-lookbook'), ttCaruselLookbook: $ttPageContent.find('.tt-carousel-lookbook'), ttPortfolioContent: $ttPageContent.find('.tt-portfolio-content'), ttLookbook: $ttPageContent.find('.tt-lookbook'), ttAirSticky: $ttPageContent.find('.airSticky'), ttfooterMobileCollapse: $ttFooter.find('.tt-collapse-title'), ttBackToTop: $('.tt-back-to-top'), ttHeaderDropdown: $ttHeader.find('.tt-dropdown-obj'), mobileMenuToggle: $('.tt-menu-toggle'), ttCarouselProducts: $('.tt-carousel-products'), ttSliderFullwidth: $('.tt-slider-fullwidth'), ttCarouselBrands: $('.tt-carousel-brands'), sliderRevolution: $('.slider-revolution'), ttItemsCategories: $ttPageContent.find('.tt-items-categories'), ttDotsAbsolute: $ttPageContent.find('.tt-dots-absolute'), ttAlignmentImg: $ttPageContent.find('.tt-alignment-img'), ttModalQuickView: $('#ModalquickView'), ttProductSingleBtnZomm: $ttPageContent.find('.tt-product-single-img .tt-btn-zomm'), ttPromoFixed: $('.tt-promo-fixed'), // main slider "Slick" - full height and full width (* index-slick-slider.html) mainSliderSlick: $('.mainSliderSlick'), // main slider "Slick" - full width and container (* index-slick-slider.html) ttSlickSlider: $ttPageContent.find('.tt-slick-slider'), }; var ttwindowWidth = window.innerWidth || $window.width(); // main slider "Slick" - full height and full width (* index-slick-slider.html) if (blocks.mainSliderSlick.length) { mainSliderSlick(); dataBg('[data-bg]'); }; function mainSliderSlick() { var $el = blocks.mainSliderSlick; $el.find('.slide').first().imagesLoaded({ background: true }, function () { setTimeout(function () { $el.parent().find('.loading-content').addClass('disable'); }, 1200); }); $el.on('init', function (e, slick) { var $firstAnimatingElements = $('div.slide:first-child').find('[data-animation]'); doAnimations($firstAnimatingElements); }); $el.on('beforeChange', function (e, slick, currentSlide, nextSlide) { var $currentSlide = $('div.slide[data-slick-index="' + nextSlide + '"]'); var $animatingElements = $currentSlide.find('[data-animation]'); doAnimations($animatingElements); }); $el.slick({ arrows: false, dots: true, autoplay: true, autoplaySpeed: 5500, fade: true, speed: 1000, pauseOnHover: false, pauseOnDotsHover: true, responsive: [{ breakpoint: 1025, settings: { dots: false, arrows: true } }] }); }; function doAnimations(elements) { var animationEndEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; elements.each(function () { var $this = $(this); var $animationDelay = $this.data('animation-delay'); var $animationType = 'animated ' + $this.data('animation'); $this.css({ 'animation-delay': $animationDelay, '-webkit-animation-delay': $animationDelay }); $this.addClass($animationType).one(animationEndEvents, function () { $this.removeClass($animationType); }); if ($this.hasClass('animate')) { $this.removeClass('animation'); } }); }; function dataBg(el) { $(el).each(function () { var $this = $(this), bg = $this.attr('data-bg'); $this.css({ 'background-image': 'url(' + bg + ')' }); }); }; // main slider "Slick" - full width and container (* index-slick-slider.html) if (blocks.ttSlickSlider.length) { blocks.ttSlickSlider.slick({ dots: true, arrows: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true, responsive: [{ breakpoint: 1025, settings: { dots: false, } }] }); }; // for demo var tooltip = { html_i: '#tt-tooltip-popup', html_s: '<div id="tt-tooltip-popup"><span>', html_e: '</span><i></i></div>', tp_attr: '[data-tooltip]', tp_mod: false, init: function () { this.tp_mod = this.get_tp_mod(); if (!this.tp_mod.length || /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) return false; this.handler(); }, get_tp_attr: function () { return this.tp_attr; }, get_tp_mod: function () { return $(this.get_tp_attr()); }, get_w_width: function () { return window.innerWidth || $window.width(); }, get_html_obj: function (name) { return this.html_s + name + this.html_e; }, check_pr_page_swatches: function ($obj) { var swc = $obj.closest('.tt-swatches-container'); var search = $obj.closest('.tt-search'); var qv = $obj.closest('.tt-btn-quickview'); var cc = $obj.closest('.tt-collapse-content'); var wl = $obj.closest('.wlbutton-js'); if (!swc.length && !search.length && !qv.length && !cc.length && !wl.length) return false; return true; }, handler: function () { var _ = this; $('body').on('mouseenter mouseleave', this.get_tp_attr(), function (e) { var ww = _.get_w_width(); if (ww <= 1024) return false; //var $stnav = $(this).closest('.tt-stuck-nav'); //if($stnav.length == 1 && $stnav.hasClass('stuck')) return false; if (e.type === 'mouseenter') _.onHover($(this)); if (e.type === 'mouseleave') _.offHover($(this)); }); }, onHover: function ($obj) { var _ = this, value = $obj.attr('data-tooltip'), $o = $(this.get_html_obj(value)), tposition = $obj.attr('data-tposition'), ftag = $obj.attr('data-findtag'); if (value == "") return false; $body.append($o); var $objforsize = typeof ftag != 'undefined' ? $obj.find(ftag).first() : $obj, th = $o.innerHeight(), tw = $o.innerWidth(), oh = $objforsize.innerHeight(), ow = $objforsize.innerWidth(), v = $objforsize.offset().top, h = $objforsize.offset().left; tposition = typeof tposition != 'undefined' ? tposition : 'top'; if (tposition == 'top') { v += -th - 20; h += parseInt((ow - tw) / 2); } if (tposition == 'bottom') { v += oh + 24; h += parseInt((ow - tw) / 2); } if (tposition == 'left') { v += parseInt((oh - th) / 2); h += -tw - 24; } if (tposition == 'right') { v += parseInt((oh - th) / 2); h += ow + 24; } this.showTooltip($o, h, v, tposition); if (!this.check_pr_page_swatches($obj)) return false; $obj.on('click.closeTooltip', function () { _.offHover($(this)); $(this).unbind("click.closeTooltip"); }) }, offHover: function ($obj) { $body.find(this.html_i).remove(); if (!this.check_pr_page_swatches($obj)) return false; $obj.unbind("click.closeTooltip"); }, showTooltip: function ($o, h, v, tposition) { var a = { opacity: 1 }, k = tposition; if (k == 'bottom') k = 'top'; if (k == 'right') k = 'left'; a[k] = tposition == 'bottom' || tposition == 'right' ? '-=10px' : '+=10px'; $o.css({ 'top': v, 'left': h }).addClass('tooltip-' + tposition).animate(a, 200); } } tooltip.init(); // wishlist var jsWishlistRemoveitem = $('#js-wishlist-removeitem'); if (jsWishlistRemoveitem.length) { jsWishlistRemoveitem.on('click', '.js-removeitem', function () { $(this).closest('.tt-item').remove(); }); }; // lazyLoad (function () { new LazyLoad(); new LazyLoad({ elements_selector: "iframe" }); new LazyLoad({ elements_selector: "video" }); }()); //compare (*compare.html) var ttCompareTable = $('#tt-compare-table'); if (ttCompareTable.length) { //product quantity var ttCompareItemCount = ttCompareTable.find('.tt-item').size(); if (ttCompareItemCount > 0) { $('#tt-compare-countitem').html(ttCompareItemCount); }; //slider init ttCompareTable.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 1, adaptiveHeight: true, responsive: [{ breakpoint: 1025, settings: { slidesToShow: 2, } }, { breakpoint: 410, settings: { slidesToShow: 1 } } ] }); //the need for an indent var ttCompareSlickBtn = ttCompareTable.find('.slick-arrow').size(); if (ttCompareSlickBtn > 0) { ttCompareTable.addClass('slick-init'); }; //remove item after click ttCompareTable.on('click', '.js-remove-item', function () { $(this).closest('.tt-item').remove(); }); // alignmentColHeight(); $window.on('load', function () { alignmentColHeight(); }); $window.resize(debouncer(function (e) { alignmentColHeight(); })); }; function alignmentColHeight() { var ttwindowWidth = window.innerWidth || $window.width(); if (ttwindowWidth > 409) { calculatingMaxHeight(ttCompareTable.find('.tt-item .js-description')); calculatingMaxHeight(ttCompareTable.find('.tt-item .tt-image-box')); calculatingMaxHeight(ttCompareTable.find('.tt-item')); } else { ttCompareTable.find('.tt-item .js-description').css("height", "auto"); ttCompareTable.find('.tt-item .tt-image-box').css("height", "auto"); }; }; function calculatingMaxHeight($obj) { var maxHeight = 0; $obj.css("height", "auto").each(function () { $(this).css("height", "auto"); var colHeight = $(this).height(); if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }; }); $obj.height(maxHeight); }; //compare (compare-02.html) var ttCompareTable02 = $('#tt-compare-table02'), compareInitSlider02 = ttCompareTable02.find('.compare-init-slider'); if (ttCompareTable02.length && compareInitSlider02.length) { (function () { //slider init compareInitSlider02.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 1, adaptiveHeight: true, responsive: [{ breakpoint: 1025, settings: { slidesToShow: 2, } }, { breakpoint: 790, settings: { slidesToShow: 1 } } ] }); $window.on('ready, load', function () { initalignmentTable(); }); $window.resize(debouncer(function (e) { initalignmentTable(); })); function initalignmentTable() { var place01 = ttCompareTable02.find('.tt-col-title'), place02 = ttCompareTable02.find('.tt-col-item'), place01TotalElement = place01.find('> div').size(), place02TotalElement = place02.find('.tt-item:first-child > div').size(); if (place01TotalElement === place02TotalElement) { var i = 1; while (i <= place01TotalElement) { var keyword = "js_one-height-0" + i; i++; calculatingMaxHeight(keyword); } }; function calculatingMaxHeight($obj) { var getObj = ttCompareTable02.find('.' + $obj); var maxHeight = 0; getObj.css("height", "auto").each(function () { $(this).css("height", "auto"); var colHeight = $(this).height(); if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }; }); getObj.height(maxHeight); }; }; }()); }; //instafeed $.fn.func_instafeed = function (new_obj) { var $this = $(this), $accessToken = $(this).attr('data-accessToken'), $clientId = $(this).attr('data-clientId'), $userId = $(this).attr('data-userId'), $limitImg = $(this).attr('data-limitImg'); if (!$this.length) return; var new_obj = new_obj || {}, set_obj = { get: 'user', userId: $userId, clientId: $clientId, limit: $limitImg, sortBy: 'most-liked', resolution: "standard_resolution", accessToken: $accessToken, template: '<a href="{{link}}" target="_blank"><img src="{{image}}" /></a>', }; $.extend(set_obj, new_obj); var feed = new Instafeed(set_obj); feed.run(); }; $('#instafeed').each(function () { $(this).func_instafeed(); }); // header, search, at focus input - result of search if ($ttSearchObjPopupInput.length && $ttSearchObjPopupResults.length) { $ttSearchObj.on("input", function (ev) { if ($(ev.target).val()) { $ttSearchObjPopupResults.fadeIn("200"); }; }); $ttSearchObjPopupInput.blur(function () { $ttSearchObjPopupResults.fadeOut("200"); }); }; if (blocks.ttPromoFixed.length) { setTimeout(function () { blocks.ttPromoFixed.fadeTo("90", 1); }, 2300); blocks.ttPromoFixed.on('click', '.tt-btn-close', function () { $(this).closest('.tt-promo-fixed').hide(); }); }; if (blocks.sliderRevolution.length) { sliderRevolution(); }; if (blocks.ttItemsCategories.length) { ttItemsCategories(); }; if (blocks.modalAddToCart.length) { modalAddToCart(); }; // Mobile Menu if (blocks.mobileMenuToggle.length) { blocks.mobileMenuToggle.initMM({ enable_breakpoint: true, mobile_button: true, breakpoint: 1025, menu_class: 'mobile-main-menu' }); }; //header top panel if ($ttTopPanel.length) { ttTopPanel(); }; // add product item if (blocks.ttBackToTop.length) { ttBackToTop(); }; // add product item if (blocks.ttBtnAddProduct.length) { ttAddProduct(); }; // switching click if (blocks.ttOptionsSwatch.length) { initSwatch(blocks.ttOptionsSwatch); }; // switching click product item(*wishlist, *compare) if (blocks.ttProductItem.length) { var ttBtnWishlist = blocks.ttProductItem.find(".tt-btn-wishlist"), ttBtnCompare = blocks.ttProductItem.find(".tt-btn-compare"); if (ttBtnWishlist.length) { ttBtnWishlist.on('click', function () { $(this).toggleClass('active'); return false; }); }; if (ttBtnCompare.length) { ttBtnCompare.on('click', function () { $(this).toggleClass('active'); return false; }); }; }; // Slide Column *listing-left-column.html if ($ttLeftColumnAside && blocks.ttBtnColumnClose && blocks.ttBtnToggle) { ttToggleCol(); }; //countDown if (blocks.ttCountdown.length) { ttCountDown(true); }; // collapseBlock if (blocks.ttCollapse.length) { ttCollapse(); }; //modal video on page product if (blocks.modalVideoProduct.length) { ttVideoPopup(); }; //tt-collapse-block(pages product single) if (blocks.ttCollapseBlock.length) { ttCollapseBlock(); }; //calendarDatepicker(blog) if (blocks.ttCalendarDatepicker.length) { blocks.ttCalendarDatepicker.datepicker(); }; //video(blog listing) if (blocks.ttVideoBlock.length) { ttVideoBlock(); }; // determination ie if (getInternetExplorerVersion() !== -1) { $html.addClass("ie"); }; // inputCounter /* if (blocks.ttInputCounter.length) { ttInputCounter(); }; */ // header initStuck(); if ($ttDesctopParentSearch.length) { mobileParentSearch(); }; if ($ttcartObj.length) { mobileParentCart(); }; if ($ttDesctopParentAccount.length) { mobileParentAccount(); }; if ($ttDesctopParentMulti.length) { mobileParentMulti(); }; // product item Design01 if (blocks.ttProductDesign01.length) { ttProductHover(); }; if (blocks.ttfooterMobileCollapse.length) { ttFooterCollapse(); }; // lookbook.html if (blocks.ttLookbook.length) { ttLookbook(ttwindowWidth); }; // shopping_cart.html if (blocks.ttShopCart.length) { ttShopCart(ttwindowWidth); }; // slider fullwidth content(*index-07.html) if (blocks.ttSliderFullwidth.length) { blocks.ttSliderFullwidth.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true }); }; // carousel brandsh content(*index-07.html) if (blocks.ttCarouselBrands.length) { blocks.ttCarouselBrands.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 8, slidesToScroll: 1, adaptiveHeight: true, responsive: [{ breakpoint: 1230, settings: { slidesToShow: 6, } }, { breakpoint: 1025, settings: { slidesToShow: 4, } }, { breakpoint: 790, settings: { slidesToShow: 3 } }, { breakpoint: 576, settings: { slidesToShow: 2 } }, { breakpoint: 380, settings: { slidesToShow: 1 } } ] }); }; // carusel if (blocks.ttCarouselProducts.length) { blocks.ttCarouselProducts.each(function () { var pathname = window.location.pathname; var route = pathname.split("/"); /** Mi código */ if (route[1] != 'producto') { var slick = $(this), item = $(this).data('item'); slick.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: item || 4, slidesToScroll: item || 4, adaptiveHeight: true, responsive: [{ breakpoint: 1025, settings: { slidesToShow: 3, slidesToScroll: 3 } }, { breakpoint: 791, settings: { slidesToShow: 2, slidesToScroll: 2 } } ] }); } }); }; // lookbook.html // slider if (blocks.ttSliderLookbook.length) { blocks.ttSliderLookbook.slick({ dots: true, arrows: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true }); }; // carusel if (blocks.ttCaruselLookbook.length) { blocks.ttCaruselLookbook.slick({ dots: true, arrows: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 3, adaptiveHeight: true, responsive: [{ breakpoint: 1025, settings: { slidesToShow: 2, slidesToScroll: 2 } }, { breakpoint: 790, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); }; //blog listing slider if (blocks.ttMobileProductSlider.length) { blocks.ttMobileProductSlider.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true, lazyLoad: 'progressive', }); if ($html.hasClass('ie')) { blocks.ttModalQuickView.each(function () { blocks.ttMobileProductSlider.slick("slickSetOption", "infinite", false); }); }; }; //blog listing slider if (blocks.ttSliderBlog.length) { blocks.ttSliderBlog.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true }); }; //blog single post slider if (blocks.ttSliderBlogSingle.length) { blocks.ttSliderBlogSingle.slick({ dots: false, arrows: false, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true }); //total slides var ttSlickQuantity = $('.tt-slick-quantity'); if (ttSlickQuantity.length) { ttSlickQuantity.find('.total').html(blocks.ttSliderBlogSingle.slick("getSlick").slideCount); blocks.ttSliderBlogSingle.on('afterChange', function (event, slick, currentSlide) { var currentIndex = $('.slick-current').attr('data-slick-index'); currentIndex++; ttSlickQuantity.find('.account-number').html(currentIndex); }); }; //button var ttSlickButton = $('.tt-slick-button'); if (ttSlickButton.length) { ttSlickButton.find('.slick-next').on('click', function (e) { blocks.ttSliderBlogSingle.slick('slickNext'); }); ttSlickButton.find('.slick-prev').on('click', function (e) { blocks.ttSliderBlogSingle.slick('slickPrev'); }); }; }; //ttOptionsSwatch function initSwatch($obj) { $obj.each(function () { var $this = $(this), jsChangeImg = $this.hasClass('js-change-img'), optionsColorImg = $this.find('.options-color-img'); $this.on('click', 'li', function (e) { var $this = $(this); $this.addClass('active').siblings().removeClass('active'); if (jsChangeImg) { addImg($this); }; return false; }); if (optionsColorImg.length) { addBg(optionsColorImg); }; }); }; function addBg(optionsColorImg) { $(optionsColorImg).each(function () { $(this).css({ 'background-image': 'url(' + $(this).attr('data-src') + ')' }); }); }; function addImg($this) { var $objData = $this.find('.options-color-img'), $objDataImg = $objData.attr('data-src'), $objDataImgHover = $objData.attr('data-src-hover') || false, $objImgWrapper = $this.closest('.tt-product').find('.tt-image-box'), $objImgMain = $objImgWrapper.find('.tt-img img'), $objImgMainHover = $objImgWrapper.find('.tt-img-roll-over img'); //change imgMain if ($objDataImg.length) { $objImgMain.attr('src', $objDataImg); }; //change imgRollOvernHover if ($objDataImg.length) { var checkDisable = $objImgMainHover.closest('.tt-img-roll-over'); $objImgMainHover.attr('src', $objDataImgHover); if (checkDisable.hasClass('disable')) { checkDisable.removeClass('disable'); }; }; if ($objDataImgHover === false) { $objImgMainHover.closest('.tt-img-roll-over').addClass('disable'); }; }; // portfolio mobile click if (blocks.ttPortfolioContent.length && is_touch_device()) { ttPortfolioContentMobile(); }; //ttAddProduct function ttAddProduct() { var isotopShowmoreJs = $('.tt_product_showmore .btn'), ttAddItem = $('.tt-product-listing'); if (isotopShowmoreJs.length && ttAddItem.length) { isotopShowmoreJs.on('click', function (e) { e.preventDefault(); $.ajax({ url: 'ajax_product.php', success: function (data) { var $item = $(data); ttAddItem.append($item); ttProductSmall(); adjustOffset(); } }); function adjustOffset() { var offsetLastItem = ttAddItem.children().last().children().offset().top - 80; $($body, $html).animate({ scrollTop: offsetLastItem }, 500); }; return false; }); }; }; if (blocks.ttDotsAbsolute.length) { ttSlickDots(); }; //sticky(product-05.html) if (blocks.ttAirSticky.length) { ttAirSticky(ttwindowWidth); }; // header - tt-dropdown-obj if (blocks.ttHeaderDropdown.length) { ttHeaderDropdown(); }; // product single tt-btn-zomm(*magnific popup) if (blocks.ttProductSingleBtnZomm.length) { ttProductSingleBtnZomm(); }; setTimeout(function () { $body.addClass('loaded'); }, 1500); $window.on('load', function () { var ttwindowWidth = window.innerWidth || $window.width(); if ($body.length) { $body.addClass('loaded'); }; // filters options product(definition layout) if ($ttFilterOptions.length) { ttFilterLayout(ttwindowWidth); }; if (blocks.ttProductItem.length) { ttProductSmall(ttwindowWidth); }; if (blocks.ttProductDesign02.length) { ttOverflowProduct(); }; // centering arrow if (blocks.ttAlignmentImg.length) { alignmentArrowValue(); }; if (blocks.ttProductMasonry.length) { gridProductMasonr(); }; if (blocks.ttLookBookMasonry.length) { gridLookbookMasonr(); }; if (blocks.ttBlogMasonry.length) { gridGalleryMasonr(); }; if (blocks.ttPortfolioMasonry.length) { gridPortfolioMasonr(); initPortfolioPopup(); }; }); var ttCachedWidth = $window.width(); $window.on('resize', function () { var newWidth = $window.width(); if (newWidth !== ttCachedWidth) { ttCachedWidth = newWidth; var ttwindowWidth = window.innerWidth || $window.width(); // shopping_cart.html if (blocks.ttShopCart.length) { ttShopCart(ttwindowWidth); }; // filters options product(definition layout) if ($ttFilterOptions.length) { ttFilterLayout(ttwindowWidth); }; if (blocks.ttProductItem.length) { ttProductSmall(); }; if (blocks.ttProductDesign02.length) { ttOverflowProduct(); }; // portfolio mobile click if (blocks.ttPortfolioContent.length && is_touch_device()) { ttPortfolioContentMobile(); }; //sticky(product-05.html) if (blocks.ttAirSticky.length) { ttAirSticky(ttwindowWidth); }; if ($ttLeftColumnAside.hasClass('column-open') && $ttLeftColumnAside.length) { $ttLeftColumnAside.find('.tt-btn-col-close a').trigger('click'); }; //header init stuck and detach if ($ttDesctopParentSearch.length) { mobileParentSearch(); }; if ($ttcartObj.length) { mobileParentCart(); }; if ($ttDesctopParentAccount.length) { mobileParentAccount(); }; if ($ttDesctopParentMulti.length) { mobileParentMulti(); }; if (blocks.ttDotsAbsolute.length) { ttSlickDots(); }; // centering arrow if (blocks.ttAlignmentImg.length) { alignmentArrowValue(); }; } }); // Functions var cssFix = function () { var u = navigator.userAgent.toLowerCase(), is = function (t) { return (u.indexOf(t) != -1) }; $html.addClass([ (!(/opera|webtv/i.test(u)) && /msie (\d)/.test(u)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? 'gecko ff2' : is('firefox/3') ? 'gecko ff3' : is('gecko/') ? 'gecko' : is('opera/9') ? 'opera opera9' : /opera (\d)/.test(u) ? 'opera opera' + RegExp.$1 : is('konqueror') ? 'konqueror' : is('applewebkit/') ? 'webkit safari' : is('mozilla/') ? 'gecko' : '', (is('x11') || is('linux')) ? ' linux' : is('mac') ? ' mac' : is('win') ? ' win' : '' ].join('')); }(); function ttTopPanel() { $ttTopPanel.on('click', function (e) { e.preventDefault; var target = e.target; if ($('.tt-btn-close').is(target)) { $(this).slideUp(200); }; }); }; //tabs init carusel $('a[data-toggle="tab"]').length && $('body').on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) { $('.slick-slider').each(function () { $(this).slick("getSlick").refresh(); }); if (blocks.ttAlignmentImg.length) { alignmentArrowValue(); }; }); $('.modal').on('shown.bs.modal', function (e) { var objSlickSlider = $(this).find('.slick-slider'); if (objSlickSlider.length) { objSlickSlider.each(function () { $(this).slick("getSlick").refresh(); }); }; }); function ttItemsCategories() { blocks.ttItemsCategories.on('hover', function () { $(this).toggleClass('active'); }); }; function ttHeaderDropdown() { var dropdownPopup = $('.header-popup-bg'); if (!dropdownPopup.length) { $body.append('<div class="header-popup-bg"></div>'); }; $('header').on('click', '.tt-dropdown-obj', function (e) { var ttwindowWidth = window.innerWidth || $window.width(), $this = $(this), target = e.target, objSearch = $('.tt-search'), objSearchInput = objSearch.find('.tt-search-input'); // search if ($this.hasClass('tt-search') && $('.tt-dropdown-toggle').is(target)) { searchPopup(); }; function searchPopup() { $this.addClass('active'); objSearchInput.focus(); return false; }; if (objSearch.find('.tt-btn-close').is(target)) { objSearchClose(); return false; }; function objSearchClose() { $this.removeClass('active'); objSearchInput.blur(); return false; }; // cart, account, multi-ob if (!$(this).hasClass('tt-search') && $('.tt-dropdown-toggle').is(target)) { ttwindowWidth <= 1024 ? popupObjMobile($this) : popupObjDesctop($this); }; function popupObjMobile(obj) { $('header').find('.tt-dropdown-obj.active').removeClass('active'); obj.toggleClass('active').find('.tt-dropdown-menu').removeAttr("style"); $body.toggleClass('tt-popup-dropdown'); }; function popupObjDesctop(obj) { var $this = obj, target = e.target; if ($this.hasClass('active')) { $this.toggleClass('active').find('.tt-dropdown-menu').slideToggle(200); return; }; $('.tt-desktop-header .tt-dropdown-obj').each(function () { var $this = $(this); if ($this.hasClass('active')) { $this.removeClass('active').find('.tt-dropdown-menu').css("display", "none"); } }); if ($('.tt-dropdown-toggle').is(target)) { toggleDropdown($this); }; }; function toggleDropdown(obj) { obj.toggleClass('active').find('.tt-dropdown-menu').slideToggle(200); }; $(document).mouseup(function (e) { var ttwindowWidth = window.innerWidth || $window.width(); if (!$this.is(e.target) && $this.has(e.target).length === 0) { $this.each(function () { if ($this.hasClass('active') && $this.hasClass('tt-search')) { objSearch.find('.tt-btn-close').trigger('click'); }; if ($this.hasClass('active') && !$this.hasClass('tt-search')) { if (ttwindowWidth <= 1024) { closeObjPopupMobile(); } else { $('.tt-dropdown-obj').each(function () { if ($(this).hasClass('active')) { $(this).removeClass('active').find('.tt-dropdown-menu').css("display", "none"); } }); }; }; }); }; if ($this.find('.tt-mobile-add .tt-close').is(e.target)) { closeObjPopupMobile(); }; }); function closeObjPopupMobile() { $('.tt-dropdown-obj.active').removeClass('active'); $body.removeClass('tt-popup-dropdown'); return false; }; }); }; // button back to top function ttBackToTop() { blocks.ttBackToTop.on('click', function (e) { $('html, body').animate({ scrollTop: 0 }, 500); return false; }); $window.scroll(function () { $window.scrollTop() > 500 ? blocks.ttBackToTop.stop(true.false).addClass('tt-show') : blocks.ttBackToTop.stop(true.false).removeClass('tt-show'); }); }; // modal Add ToCart(*close) function modalAddToCart() { blocks.modalAddToCart.on('click', '.btn-close-popup', function (e) { $(this).closest('.modal-content').find('.modal-header .close').trigger('click'); return false; }); }; // Mobile footer collapse function ttFooterCollapse() { blocks.ttfooterMobileCollapse.on('click', function (e) { e.preventDefault; $(this).toggleClass('tt-open'); }); }; //slick slider functional for dots function ttSlickDots() { blocks.ttDotsAbsolute.each(function () { var $this = $(this).find('.slick-dots'); if ($this.is(':visible')) { var upperParent = $this.closest('[class ^= container]'); if (upperParent.length) { upperParent.css({ 'paddingBottom': parseInt($this.height(), 10) + parseInt($this.css('marginTop'), 10) }); } } }); }; // product item Design01 hover (*desctope) function ttProductHover() { $document.on('mouseenter mouseleave click', '#tt-pageContent .tt-product:not(.tt-view)', function (e) { var $this = $(this), windW = window.innerWidth, objLiftUp01 = $this.find('.tt-description'), objLiftUp02 = $this.find('.tt-product-inside-hover'), objHeight02 = objLiftUp02.height(), objCountdown = $this.find('.tt-countdown_box'), target = e.target; if ($this.hasClass('product-nohover')) return; if (e.type === 'mouseenter' && windW > 1024) { ttOnHover(); } else if (e.type === 'mouseleave' && e.relatedTarget && windW > 1024) { ttOffHover(); }; function ttOnHover(e) { $this.stop().css({ height: $this.innerHeight() }).addClass('hovered'); objLiftUp01.stop().animate({ 'top': '-' + objHeight02 }, 200); objLiftUp02.stop().animate({ 'opacity': 1 }, 400); objCountdown.stop().animate({ 'bottom': objHeight02 }, 200); return false; }; function ttOffHover(e) { $this.stop().removeClass('hovered').removeAttr('style'); objLiftUp01.stop().animate({ 'top': '0' }, 200, function () { $(this).removeAttr('style') }); objLiftUp02.stop().animate({ 'opacity': 0 }, 100, function () { $(this).removeAttr('style') }); objCountdown.stop().animate({ 'bottom': 0 }, 200, function () { $(this).removeAttr('style') }); return false }; }); }; // shopping_cart.html function ttShopCart(ttwindowWidth) { ttwindowWidth <= 789 ? insertDesctopeObj() : insertMobileObj(); function insertDesctopeObj() { blocks.ttShopCart.find('tr').each(function () { var objDesctope = $(this).find('.detach-quantity-desctope .tt-input-counter').detach().get(0); $(this).find('.detach-quantity-mobile').append(objDesctope); }); }; function insertMobileObj() { blocks.ttShopCart.find('tr').each(function () { var objMobile = $(this).find('.detach-quantity-mobile .tt-input-counter').detach().get(0); $(this).find('.detach-quantity-desctope').append(objMobile); }); }; }; // product Small function ttProductSmall() { var currentW = parseInt(blocks.ttProductItem.width(), 10), objProduct = $(".tt-product-design02"); currentW <= 210 ? objProduct.addClass("tt-small") : objProduct.removeClass("tt-small"); }; function debouncer(func, timeout) { var timeoutID, timeout = timeout || 500; return function () { var scope = this, args = arguments; clearTimeout(timeoutID); timeoutID = setTimeout(function () { func.apply(scope, Array.prototype.slice.call(args)); }, timeout); } }; // centering arrow function alignmentArrowValue() { var ttwindowWidth = window.innerWidth || $window.width(); if (ttwindowWidth > 1024) { setTimeout(function () { blocks.ttAlignmentImg.each(function () { $(this).find('.slick-arrow').removeAttr("style"); }); }, 225); } else { setTimeout(function () { blocks.ttAlignmentImg.each(function () { var ttObj = $(this), $objParentArrow = ttObj.find('.slick-arrow'); if (ttObj.find('.tt-image-box').length == 0 || $objParentArrow.length == 0) return; var $obj = ttObj.find('.tt-image-box').first(); $objParentArrow.css({ 'top': $obj.findHeight() - $objParentArrow.findHeight() - parseInt(ttObj.css('marginTop'), 10) + 'px' }); ttObj.find('.tt-product').length && ttProductSmall(); }); }, 225); }; }; $.fn.findHeight = function () { var $blocks = $(this), maxH = $blocks.eq(0).innerHeight(); $blocks.each(function () { maxH = ($(this).innerHeight() > maxH) ? $(this).innerHeight() : maxH; }); return maxH / 2; }; // tt-hotspot function ttLookbook(ttwindowWidth) { //add lookbook popup var objPopup = $('.tt-lookbook-popup'); if (!objPopup.length) { $body.append('<div class="tt-lookbook-popup"><div class="tt-lookbook-container"></div></div>'); }; blocks.ttLookbook.on('click', '.tt-hotspot', function (e) { var $this = $(this), target = e.target, ttHotspot = $('.tt-hotspot'), ttwindowWidth = window.innerWidth || $window.width(), ttCenterBtn = $('.tt-btn').innerHeight() / 2, ttWidthPopup = $('.tt-hotspot-content').innerWidth(); ttwindowWidth <= 789 ? ttLookbookMobile($this) : ttLookbookDesktop($this); //ttLookbookDesktop function ttLookbookDesktop($this) { if ($this.hasClass('active')) return; var objTop = $this.offset().top + ttCenterBtn, objLeft = $this.offset().left, objContent = $this.find('.tt-hotspot-content').detach(); //check if an open popup var checkChildren = $('.tt-lookbook-container').children().size(); if (checkChildren > 0) { if (ttwindowWidth <= 789) { closePopupMobile(); } else { closePopupDesctop(); }; } //open popup popupOpenDesktop(objContent, objTop, objLeft); }; function popupOpenDesktop(objContent, objTop, objLeft) { //check out viewport(left or right) var halfWidth = ttwindowWidth / 2, objLeftFinal = 0; if (halfWidth < objLeft) { objLeftFinal = objLeft - ttWidthPopup - 7; popupShowLeft(objLeftFinal); } else { objLeftFinal = objLeft + 45; popupShowRight(objLeftFinal); }; $('.tt-lookbook-popup').find('.tt-lookbook-container').append(objContent); $this.addClass('active').siblings().removeClass('active'); function popupShowLeft(objLeftFinal) { $('.tt-lookbook-popup').css({ 'top': objTop, 'left': objLeftFinal, 'display': 'block' }, 300).animate({ marginLeft: 26 + 'px', opacity: 1 }, 300); }; function popupShowRight(objLeftFinal) { $('.tt-lookbook-popup').css({ 'top': objTop, 'left': objLeftFinal, 'display': 'block' }).animate({ marginLeft: -26 + 'px', opacity: 1 }); }; }; //ttLookbookMobile function ttLookbookMobile($this) { var valueTop = $this.attr('data-top') + '%', valueLeft = $this.attr('data-left') + '%'; $this.find('.tt-btn').css({ 'top': valueTop, 'left': valueLeft }); $this.css({ 'top': '0px', 'left': '0px', 'width': '100%', 'height': '100%' }); $this.addClass('active').siblings().removeClass('active'); $this.find('.tt-content-parent').fadeIn(200); }; //Close mobile if (ttwindowWidth <= 789) { if ($('.tt-btn-close').is(e.target)) { closePopupMobile(); return false; }; if ($('.tt-hotspot').is(e.target)) { closePopupMobile(); }; $(document).mouseup(function (e) { if (!$('.tt-lookbook-popup').is(e.target) && $('.tt-lookbook-popup').has(e.target).length === 0 && !$('.tt-hotspot').is(e.target) && $('.tt-hotspot').has(e.target).length === 0) { closePopupDesctop(); }; }); }; //Close desctope if (ttwindowWidth > 789) { //ttLookbookClose $(document).mouseup(function (e) { var ttwindowWidth = window.innerWidth || $window.width(); if ($('.tt-btn-close').is(e.target)) { closePopupDesctop(); return false; }; if (!$('.tt-lookbook-popup').is(e.target) && $('.tt-lookbook-popup').has(e.target).length === 0 && !$('.tt-hotspot').is(e.target) && $('.tt-hotspot').has(e.target).length === 0) { closePopupDesctop(); }; }); }; function closePopupDesctop() { //detach content popup var detachContentPopup = $('.tt-lookbook-popup').removeAttr("style").find('.tt-hotspot-content').detach(); $('.tt-hotspot.active').removeClass('active').find('.tt-content-parent').append(detachContentPopup); }; function closePopupMobile() { if ($('.tt-lookbook-container').is(':has(div)')) { var checkPopupContent = $('.tt-lookbook-container').find('.tt-hotspot-content').detach(); $('.tt-hotspot.active').find('.tt-content-parent').append(checkPopupContent); }; $('.tt-lookbook').find('.tt-hotspot.active').each(function (index) { var $this = $(this), valueTop = $this.attr('data-top') + '%', valueLeft = $this.attr('data-left') + '%'; $this.removeClass('active').removeAttr("style").css({ 'top': valueTop, 'left': valueLeft, }).find('.tt-btn').removeAttr("style").next().removeAttr("style"); }); }; function checkclosePopupMobile() { $('.tt-hotspot').find('.tt-content-parent').each(function () { var $this = $(this); if ($this.css('display') == 'block') { var $thisParent = $this.closest('.tt-hotspot'), valueTop = $thisParent.attr('data-top') + '%', valueLeft = $thisParent.attr('data-left') + '%'; $this.removeAttr("style").prev().removeAttr("style"); $thisParent.removeAttr("style").css({ 'top': valueTop, 'left': valueLeft, }); }; }); }; $(window).resize(debouncer(function (e) { var ttwindowWidth = window.innerWidth || $window.width(); if (ttwindowWidth <= 789) { closePopupMobile(); } else { closePopupDesctop(); checkclosePopupMobile(); }; })); }); }; // Overflow Product function ttOverflowProduct() { blocks.ttProductDesign02.on("mouseenter", function () { if (window.innerWidth < 1024) return; var objImgHeight = $(this).find('.tt-image-box').height(), objScroll = $(this).find('.tt-description'), objScrollHeight = objScroll.height() + 25, valueHeight01 = objScroll.find('.tt-row').height(), valueHeight02 = objScroll.find('.tt-title').height(), valueHeight03 = objScroll.find('.tt-price').height(), valueHeight04 = objScroll.find('.tt-option-block').height(), valueHeight05 = objScroll.find('.tt-product-inside-hover').height(), valueHeighttotal = valueHeight01 + valueHeight02 + valueHeight03 + valueHeight04 + valueHeight05 + 60; if (objImgHeight > valueHeighttotal) return; $(this).addClass('tt-small'); objScroll.height(objImgHeight).perfectScrollbar(); }).on('mouseleave', function () { if (window.innerWidth < 1024) return; $(this).removeClass('tt-small').find('.tt-description').removeAttr('style').perfectScrollbar('destroy'); }); }; // portfolio mobile click function ttPortfolioContentMobile() { blocks.ttPortfolioContent.on('click', 'figure img', function () { $(this).closest(".tt-portfolio-content").find('figure').removeClass('gallery-click'); $(this).closest("figure").addClass('gallery-click'); }); }; //toggle col (listing-left-column.html) function ttToggleCol() { var $btnClose = $ttLeftColumnAside.find('.tt-btn-col-close a'); $('.tt-btn-toggle').on('click', function (e) { e.preventDefault(); var ttScrollValue = $body.scrollTop() || $html.scrollTop(); $ttLeftColumnAside.toggleClass('column-open').perfectScrollbar(); $body.css("top", -ttScrollValue).addClass("no-scroll").append('<div class="modal-filter"></div>'); var modalFilter = $('.modal-filter').fadeTo('fast', 1); if (modalFilter.length) { modalFilter.on('click', function () { $btnClose.trigger('click'); }) } return false; }); blocks.ttBtnColumnClose.on('click', function (e) { e.preventDefault(); $ttLeftColumnAside.removeClass('column-open').perfectScrollbar('destroy'); var top = parseInt($body.css("top").replace("px", ""), 10) * -1; $body.removeAttr("style").removeClass("no-scroll").scrollTop(top); $html.removeAttr("style").scrollTop(top); $(".modal-filter").off().remove(); return false; }); }; // Countdown function ttCountDown(showZero) { var showZero = showZero || false; blocks.ttCountdown.each(function () { var $this = $(this), date = $this.data('date'), set_year = $this.data('year') || 'Yrs', set_month = $this.data('month') || 'Mths', set_week = $this.data('week') || 'Wk', set_day = $this.data('day') || 'Day', set_hour = $this.data('hour') || 'Hrs', set_minute = $this.data('minute') || 'Min', set_second = $this.data('second') || 'Sec'; if (date = date.split('-')) { date = date.join('/'); } else return; $this.countdown(date, function (e) { var format = '<span class="countdown-row">'; function addFormat(func, timeNum, showZero) { if (timeNum === 0 && !showZero) return; func(format); }; addFormat(function () { format += '<span class="countdown-section">' + '<span class="countdown-amount">' + e.offset.totalDays + '</span>' + '<span class="countdown-period">' + set_day + '</span>' + '</span>'; }, e.offset.totalDays, showZero); addFormat(function () { format += '<span class="countdown-section">' + '<span class="countdown-amount">' + e.offset.hours + '</span>' + '<span class="countdown-period">' + set_hour + '</span>' + '</span>'; }, e.offset.hours, showZero); addFormat(function () { format += '<span class="countdown-section">' + '<span class="countdown-amount">' + e.offset.minutes + '</span>' + '<span class="countdown-period">' + set_minute + '</span>' + '</span>'; }, e.offset.minutes, showZero); addFormat(function () { format += '<span class="countdown-section">' + '<span class="countdown-amount">' + e.offset.seconds + '</span>' + '<span class="countdown-period">' + set_second + '</span>' + '</span>'; }, e.offset.seconds, showZero); format += '</span>'; $(this).html(format); }); }); }; function ttCollapseBlock() { blocks.ttCollapseBlock.each(function () { var obj = $(this), objOpen = obj.find('.tt-item.active'), objItemTitle = obj.find('.tt-item .tt-collapse-title'); objOpen.find('.tt-collapse-content').slideToggle(200); objItemTitle.on('click', function () { $(this).next().slideToggle(200).parent().toggleClass('active'); }); }); }; function getInternetExplorerVersion() { var rv = -1; if (navigator.appName === 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } else if (navigator.appName === 'Netscape') { var ua = navigator.userAgent; var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; }; // identify touch device function is_touch_device() { return !!('ontouchstart' in window) || !!('onmsgesturechange' in window); }; if (is_touch_device()) { $body.addClass('touch-device'); $html.addClass('touch-device'); }; if (/Edge/.test(navigator.userAgent)) { $html.addClass('edge'); }; //video function ttVideoBlock() { $('.tt-video-block').on('click', function (e) { e.preventDefault(); var myVideo = $(this).find('.movie')[0]; if (myVideo.paused) { myVideo.play(); $(this).addClass('play'); } else { myVideo.pause(); $(this).removeClass('play'); } }); }; // Blog Masonr function gridGalleryMasonr() { // init Isotope var $grid = blocks.ttBlogMasonry.find('.tt-blog-init').isotope({ itemSelector: '.element-item', layoutMode: 'masonry', }); // layout Isotope after each image loads $grid.imagesLoaded().progress(function () { $grid.isotope('layout').addClass('tt-show'); }); // filter functions var ttFilterNav = blocks.ttBlogMasonry.find('.tt-filter-nav'); if (ttFilterNav.length) { var filterFns = { ium: function () { var name = $(this).find('.name').text(); return name.match(/ium$/); } }; // bind filter button click ttFilterNav.on('click', '.button', function () { var filterValue = $(this).attr('data-filter'); filterValue = filterFns[filterValue] || filterValue; $grid.isotope({ filter: filterValue }); $(this).addClass('active').siblings().removeClass('active'); }); }; var isotopShowmoreJs = $('.isotop_showmore_js .btn'), ttAddItem = $('.tt-add-item'); if (isotopShowmoreJs.length && ttAddItem.length) { isotopShowmoreJs.on('click', function (e) { e.preventDefault(); $.ajax({ url: 'ajax_post.php', success: function (data) { var $item = $(data); ttAddItem.append($item); $grid.isotope('appended', $item); adjustOffset(); } }); function adjustOffset() { var offsetLastItem = ttAddItem.children().last().children().offset().top - 180; $($body, $html).animate({ scrollTop: offsetLastItem }, 500); }; return false; }); }; }; // Product Masonr (listing-metro.html) function gridProductMasonr() { // init Isotope var $grid = blocks.ttProductMasonry.find('.tt-product-init').isotope({ itemSelector: '.element-item', layoutMode: 'masonry', }); // layout Isotope after each image loads $grid.imagesLoaded().progress(function () { $grid.isotope('layout'); }); // filter functions var ttFilterNav = blocks.ttProductMasonry.find('.tt-filter-nav'); if (ttFilterNav.length) { var filterFns = { ium: function () { var name = $(this).find('.name').text(); return name.match(/ium$/); } }; // bind filter button click ttFilterNav.on('click', '.button', function () { var filterValue = $(this).attr('data-filter'); filterValue = filterFns[filterValue] || filterValue; $grid.isotope({ filter: filterValue }); $(this).addClass('active').siblings().removeClass('active'); }); }; //add item var isotopShowmoreJs = $('.isotop_showmore_js .btn'), ttAddItem = $('.tt-add-item'); if (isotopShowmoreJs.length && ttAddItem.length) { isotopShowmoreJs.on('click', function (e) { e.preventDefault(); $.ajax({ url: 'ajax_product_metro.php', success: function (data) { var $item = $(data); ttAddItem.append($item); $grid.isotope('appended', $item); ttProductSmall(); adjustOffset(); } }); function adjustOffset() { var offsetLastItem = ttAddItem.children().last().children().offset().top - 80; $($body, $html).animate({ scrollTop: offsetLastItem }, 500); }; return false; }); }; }; // Lookbook Masonr function gridLookbookMasonr() { // init Isotope var $grid = blocks.ttLookBookMasonry.find('.tt-lookbook-init').isotope({ itemSelector: '.element-item', layoutMode: 'masonry', gutter: 0 }); // layout Isotope after each image loads $grid.imagesLoaded().progress(function () { $grid.addClass('tt-show').isotope('layout'); }); //add item var isotopShowmoreJs = $('.isotop_showmore_js .btn'), ttAddItem = $('.tt-add-item'); if (isotopShowmoreJs.length && ttAddItem.length) { isotopShowmoreJs.on('click', function (e) { e.preventDefault(); $.ajax({ url: 'ajax_post.php', success: function (data) { var $item = $(data); ttAddItem.append($item); $grid.isotope('appended', $item); adjustOffset(); } }); function adjustOffset() { var offsetLastItem = ttAddItem.children().last().children().offset().top - 180; $($body, $html).animate({ scrollTop: offsetLastItem }, 500); }; return false; }); }; }; // collapseBlock(pages listing) *listing-left-column.html function ttCollapse() { var item = blocks.ttCollapse, itemTitle = item.find('.tt-collapse-title'), itemContent = item.find('.tt-collapse-content'); item.each(function () { if ($(this).hasClass('open')) { $(this).find(itemContent).slideDown(); } else { $(this).find(itemContent).slideUp(); } }); itemTitle.on('click', function (e) { e.preventDefault(); var speed = 300; var thisParent = $(this).parent(), nextLevel = $(this).next('.tt-collapse-content'); if (thisParent.hasClass('open')) { thisParent.removeClass('open'); nextLevel.slideUp(speed); } else { thisParent.addClass('open'); nextLevel.slideDown(speed); } }) }; // ttFiltersOptions (function ($) { $.fn.removeClassFirstPart = function (mask) { return this.removeClass(function (index, cls) { var re = mask.replace(/\*/g, '\\S+'); return (cls.match(new RegExp('\\b' + re + '', 'g')) || []).join(' '); }); }; })(jQuery); function ttFilterLayout(ttwindowWidth) { // detach filter aside left if ($ttFilterOptions.hasClass('desctop-no-sidebar') && !$ttFilterOptions.hasClass('filters-detach-mobile')) { ttwindowWidth <= 1024 ? insertMobileCol() : insertFilter(); }; if ($ttFilterOptions.hasClass('filters-detach-mobile')) { ttwindowWidth <= 1024 ? insertMobileCol() : insertFilter(); }; if (!$ttFilterOptions.hasClass('desctop-no-sidebar')) { ttwindowWidth <= 1024 ? insertMobileCol() : insertFilter(); }; function insertMobileCol() { var objFilterOptions = blocks.ttFilterSort.find('select').detach(); blocks.ttFilterDetachOption.find('.filters-row-select').append(objFilterOptions); }; function insertFilter() { var objColFilterOptions = blocks.ttFilterDetachOption.find('.filters-row-select select').detach(); blocks.ttFilterSort.append(objColFilterOptions); }; //active filter detection blocks.ttProductListing.removeClassFirstPart("tt-col-*"); var ttQuantity = $ttFilterOptions.find('.tt-quantity'), ttProductItem = blocks.ttProductListing.find('.tt-col-item:first'), ttProductItemValue = (function () { if (ttQuantity.length && !ttQuantity.hasClass('tt-disabled')) { var ttValue = parseInt(ttProductItem.css("flex").replace("0 0", "").replace("%", ""), 10) || parseInt(ttProductItem.css("max-width"), 10); return ttValue; }; }()), ttGridSwitch = $ttFilterOptions.find('.tt-grid-switch'); if (ttProductItemValue == 16) { ttСhangeclass(ttQuantity, '.tt-col-six'); } else if (ttProductItemValue == 25) { ttСhangeclass(ttQuantity, '.tt-col-four'); } else if (ttProductItemValue == 33) { ttСhangeclass(ttQuantity, '.tt-col-three'); } else if (ttProductItemValue == 50) { ttСhangeclass(ttQuantity, '.tt-col-two'); } else if (ttProductItemValue == 100) { ttСhangeclass(ttQuantity, '.tt-col-one'); }; function ttСhangeclass(ttObj, ttObjvalue) { ttObj.find(ttObjvalue).addClass('active').siblings().removeClass('active'); ttwindowWidth <= 1024 ? ttShowIconMobile(ttObj, ttObjvalue) : ttShowIconDesctop(ttObj, ttObjvalue); }; function ttShowIconDesctop(ttObj, ttObjvalue) { ttObj.find('.tt-show').removeClass('tt-show'); ttObj.find('.tt-show-siblings').removeClass('tt-show-siblings'); var $this = ttObj.find(ttObjvalue); $this.addClass('tt-show'); $this.next().addClass('tt-show-siblings'); $this.prev().addClass('tt-show-siblings'); var quantitySiblings = $('.tt-quantity .tt-show-siblings').length; if (quantitySiblings === 1) { ttObj.find('.tt-show-siblings').prev().addClass('tt-show-siblings'); }; }; function ttShowIconMobile(ttObj, ttObjvalue) { ttObj.find('.tt-show').removeClass('tt-show'); ttObj.find('.tt-show-siblings').removeClass('tt-show-siblings'); var $this = ttObj.find(ttObjvalue); $this.addClass('tt-show'); $this.prev().addClass('tt-show-siblings'); }; //click buttons filter ttQuantity.on('click', 'a', function (e) { e.preventDefault(); if (ttQuantity.hasClass('tt-disabled')) { blocks.ttProductListing.removeClass('tt-row-view').find('.tt-col-item > div').removeClass('tt-view'); ttQuantity.removeClass('tt-disabled'); ttGridSwitch.removeClass('active'); ttOverflowProduct(); }; ttQuantity.find('a').removeClass('active'); var ttActiveValue = $(this).addClass('active').attr('data-value'); blocks.ttProductListing.removeClassFirstPart("tt-col-*").addClass(ttActiveValue); ttProductSmall(); }); }; $ttFilterOptions.find('.tt-grid-switch').on('click', function (e) { e.preventDefault(); $(this).toggleClass('active'); blocks.ttProductListing.toggleClass('tt-row-view').find('.tt-col-item > div').toggleClass('tt-view'); $ttFilterOptions.find('.tt-quantity').toggleClass('tt-disabled'); }); // Portfolio function gridPortfolioMasonr() { // init Isotope var $grid = blocks.ttPortfolioMasonry.find('.tt-portfolio-content').isotope({ itemSelector: '.element-item', layoutMode: 'masonry', }); // layout Isotope after each image loads $grid.imagesLoaded().progress(function () { $grid.isotope('layout').addClass('tt-show'); }); // filter functions var ttFilterNav = blocks.ttPortfolioMasonry.find('.tt-filter-nav'); if (ttFilterNav.length) { var filterFns = { ium: function () { var name = $(this).find('.name').text(); return name.match(/ium$/); } }; // bind filter button click ttFilterNav.on('click', '.button', function () { var filterValue = $(this).attr('data-filter'); filterValue = filterFns[filterValue] || filterValue; $grid.isotope({ filter: filterValue }); $(this).addClass('active').siblings().removeClass('active'); }); }; //add item var isotopShowmoreJs = $('.isotop_showmore_js .btn'), ttAddItem = $('.tt-add-item'); if (isotopShowmoreJs.length && ttAddItem.length) { isotopShowmoreJs.on('click', function (e) { e.preventDefault(); $.ajax({ url: 'ajax_portfolio.php', success: function (data) { var $item = $(data); ttAddItem.append($item); $grid.isotope('appended', $item); initPortfolioPopup(); adjustOffset(); } }); function adjustOffset() { var offsetLastItem = ttAddItem.children().last().children().offset().top - 180; $($body, $html).animate({ scrollTop: offsetLastItem }, 500); }; return false; }); }; }; function initPortfolioPopup() { var objZoom = $ttPageContent.find('.tt-portfolio-masonry .tt-btn-zomm'); objZoom.magnificPopup({ type: 'image', gallery: { enabled: true } }); }; //input-counter /* function ttInputCounter() { blocks.ttInputCounter.find('.minus-btn, .plus-btn').on('click', function (e) { var $input = $(this).parent().find('input'); var count = parseInt($input.val(), 10) + parseInt(e.currentTarget.className === 'plus-btn' ? 1 : -1, 10); $input.val(count).change(); }); blocks.ttInputCounter.find("input").change(function () { var _ = $(this); var min = 1; var val = parseInt(_.val(), 10); var max = parseInt(_.attr('size'), 10); val = Math.min(val, max); val = Math.max(val, min); _.val(val); }) .on("keypress", function (e) { if (e.keyCode === 13) { e.preventDefault(); } }); }; */ //popup on pages product single function ttVideoPopup() { blocks.modalVideoProduct.on('show.bs.modal', function (e) { var relatedTarget = $(e.relatedTarget), attr = relatedTarget.attr('data-value'), attrPoster = relatedTarget.attr('data-poster'), attrType = relatedTarget.attr('data-type'); if (attrType === "youtube" || attrType === "vimeo" || attrType === undefined) { $('<iframe src="' + attr + '" allowfullscreen></iframe>').appendTo($(this).find('.modal-video-content')); }; if (attrType === "video") { $('<div class="tt-video-block"><a href="#" class="link-video"></a><video class="movie" src="' + attr + '" poster="' + attrPoster + '" allowfullscreen></video></div>').appendTo($(this).find('.modal-video-content')); }; ttVideoBlock(); }).on('hidden.bs.modal', function () { $(this).find('.modal-video-content').empty(); }); }; //product pages var elevateZoomWidget = { scroll_zoom: true, class_name: '.zoom-product', thumb_parent: $('#smallGallery'), scrollslider_parent: $('.slider-scroll-product'), checkNoZoom: function () { return $(this.class_name).parent().parent().hasClass('no-zoom'); }, init: function (type) { var _ = this; var currentW = window.innerWidth || $(window).width(); var zoom_image = $(_.class_name); var _thumbs = _.thumb_parent; _.initBigGalleryButtons(); _.scrollSlider(); if (zoom_image.length == 0) return false; if (!_.checkNoZoom()) { var attr_scroll = zoom_image.parent().parent().attr('data-scrollzoom'); attr_scroll = attr_scroll ? attr_scroll : _.scroll_zoom; _.scroll_zoom = attr_scroll == 'false' ? false : true; currentW > 575 && _.configureZoomImage(); _.resize(); } if (_thumbs.length == 0) return false; var thumb_type = _thumbs.parent().attr('class').indexOf('-vertical') > -1 ? 'vertical' : 'horizontal'; _[thumb_type](_thumbs); _.setBigImage(_thumbs); }, configureZoomImage: function () { var _ = this; $('.zoomContainer').remove(); var zoom_image = $(this.class_name); zoom_image.each(function () { var _this = $(this); var clone = _this.removeData('elevateZoom').clone(); _this.after(clone).remove(); }); setTimeout(function () { $(_.class_name).elevateZoom({ gallery: _.thumb_parent.attr('id'), zoomType: "inner", scrollZoom: Boolean(_.scroll_zoom), cursor: "crosshair", zoomWindowFadeIn: 300, zoomWindowFadeOut: 300 }); }, 100); }, resize: function () { var _ = this; $(window).resize(function () { var currentW = window.innerWidth || $(window).width(); if (currentW <= 575) return false; _.configureZoomImage(); }); }, horizontal: function (_parent) { _parent.slick({ infinite: true, dots: false, arrows: true, slidesToShow: 6, slidesToScroll: 1, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 4, slidesToScroll: 1 } }, { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1 } } ] }); }, vertical: function (_parent) { _parent.slick({ vertical: true, infinite: true, slidesToShow: 5, slidesToScroll: 1, verticalSwiping: true, arrows: true, dots: false, centerPadding: "0px", customPaging: "0px", responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 1 } }, { breakpoint: 992, settings: { slidesToShow: 5, slidesToScroll: 1 } }, { breakpoint: 768, settings: { slidesToShow: 5, slidesToScroll: 1 } } ] }); }, initBigGalleryButtons: function () { var bigGallery = $('.bigGallery'); if (bigGallery.length == 0) return false; $('body').on('mouseenter', '.zoomContainer', function () { bigGallery.find('button').addClass('show'); } ).on('mouseleave', '.zoomContainer', function () { bigGallery.find('button').removeClass('show'); } ); }, scrollSlider: function () { var _scrollslider_parent = this.scrollslider_parent; if (_scrollslider_parent.length == 0) return false; _scrollslider_parent.on('init', function (event, slick) { _scrollslider_parent.css({ 'opacity': 1 }); }); _scrollslider_parent.css({ 'opacity': 0 }).slick({ infinite: false, vertical: true, verticalScrolling: true, dots: true, arrows: false, slidesToShow: 1, slidesToScroll: 1, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, slidesToScroll: 1 } }, { breakpoint: 992, settings: { slidesToShow: 1, slidesToScroll: 1 } }, { breakpoint: 768, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }).mousewheel(function (e) { e.preventDefault(); e.deltaY < 0 ? $(this).slick('slickNext') : $(this).slick('slickPrev'); }); }, setBigImage: function (_parent) { var _ = this; _parent.find('a').on('click', function (e) { _.checkNoZoom() && e.preventDefault(); var zoom_image = $(_.class_name); var getParam = _.checkNoZoom() ? 'data-image' : 'data-zoom-image'; var setParam = _.checkNoZoom() ? 'src' : 'data-zoom-image'; var big_image = $(this).attr(getParam); zoom_image.attr(setParam, big_image); if (!_.checkNoZoom()) return false; _parent.find('.zoomGalleryActive').removeClass('zoomGalleryActive'); $(this).addClass('zoomGalleryActive'); }); } }; elevateZoomWidget.init(); // product single tt-btn-zomm(*magnific popup) function ttProductSingleBtnZomm() { $body.on('click', '.tt-product-single-img .tt-btn-zomm', function (e) { var objSmallGallery = $('#smallGallery'); objSmallGallery.find('a').each(function () { var dataZoomImg = $(this).attr('data-zoom-image'); if (dataZoomImg.length) { $(this).closest('li').append("<a class='link-magnific-popup' href='#'></a>").find('.link-magnific-popup').attr('href', dataZoomImg); if ($(this).hasClass('zoomGalleryActive')) { $(this).closest('li').find('.link-magnific-popup').addClass('zoomGalleryActive'); }; }; }); objSmallGallery.addClass('tt-magnific-popup').find('.link-magnific-popup').magnificPopup({ type: 'image', gallery: { enabled: true, tCounter: '<span class="mfp-counter"></span>' }, callbacks: { close: function () { setTimeout(function () { objSmallGallery.removeClass('tt-magnific-popup').find('.link-magnific-popup').remove(); }, 200); } } }); objSmallGallery.find('.link-magnific-popup.zoomGalleryActive').trigger('click'); }); }; //sticky(product-05.html) function ttAirSticky(ttwindowWidth) { var airStickyObj = blocks.ttAirSticky, tabObj = blocks.ttCollapseBlock.find('.tt-collapse-title'); if (ttwindowWidth >= 1024) { airStickyObj.airStickyBlock({ debug: false, stopBlock: '.airSticky_stop-block', offsetTop: 70, }); } else if (airStickyObj.hasClass('airSticky_absolute')) { airStickyObj.removeClass('airSticky_absolute'); }; $document.on('resize scroll', tabObj, function () { airStickyObj.trigger('render.airStickyBlock'); }); tabObj.on('click', function () { setTimeout(function () { airStickyObj.trigger('render.airStickyBlock'); }, 170); }); }; /** * Stuck init. Properties: on/off * @value = 'off', default empty */ function initStuck(value) { if ($stucknav.hasClass('disabled')) return; var value = value || false, ie = (getInternetExplorerVersion() !== -1) ? true : false; if (value === 'off') return false; var n = 0; $window.scroll(function () { var HeaderTop = $('header').innerHeight(); if ($window.scrollTop() > HeaderTop) { if ($stucknav.hasClass('stuck')) return false; $stucknav.hide(); $stucknav.addClass('stuck'); // $('body').trigger('showStuck'); window.innerWidth < 1025 ? $ttStuckParentMenu.append($ttMobileParentMenuChildren.detach()) : $ttStuckParentMenu.append($ttDesctopMenu.detach()); $ttStuckParentCart.append($ttcartObj.detach()); $ttStuckParentMulti.append($ttMultiObj.detach()); $ttStuckParentAccount.append($ttAccountObj.detach()); $ttStuckParentSearch.append($ttSearchObj.detach()); if ($stucknav.find('.tt-stuck-cart-parent > .tt-cart > .dropdown').hasClass('open') || ie) $stucknav.stop().show(); else $stucknav.stop().fadeIn(300); } else { if (!$stucknav.hasClass('stuck')) return false; $stucknav.hide(); $stucknav.removeClass('stuck'); // $('body').trigger('hideStuck'); if (window.innerWidth < 1025) { $ttMobileParentMenu.append($ttMobileParentMenuChildren.detach()); $ttMobileParentCart.append($ttcartObj.detach()); $ttMobileParentMulti.append($ttMultiObj.detach()); $ttMobileParentAccount.append($ttAccountObj.detach()); $ttMobileParentSearch.append($ttSearchObj.detach()); return false; } $ttDesctopParentMenu.append($ttDesctopMenu.detach()); $ttDesctopParentCart.append($ttcartObj.detach()); $ttDesctopParentMulti.append($ttMultiObj.detach()); $ttDesctopParentAccount.append($ttAccountObj.detach()); $ttDesctopParentSearch.append($ttSearchObj.detach()); } }); $window.resize(function () { if (!$stucknav.hasClass('stuck')) return false; if (window.innerWidth < 1025) { $ttDesctopParentMenu.append($ttDesctopMenu.detach()); $ttStuckParentMenu.append($ttMobileParentMenuChildren.detach()); } else { $ttMobileParentMenu.append($ttMobileParentMenuChildren.detach()); $ttStuckParentMenu.append($ttDesctopMenu.detach()); } }); }; //header search function mobileParentSearch() { if (window.innerWidth < 1025) { if ($ttMobileParentSearch.children().lenght) return false; if ($('.stuck').length) return false; $ttMobileParentSearch.append($ttSearchObj.detach()); } else { if ($ttDesctopParentSearch.children().lenght) return false; if ($('.stuck').length) return false; $ttDesctopParentSearch.append($ttSearchObj.detach()); }; }; //header cart function mobileParentCart() { if (window.innerWidth < 1025) { if ($ttMobileParentCart.children().lenght) return false; if ($('.stuck').length) return false; $ttMobileParentCart.append($ttcartObj.detach()); } else { if ($ttDesctopParentCart.children().lenght) return false; if ($('.stuck').length) return false; $ttDesctopParentCart.append($ttcartObj.detach()); }; }; //header account function mobileParentAccount() { if (window.innerWidth < 1025) { if ($ttMobileParentAccount.children().lenght) return false; if ($('.stuck').length) return false; $ttMobileParentAccount.append($ttAccountObj.detach()); } else { if ($ttDesctopParentAccount.children().lenght) return false; if ($('.stuck').length) return false; $ttDesctopParentAccount.append($ttAccountObj.detach()); }; }; //header langue and currency(*all in one module) function mobileParentMulti() { if (window.innerWidth < 1025) { if ($ttMobileParentMulti.children().lenght) return false; if ($('.stuck').length) return false; $ttMobileParentMulti.append($ttMultiObj.detach()); } else { if ($ttDesctopParentMulti.children().lenght) return false; if ($('.stuck').length) return false; $ttDesctopParentMulti.append($ttMultiObj.detach()); }; }; /* Module Categories */ (function () { var $obj = $(".tt-menu-categories"), $objLi = $obj.find('nav > ul > li'), $subMenu = $(this).find('.dropdown-menu'), mobileCategoriesToggle = $ttHeader.find('.tt-categories-toggle'); if (!$obj.length) return; //event open menu categories $body.on('click', '.tt-menu-categories button', function (e) { e.preventDefault(); $(this).closest('.tt-menu-categories').toggleClass('opened').find('.tt-dropdown-menu').slideToggle(200); }); //determination sub menu (function subMenuCategories() { $obj.find('nav > ul > li').each(function () { var ttSubmenu = $(this).find('.dropdown-menu'); if (ttSubmenu.length) { $(this).closest('li').addClass('tt-submenu'); } }); })(); //add active class menu (function menuHover() { $obj.find(".tt-dropdown-menu li").hover(function (e) { $(this).toggleClass('acitve', e.type === 'mouseenter'); }); })(); //check popup past viewport $obj.find('.tt-megamenu-submenu ul li').on("mouseenter", function () { var $ul = $(this).find('ul:first'); if ($ul.length) { var windW = window.innerWidth, ulW = parseInt($ul.css('width'), 10) + 20, thisR = this.getBoundingClientRect().right, thisL = this.getBoundingClientRect().left; if (windW - thisR < ulW) { $ul.addClass('right-popup'); } else if (thisL < ulW) { $ul.removeClass('right-popup'); }; } }).on('mouseleave', function () { $(this).find('ul:first').removeClass('right-popup'); }); //detach (function detachCategories() { if ($stucknav.hasClass('disabled')) return; var //desctop $ttDesctopParentMenuCategories = $ttHeader.find('.tt-desctop-parent-menu-categories'), $ttStuckParentMenuCategories = $ttHeader.find('.tt-stuck-desctop-menu-categories'), //mobile $ttMobileParentMenuCategories = $ttHeader.find('.tt-mobile-parent-menu-categories'), $ttStuckMobileMenuCategories = $ttHeader.find('.tt-stuck-mobile-menu-categories'); $window.scroll(function () { var HeaderTop = $('header').innerHeight(); if ($window.scrollTop() > HeaderTop) { $ttStuckParentMenuCategories.append($ttDesctopParentMenuCategories.find('.tt-menu-categories').detach()); $ttStuckMobileMenuCategories.append($ttMobileParentMenuCategories.find('.tt-categories-toggle').detach()); } else { $ttDesctopParentMenuCategories.append($ttStuckParentMenuCategories.find('.tt-menu-categories').detach()); $ttMobileParentMenuCategories.append($ttStuckMobileMenuCategories.find('.tt-categories-toggle').detach()); }; }); })(); //mobile init menu Categories if (mobileCategoriesToggle.length) { mobileCategoriesToggle.initMM({ enable_breakpoint: true, mobile_button: true, breakpoint: 1025, menu_class: 'mobile-caterorie-menu' }); }; })(); /* header menu */ // header menu(hover) (function toggle_header_menu() { var delay = header_menu_timeout, hoverTimer = header_menu_delay, timeout1 = false; var set_dropdown_maxH = function () { var wind_H = window.innerHeight, $ttDesctopMenu = $(this).find('.dropdown-menu'), menu_top = $ttDesctopMenu.get(0).getBoundingClientRect().top, menu_max_H = wind_H - menu_top, $ttDesctopMenu_H = $ttDesctopMenu.innerHeight(), $btn_top = blocks.ttBackToTop; if ($ttDesctopMenu_H > menu_max_H) { var $body = $('body'), $stuck = $('.stuck-nav'); $ttDesctopMenu.css({ maxHeight: menu_max_H - 20, overflow: 'auto' }); var scrollWidth = function () { var $div = $('<div>').css({ overflowY: 'scroll', width: '50px', height: '50px', visibility: 'hidden' }); $body.append($div); var scrollWidth = $div.get(0).offsetWidth - $div.get(0).clientWidth; $div.remove(); return scrollWidth; }; $body.css({ overflowY: 'hidden', paddingRight: scrollWidth() }); $stuck.css({ paddingRight: scrollWidth() }); $btn_top.css({ right: scrollWidth() }); } }; if ($ttDesctopMenu.length > 0) { $('.tt-megamenu-submenu li a').each(function () { if ($(this).find('img').length) { $(this).closest('ul').addClass('tt-sub-img'); } }); $ttDesctopMenu.find('.dropdown-menu').each(function () { if ($(this).length) { $(this).closest('.dropdown').addClass('tt-submenu'); } }); $(document).on({ mouseenter: function () { var $this = $(this), that = this, windowW = window.innerWidth || $(window).width(); if (windowW > 1025 && $body.hasClass('touch-device')) { $ttDesctopMenu.find('.dropdown.tt-submenu > a').one("click", false); }; timeout1 = setTimeout(function () { var $carousel = $this.find('.tt-menu-slider'), $ttDesctopMenu = $this.find('.dropdown-menu'); $this.addClass('active') .find(".dropdown-menu") .stop() .addClass('hover') .fadeIn(hoverTimer); if ($ttDesctopMenu.length & !$ttDesctopMenu.hasClass('one-col')) { set_dropdown_maxH.call(that); } if ($carousel.length) { if (!$carousel.hasClass('slick-initialized')) { $carousel.slick({ dots: false, arrows: true, infinite: true, speed: 300, slidesToShow: 2, slidesToScroll: 2, adaptiveHeight: true }); } }; $carousel.slick('setPosition'); }, delay); }, mouseleave: function (e) { var $this = $(this), $dropdown = $this.find(".dropdown-menu"); if ($(e.target).parents('.dropdown-menu').length && !$(e.target).parents('.tt-megamenu-submenu').length && !$(e.target).parents('.one-col').length) return; if (timeout1 !== false) { clearTimeout(timeout1); timeout1 = false; } if ($dropdown.length) { $dropdown.stop().fadeOut({ duration: 0, complete: function () { $this.removeClass('active') .find(".dropdown-menu") .removeClass('hover'); } }); } else { $this.removeClass('active') .find(".dropdown-menu") .removeClass('hover'); } $dropdown.removeAttr('style'); $body.removeAttr('style'); $('.stuck-nav').css({ paddingRight: 'inherit' }); blocks.ttBackToTop.css({ right: 0 }); } }, '.tt-desctop-menu li'); $ttDesctopMenu.find('.multicolumn ul li').on('hover', function () { var $ul = $(this).find('ul:first'); if ($ul.length) { var windW = window.innerWidth, windH = window.innerHeight, ulW = parseInt($ul.css('width'), 10), thisR = this.getBoundingClientRect().right, thisL = this.getBoundingClientRect().left; if (windW - thisR < ulW) { $ul.removeClass('left').addClass('right'); } else if (thisL < ulW) { $ul.removeClass('right').addClass('left'); } else { $ul.removeClass('left right'); } $ul.stop(true, true).fadeIn(300); } }, function () { $(this).find('ul:first').stop(true, true).fadeOut(300).removeAttr('style'); }); $ttDesctopMenu.find('.tt-megamenu-submenu li').on("mouseenter", function () { var $ul = $(this).find('ul:first'); if ($ul.length) { var $dropdownMenu = $(this).parents('.dropdown').find('.dropdown-menu'), dropdown_left = $dropdownMenu.get(0).getBoundingClientRect().left, dropdown_Right = $dropdownMenu.get(0).getBoundingClientRect().right, dropdown_Bottom = $dropdownMenu.get(0).getBoundingClientRect().bottom, ulW = parseInt($ul.css('width'), 10), thisR = this.getBoundingClientRect().right, thisL = this.getBoundingClientRect().left; if (dropdown_Right - 20 - thisR < ulW) { $ul.removeClass('left').addClass('right'); } else if (thisL - ulW - 20 < dropdown_left) { $ul.removeClass('right').addClass('left'); } else { $ul.removeClass('left right'); } $ul.stop(true, true).delay(150).fadeIn(300); var ul_bottom = $ul.get(0).getBoundingClientRect().bottom; if (dropdown_Bottom < ul_bottom) { var move_top = dropdown_Bottom - ul_bottom; $ul.css({ top: move_top }); } } }).on('mouseleave', function () { $(this).find('ul:first').stop(true, true).fadeOut(300).removeAttr('style'); }); $ttDesctopMenu.find('.dropdown div').on('hover', function () { $(this).children('.tt-title-submenu').toggleClass('active'); }); }; function onscroll_dropdown_hover() { var $dropdown_active = $('.dropdown.hover'); if (!$dropdown_active.find('.dropdown-menu').not('.one-col').length) return; if ($dropdown_active.length) set_dropdown_maxH.call($dropdown_active); }; $(window).on('scroll', function () { onscroll_dropdown_hover(); }); })(); //REVOLUTION SLIDER (function to reset the plug on the breakpoints) function sliderRevolution() { function click_to_play_video() { var $this = $(this), $video = $this.find('li video'); if (!$video.length) return; $video.on('play', function () { var $btn = $(this).parents('li').find('.video-play'); $btn.addClass('pause'); $(this).parents('.tp-caption.fullscreenvideo').addClass('click-video'); }); $video.on('pause ended', function () { var $btn = $(this).parents('li').find('.video-play'); $btn.removeClass('pause'); }); $this.find('.video-play').on('click', function (e) { var $video = $(this).parents('li').find('video'); $video.trigger('click'); e.preventDefault(); e.stopPropagation(); return false; }); $this.on('revolution.slide.onbeforeswap', function (event, data) { $(this).find('.tp-caption.fullscreenvideo').removeClass('click-video'); }); }; function autoplay_video(elem) { var $get_sliders = $(this); $get_sliders.each(function () { var $slider = $(this); var set_event = function () { $slider.on('revolution.slide.onchange', function (event, data) { var $this = $(this), $active_slide = $this.find('li').eq(data.slideIndex - 1), $video = $active_slide.find('video'), autoplay = $active_slide.find('.tp-caption').attr('data-autoplay'); if ($video.length && autoplay === 'true') { var video = $video.get(0); video.currentTime = 0; $slider.one('revolution.slide.onafterswap', function (event, data) { if (video.paused) { video.play(); } }); } }); }; if ($slider.hasClass('revslider-initialised')) { set_event(); } else { $slider.one('revolution.slide.onloaded', function () { set_event(); }); } }); }; $.fn.resizeRevolution = function (options, new_rev_obj, bp_arr) { if (!$(this).length || !$(options.slider).length || !options.breakpoints) return false; var wrapper = this, slider = options.slider, breakpoints = options.breakpoints, fullscreen_BP = options.fullscreen_BP || false, new_rev_obj = new_rev_obj || {}, bp_arr = bp_arr || [], rev_obj = { dottedOverlay: "true", delay: 4600, startwidth: 1920, hideThumbs: 200, hideTimerBar: "on", thumbWidth: 100, thumbHeight: 50, thumbAmount: 5, navigationArrows: "none", touchenabled: "on", onHoverStop: "on", swipe_velocity: 0.7, swipe_min_touches: 1, swipe_max_touches: 1, drag_block_vertical: false, parallax: "mouse", parallaxBgFreeze: "on", parallaxLevels: [7, 4, 3, 2, 5, 4, 3, 2, 1, 0], keyboardNavigation: "off", navigationHAlign: "center", navigationVAlign: "bottom", navigationHOffset: 0, navigationVOffset: 20, soloArrowLeftHalign: "left", soloArrowLeftValign: "center", soloArrowLeftHOffset: 20, soloArrowLeftVOffset: 0, soloArrowRightHalign: "right", soloArrowRightValign: "center", soloArrowRightHOffset: 20, soloArrowRightVOffset: 0, shadow: 0, spinner: "", h_align: "left", stopLoop: "off", stopAfterLoops: -1, stopAtSlide: -1, shuffle: "off", autoHeight: "off", forceFullWidth: "off", hideThumbsOnMobile: "off", hideNavDelayOnMobile: 1500, hideBulletsOnMobile: "off", hideArrowsOnMobile: "off", hideThumbsUnderResolution: 0, hideSliderAtLimit: 0, hideCaptionAtLimit: 0, hideAllCaptionAtLilmit: 0, startWithSlide: 0, fullScreenOffsetContainer: false }; $.extend(rev_obj, new_rev_obj); var get_Slider = function ($sliderWrapp) { return $sliderWrapp.find(slider); }; var get_current_bp = function () { var wind_W = window.innerWidth; for (var i = 0; i < breakpoints.length; i++) { var bp = breakpoints[i]; if (!breakpoints.length) return false; if (wind_W <= bp) { if (i === 0) { return bp; } else { if (bp > breakpoints[i - 1]) return bp; } } else if (wind_W > bp && i === breakpoints.length - 1) return Infinity; } return false; }; var $sliderWrappers = $(wrapper); $sliderWrappers.each(function () { var $sliderWrapp = $(this), $sliderInit = get_Slider($sliderWrapp), $sliderCopy = $sliderWrapp.clone(), bp = get_current_bp(); if (!$sliderInit.length) return false; var start_Rev = function ($sliderInit, bp) { var wind_W = window.innerWidth, rev_settings_obj = {}, rev_screen_obj = {}, set_rev_obj = {}; if (fullscreen_BP) { var full_width = (wind_W >= fullscreen_BP) ? 'off' : 'on', full_screen = (wind_W >= fullscreen_BP) ? 'on' : 'off'; rev_screen_obj = { fullWidth: full_width, fullScreen: full_screen }; } if (bp_arr.length) { for (var i = 0; i < bp_arr.length; i++) { var this_obj = bp_arr[i]; if (this_obj.bp && this_obj.bp.length === 2 && this_obj.bp[0] < this_obj.bp[1]) { var from = this_obj.bp[0], to = this_obj.bp[1]; if (from <= bp && to >= bp) { for (var key in this_obj) { if (key !== 'bp') rev_settings_obj[key] = this_obj[key]; } } } } } $.extend(set_rev_obj, rev_obj, rev_settings_obj, rev_screen_obj); $($sliderInit).show().revolution(set_rev_obj); $(options.functions).each(function () { this.call($sliderInit); }); }; start_Rev($sliderInit, bp); var restart_Rev = function (current_bp) { if (!$($sliderInit).hasClass('revslider-initialised')) return; bp = current_bp || 0; $sliderInit.revkill(); $sliderWrapp.replaceWith($sliderCopy); $sliderWrapp = $sliderCopy; $sliderCopy = $sliderWrapp.clone(); $sliderInit = get_Slider($sliderWrapp); start_Rev($sliderInit, bp); }; function endResize(func) { var windWidth = window.innerWidth, interval; interval = setInterval(function () { var windWidthInterval = window.innerWidth; if (windWidth === windWidthInterval) { setTimeout(function () { func(); }, 200); } clearInterval(interval); }, 100); }; $(window).on('resize', function () { endResize(function () { var current_bp = get_current_bp(); if (current_bp !== bp) restart_Rev(current_bp); }) }); }); }; var $slider = $('.slider-revolution.revolution-default'), fullscreen = $slider.attr('data-fullscreen') == 'false' ? false : 768, width = $slider.attr('data-width'), height = $slider.attr('data-height'); $('.slider-revolution.revolution-default').resizeRevolution({ slider: '.tp-banner', breakpoints: [414, 789, 1025], fullscreen_BP: fullscreen, functions: [ click_to_play_video, autoplay_video ] }, { fullScreenOffsetContainer: "header, .tt-add-full-screen", navigationArrows: "true", startwidth: width || 1920, startheight: height || 800 }, [{ bp: [0, 790], startheight: height || 1200 }]); $('.slider-revolution.revolution-static').resizeRevolution({ slider: '.tp-banner', breakpoints: [414, 789, 1025], fullscreen_BP: 790, functions: [ click_to_play_video, autoplay_video ] }, { fullScreenOffsetContainer: "header-static" }, [{ bp: [0, 790], startheight: 1300 }, { bp: [0, 1025], fullScreenOffsetContainer: "header" } ]); }; console.log('-------Cargó main.js--------'); })(jQuery); /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2006, 2014 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s); } function decode(s) { return config.raw ? s : decodeURIComponent(s); } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)); } function parseCookieValue(s) { if (s.indexOf('"') === 0) { s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { s = decodeURIComponent(s.replace(pluses, ' ')); return config.json ? JSON.parse(s) : s; } catch (e) {} } function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value; } var config = $.cookie = function (key, value, options) { if (arguments.length > 1 && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setMilliseconds(t.getMilliseconds() + days * 864e+5); } return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } var result = key ? undefined : {}, cookies = document.cookie ? document.cookie.split('; ') : [], i = 0, l = cookies.length; for (; i < l; i++) { var parts = cookies[i].split('='), name = decode(parts.shift()), cookie = parts.join('='); if (key === name) { result = read(cookie, value); break; } if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; })); /* show Modals */ jQuery(function ($) { function initnewsLetterObj($obj) { var pause = $obj.attr('data-pause'); setTimeout(function () { $obj.modal('show'); }, pause); }; $('#Modalnewsletter').on('click', '.checkbox-group', function () { $.cookie('modalnewsletter', '1', { expires: 7 }); }); $('#ModalVerifyAge').on('click', '.js-btn-close', function () { $.cookie('modalverifyage', '2', { expires: 7 }); console.log("click"); return false; }); $('#ModalDiscount').on('click', '.js-reject-discount', function () { $.cookie('modaldiscount', '3', { expires: 7 }); console.log("click"); return false; }); var $body = $('body'), modalnewsletter = $.cookie('modalnewsletter'), newsLetterObj = $('#Modalnewsletter'), modalverifyage = $.cookie('modalverifyage'), verifyageObj = $('#ModalVerifyAge'), modaldiscount = $.cookie('modaldiscount'), discountObj = $('#ModalDiscount'); if (modalnewsletter == 1) return; if (newsLetterObj.length) { initnewsLetterObj(newsLetterObj); $body.addClass('modal-newsletter'); $('#Modalnewsletter').on('click', '.modal-header .close', function () { $body.removeClass('modal-newsletter'); }); }; if (modalverifyage == 2) return; if (verifyageObj.length) { initnewsLetterObj(verifyageObj); verifyageObj.on('click', '.js-btn-close', function () { verifyageObj.find('.modal-header .close').trigger('click'); return false; }); }; if (modaldiscount == 3) return; if (discountObj.length) { initnewsLetterObj(discountObj); discountObj.on('click', '.js-reject-discount', function () { discountObj.find('.modal-header .close').trigger('click'); return false; }); }; });
const cmds = require('./cmds') module.exports.activate = (s) => { // Register subscriptions cmds.aux.reload() const disposable = cmds.aux.get_disposable() // Register commands const commands = cmds.commands() for(let i in commands) { disposable.add( atom.commands.add( 'atom-workspace', 'chlorine:' + i, commands[i] ) ) } // Register some callbacks cmds.aux.observe_editor() cmds.aux.observe_config() } module.exports.deactivate = (s) => { cmds.aux.get_disposable().dispose() } module.exports.config = cmds.config module.exports.repl = cmds.repl module.exports.ext = cmds.repl module.exports.everything_provider = cmds.everything_provider module.exports.autocomplete_provider = cmds.autocomplete_provider module.exports.status_bar_consumer = cmds.status_bar_consumer module.exports.ink_consumer = cmds.ink_consumer
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MultichainLib = require("multichain-node"); var UtilLib = require("../Utils"); var HDKeyLib = require("../secure/HDKey"); var Error_1 = require("../base/Error"); var Multichain = /** @class */ (function () { function Multichain(address, connection, asset, permissions) { this.address = address; this.asset = asset; this.permissions = permissions; this.Utils = new UtilLib.Utils(); if (connection) { this.multichain = MultichainLib(connection); } else { this.multichain = Multichain.makeConnectedMultichainObject(); } } Multichain.makeConnectionFromEnv = function () { return new MultichainConnection(Number(process.env.MULTICHAINport), process.env.MULTICHAINhost, process.env.MULTICHAINuser, process.env.MULTICHAINpass); }; Multichain.makeConnectedMultichainObject = function () { return new Multichain(process.env.MULTICHAINADDRESS, Multichain.makeConnectionFromEnv()); }; Multichain.prototype.Info = function (callback) { try { this.multichain.getInfo(callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.Connect = function (connection) { this.multichain = MultichainLib(connection); }; Multichain.prototype.Streams = function (callback) { try { this.multichain.listStreams(callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.StreamItemsByKey = function (streamName, key, callback) { var _this = this; try { this.multichain.listStreamKeyItems({ stream: streamName, key: key, verbose: true }, function (error, items) { return !!error ? callback(error, null) : _this._StreamItems(null, items, callback); }); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.StreamItemsByPublisher = function (streamName, publisherAddress, callback) { var _this = this; try { this.multichain.listStreamPublisherItems({ stream: streamName, address: publisherAddress, verbose: true }, function (error, items) { return !!error ? callback(error, null) : _this._StreamItems(null, items, callback); }); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.GrantPermissionToAddress = function (addresses, permissions, callback) { try { this.multichain.grant({ addresses: addresses, permissions: permissions }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.RevokePermissionToAddress = function (address, permissions, callback) { try { this.multichain.revoke({ addresses: address, permissions: permissions }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.ImportAddress = function (address, name, callback) { try { this.multichain.importAddress({ address: address, label: name, rescan: false }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.ImportPrivKey = function (key, callback) { this.multichain.importPrivKey([key], callback); }; Multichain.prototype.SendSignedTransaction = function (signed, callback) { this.multichain.sendRawTransaction([signed.toString("hex")], callback); }; Multichain.prototype.CreateAndSignSend = function (from, to, asset, qty, callback) { var rawRequest = {}; rawRequest[to] = {}; // TODO: Use promise with async and await instead of callback, to avoid race condition rawRequest[to][asset] = function () { return Number(qty); }; var parent = this; parent.multichain.createRawSendFrom([from.address, rawRequest], function (error, raw) { parent.SignRaw(from, raw, callback); }); }; Multichain.prototype.SignRaw = function (from, hex, callback) { var HDKey = new HDKeyLib.HDKey(); from.wif = HDKey.DeriveKeyWif(from, 0); var parent = this; try { parent.multichain.signRawTransaction([hex, [], [from.wif.wif]], callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.GetAssetBalance = function (address, asset, callback) { try { this.multichain.getAddressBalances({ minconf: 0, address: address }, function (error, result) { var balance = 0; var filtered = result.filter(function (a) { return a.name === asset; }); if (filtered.length > 0) { balance = filtered[0].qty; } return callback(null, balance); }); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.SendAssetFrom = function (from, to, amount, asset, callback) { try { this.multichain.sendAssetFrom({ from: from, to: to, asset: asset, qty: amount }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.Issue = function (to, name, qty, callback) { try { this.multichain.issue({ address: to, asset: { name: name, open: true }, qty: qty, units: 1 }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.IssueMore = function (to, name, qty, callback) { try { this.multichain.issueMore({ address: to, asset: name, qty: qty }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.CreateExchange = function (from, asset, asking, callback) { var parent = this; var assets = {}; var ask = {}; assets[asset] = 1; ask[asking] = 1; this.PrepareUnlockFrom(from, assets, function (error, unlocks) { var payload = { unlocks: unlocks, prepared: '', offer: assets, asking: ask }; try { parent.multichain.createRawExchange({ txid: payload.unlocks.txid, vout: payload.unlocks.vout, assets: ask }, function (error, raw) { payload.prepared = raw; return callback(error, payload); }); } catch (error) { callback(new Error_1.MultichainError(error), null); } }); }; Multichain.prototype.FinalizeExchange = function (hex, txid, vout, assets, callback) { try { this.multichain.completeRawExchange({ hexstring: hex, txid: txid, vout: vout, assets: assets, data: '' }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.PrepareUnlockFrom = function (from, assets, callback) { try { this.multichain.prepareLockUnspentFrom({ from: from, assets: assets, lock: true }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.PrepareUnlock = function (assets, callback) { try { this.multichain.prepareLockUnspent({ assets: assets, lock: false }, callback); } catch (error) { callback(new Error_1.MultichainError(error), null); } }; Multichain.prototype.IssueEmblem = function (to, assetName, callback) { this.Issue(to, assetName, 1, callback); }; Multichain.prototype._StreamItems = function (error, items, callback) { var itemArray = []; if (items && items.length > 0) itemArray = this._elementValueCompute(items); return callback(error, itemArray); }; Multichain.prototype._elementValueCompute = function (items) { var Utils = this.Utils; return items.map(function (element) { element.value = Utils.HexToAscii(element.data); return element; }); }; return Multichain; }()); exports.Multichain = Multichain; var MultichainConnection = /** @class */ (function () { function MultichainConnection(port, host, user, pass) { this.port = port; this.host = host; this.user = user; this.pass = pass; } return MultichainConnection; }()); exports.MultichainConnection = MultichainConnection; //# sourceMappingURL=Multichain.js.map
import { h } from 'vue' export default { name: "Gifts", vendor: "Fa", type: "Solid", tags: ["gifts"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 640 512","class":"v-icon","fill":"currentColor","data-name":"fa-gifts","innerHTML":"<path d='M240.6 194.1c1.9-30.8 17.3-61.2 44-79.8C279.4 103.5 268.7 96 256 96h-29.4l30.7-22c7.2-5.1 8.9-15.1 3.7-22.3l-9.3-13c-5.1-7.2-15.1-8.9-22.3-3.7l-32 22.9 11.5-30.6c3.1-8.3-1.1-17.5-9.4-20.6l-15-5.6c-8.3-3.1-17.5 1.1-20.6 9.4l-19.9 53-19.9-53.1C121 2.1 111.8-2.1 103.5 1l-15 5.6C80.2 9.7 76 19 79.2 27.2l11.5 30.6L58.6 35c-7.2-5.1-17.2-3.5-22.3 3.7l-9.3 13c-5.1 7.2-3.5 17.2 3.7 22.3l30.7 22H32c-17.7 0-32 14.3-32 32v352c0 17.7 14.3 32 32 32h168.9c-5.5-9.5-8.9-20.3-8.9-32V256c0-29.9 20.8-55 48.6-61.9zM224 480c0 17.7 14.3 32 32 32h160V384H224v96zm224 32h160c17.7 0 32-14.3 32-32v-96H448v128zm160-288h-20.4c2.6-7.6 4.4-15.5 4.4-23.8 0-35.5-27-72.2-72.1-72.2-48.1 0-75.9 47.7-87.9 75.3-12.1-27.6-39.9-75.3-87.9-75.3-45.1 0-72.1 36.7-72.1 72.2 0 8.3 1.7 16.2 4.4 23.8H256c-17.7 0-32 14.3-32 32v96h192V224h15.3l.7-.2.7.2H448v128h192v-96c0-17.7-14.3-32-32-32zm-272 0c-2.7-1.4-5.1-3-7.2-4.8-7.3-6.4-8.8-13.8-8.8-19 0-9.7 6.4-24.2 24.1-24.2 18.7 0 35.6 27.4 44.5 48H336zm199.2-4.8c-2.1 1.8-4.5 3.4-7.2 4.8h-52.6c8.8-20.3 25.8-48 44.5-48 17.7 0 24.1 14.5 24.1 24.2 0 5.2-1.5 12.6-8.8 19z'/>"}, ) } }
const waitUntil=require('wait-until'); const assert=require('chai').assert; //获取合约json对象 let factory_json = require("../build/contracts/Factory"); let adder_json = require("../build/contracts/Adder.json"); let tester_json = require("../build/contracts/Tester.json"); //获取vns-web3js SDK,连接本地RPC服务端口 let Web3=require('vns-web3'); let web3= new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8585')); let accounts=web3.vns.accounts; console.log("accounts:\n",accounts); //获取合约对象 let Factory = web3.vns.contract(factory_json.abi); let Tester = web3.vns.contract(tester_json.abi); let factoryAddress=[]; let testerAddress=[] ; let salt=[12,23,35,42,57,64,75]; let arr=[[2,4],[3,5],[4,6],[4,8],[5,8],[6,9],[11,21]]; let addResultArr=[6,8,10,12,13,15,32]; describe("FactoryAndTester",() => { for (let j=0;j<arr.length;j++){ //测试新部署的合约 before("deployFactoryAndTester",async () => { //deployFactoryAndTester Factory.new( { data:"0x"+factory_json.evm.bytecode.object, from:accounts[0], gas:4700000 }, (error, result)=> { if (!error) { if (typeof (result.address) != "undefined") { factoryAddress[j] = result.address; console.log("factoryAddress:", factoryAddress[j]); //deployTester(factoryAddress[i],salt[i]) console.time('Tester-deploy'+j); Tester.new( factoryAddress[j], salt[j], { data: "0x" + tester_json.evm.bytecode.object, from: accounts[0], gas: 4700000 }, //TesterCallBack (error, result)=>{ if (!error) { if (typeof(result.address)!="undefined"){ testerAddress[j] = result.address; console.log("testerAddress:", testerAddress[j]); console.timeEnd('Tester-deploy'+j); } } else { console.log("testerCallBackError:", error); } } ); let factoryInstance = Factory.at(factoryAddress[j]); let FactoryDeployed01 = factoryInstance.Deployed01({fromBlock: 4660, toBlock: 'latest'}); FactoryDeployed01.watch((error, event) => { if (!error) { console.log("FactoryDeployed01:", event.args); } else { console.log(error); } }); let FactoryDeployed02 = factoryInstance.Deployed02({fromBlock: 4660, toBlock: 'latest'}); FactoryDeployed02.watch((error, event) => { if (!error) { console.log("FactoryDeployed02:", event.args); } else { console.log(error); } }); } } else { console.log("factoryCallBackError:", error); } } ); }); it('TesterInstance_testAdd1', () => { waitUntil() .interval(500) .times(1000) .condition(function() { return (testerAddress[j]!==undefined) }) .done(async function() { // test Add1 contract'interface (Factory contract created Add1 contract) let testerInstance = Tester.at(testerAddress[j]); let res1 = await testerInstance.testAdd1.call(arr[j][0],arr[j][1]).toNumber(); console.log(arr[j][0],' + ',arr[j][1],' = ',res1); assert.equal(addResultArr[j],res1); }); }); it('TesterInstance_testAdd2', () => { waitUntil() .interval(500) .times(1000) .condition(function() { return (testerAddress[j]!==undefined) }) .done(async function() { // // test Add2 contract'interface (Factory contract created Add2 contract) let testerInstance = Tester.at(testerAddress[j]); let res2 = await testerInstance.testAdd2.call(arr[j][0],arr[j][1]).toNumber(); console.log(arr[j][0]," + ",arr[j][1]," = ",res2); assert.equal(addResultArr[j],res2); }); }); } });
// This is a manifest file that'll be compiled into application.js. // // Any JavaScript file within this directory can be referenced here using a relative path. // // You're free to add application-wide JavaScript to this file, but it's generally better // to create separate JavaScript files as needed. // //= require jquery //= require_tree . //= require_self //= require bootstrap //= require jquery-ui/js/jquery-ui-1.10.3.custom.min if (typeof jQuery !== 'undefined') { (function($) { $('#spinner').ajaxStart(function() { $(this).fadeIn(); }).ajaxStop(function() { $(this).fadeOut(); }); })(jQuery); }
import React from 'react'; import { Link } from 'react-router-dom'; import Main from '../layouts/Main'; import EmailLink from '../components/Contact/EmailLink'; import ContactIcons from '../components/Contact/ContactIcons'; const Contact = () => ( <Main title="Contact" description="Contact Arthur Gassner via email @ arth.gassner@gmail.com" > <article className="post" id="contact"> <header> <div className="title"> <h2 data-testid="heading"><Link to="/contact">Contact</Link></h2> </div> </header> <div className="email-at"> <p>Feel free to get in touch. You can email me at: </p> <EmailLink /> </div> <ContactIcons /> </article> </Main> ); export default Contact;
var results; var bot; exports.init = function( mainbot ) { bot = mainbot; mainbot.dispatch.add( 'fight', 'fight [user]', cmdFight, {maxArgs:1} ); } async function cmdFight( msg, uname ) { if ( !results ) results = require( './results.json'); if ( !uname ) return msg.channel.send( 'You attack the darkness!'); let target = bot.findUser( msg.channel, uname ); let attacker = msg.hasOwnProperty( 'member' ) ? msg.member.displayName : msg.author.username; if ( !target ) return msg.channel.send( 'I don\'t see ' + uname + ' here. So you must be talking to me. Are you talking to me?'); else if ( target.presence.status == 'offline') return msg.channel.send( attacker + ' is only brave enough to fight ' + uname + ' when they aren\'t here. How sad.' ); else if ( target.id === msg.author.id ) return msg.channel.send( attacker + ' self flagellates in public.' ); else if ( target.id === bot.client.user.id ) return msg.channel.send( bot.client.user.username + ' throws down ' + attacker + ' and smites his ruin upon the mountainside.'); else { let ind = Math.floor(results.length*Math.random() ); let result = results[ind]; result = result.replace( /%t/g, uname ); result = result.replace( /%a/g, attacker ); return msg.channel.send( result ); } }
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import { slice } from '../ops/slice'; // TODO(annxingyuan): Use this helper in WASM Split kernel once intermediate // kernels have been modularized in WebGL and CPU // https://github.com/tensorflow/tfjs/issues/2822. /** Shared implementation of the split kernel across WebGL and CPU. */ export function split(x, sizeSplits, axis) { const begin = new Array(x.rank).fill(0); const size = x.shape.slice(); return sizeSplits.map(s => { const sliceSize = [...size]; sliceSize[axis] = s; const sliceT = slice(x, begin, sliceSize); begin[axis] += s; return sliceT; }); } //# sourceMappingURL=split_shared.js.map
//>>built define("dojox/encoding/digests/_base",["dojo/_base/lang"],function(e){e=e.getObject("dojox.encoding.digests",!0);e.outputTypes={Base64:0,Hex:1,String:2,Raw:3};e.addWords=function(d,c){var a=(d&65535)+(c&65535);return(d>>16)+(c>>16)+(a>>16)<<16|a&65535};e.stringToWord=function(d){for(var c=[],a=0,b=8*d.length;a<b;a+=8)c[a>>5]|=(d.charCodeAt(a/8)&255)<<a%32;return c};e.wordToString=function(d){for(var c=[],a=0,b=32*d.length;a<b;a+=8)c.push(String.fromCharCode(d[a>>5]>>>a%32&255));return c.join("")}; e.wordToHex=function(d){for(var c=[],a=0,b=4*d.length;a<b;a++)c.push("0123456789abcdef".charAt(d[a>>2]>>8*(a%4)+4&15)+"0123456789abcdef".charAt(d[a>>2]>>8*(a%4)&15));return c.join("")};e.wordToBase64=function(d){for(var c=[],a=0,b=4*d.length;a<b;a+=3)for(var e=(d[a>>2]>>8*(a%4)&255)<<16|(d[a+1>>2]>>8*((a+1)%4)&255)<<8|d[a+2>>2]>>8*((a+2)%4)&255,f=0;4>f;f++)8*a+6*f>32*d.length?c.push("\x3d"):c.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e>>6*(3-f)&63));return c.join("")}; e.stringToUtf8=function(d){for(var c="",a=-1,b,e;++a<d.length;)b=d.charCodeAt(a),e=a+1<d.length?d.charCodeAt(a+1):0,55296<=b&&(56319>=b&&56320<=e&&57343>=e)&&(b=65536+((b&1023)<<10)+(e&1023),a++),127>=b?c+=String.fromCharCode(b):2047>=b?c+=String.fromCharCode(192|b>>>6&31,128|b&63):65535>=b?c+=String.fromCharCode(224|b>>>12&15,128|b>>>6&63,128|b&63):2097151>=b&&(c+=String.fromCharCode(240|b>>>18&7,128|b>>>12&63,128|b>>>6&63,128|b&63));return c};return e}); //# sourceMappingURL=_base.js.map
import * as React from "react"; import LoggedIn from "../Functions/LoggedIn"; import {Redirect} from 'react-router-dom'; export default class Home extends React.Component{ constructor(props){ super(props); this.state = { cookie: '', }; } render() { //Check Existence of localStorage existence if('login_info' in localStorage) { let info = JSON.parse(localStorage.getItem('login_info')); return ( <div> </div> ) } else{ return ( <div> <Redirect to='/login'/> </div> ) } } }
var path = require('path'); // Cargar ORM var Sequelize = require('sequelize'); // Usar BBDD SQLite: // DATABASE_URL = sqlite:/// // DATABASE_STORAGE = quiz.sqlite // Usar BBDD Postgres: // DATABASE_URL = postgres://user:passwd@host:port/database var url, storage; if (!process.env.DATABASE_URL) { url = "sqlite:///"; storage = "quiz.sqlite"; } else { url = process.env.DATABASE_URL; storage = process.env.DATABASE_STORAGE || ""; } var sequelize = new Sequelize(url, { storage: storage, omitNull: true }); // Importar la definicion de la tabla Quiz de quiz.js var Quiz = sequelize.import(path.join(__dirname,'quiz')); // sequelize.sync() crea e inicializa tabla de preguntas en DB sequelize.sync() .then(function() { // Ya se han creado las tablas necesarias. return Quiz.count() .then(function (c) { if (c === 0) { // la tabla se inicializa solo si está vacía return Quiz.bulkCreate([ {question: 'Capital de Italia', answer: 'Roma'}, {question: 'Capital de Portugal', answer: 'Lisboa'} ]) .then(function() { console.log('Base de datos inicializada con datos'); }); } }); }) .catch(function(error) { console.log("Error Sincronizando las tablas de la BBDD:", error); process.exit(1); }); exports.Quiz = Quiz; // exportar definición de tabla Quiz
export default function() { var node = this, nodes = [node]; while (node = node.parent) { nodes.push(node); } return nodes; }
//movie listing directive for the extended listing on Movie Page angular.module('reel-seek').directive('listingLong', function(){ return { restrict: 'E', replace: true, scope: { movie: '=movie' }, templateUrl: 'views/partials/movieListingLong.html' }; });
import React from 'react'; export const Livescript = props => ( <svg viewBox="0 0 20 20" {...props}><path d="M39,9.5 L43.5,9.5 L43.5,13.5 L37.3284271,13.5 L36.3284271,14.5 L43.5,14.5 L43.5,18.5 L32.5,18.5 L32.5,18.3284271 L30.8284271,20 L43,20 L43,24 L27,24 L27,23.8284271 L24.8284271,26 L43,26 L43,30 L21,30 L21,29.8284271 L18.8284271,32 L43,32 L43,36 L15,36 L15,35.8284271 L12.3284271,38.5 L46.5,38.5 L46.5,43.5 L10,43.5 L10,46 L5,46 L5,43.5 L2.5,43.5 L2.5,38.5 L5,38.5 L5,2 L10,2 L10,35.1715729 L12.1715729,33 L12,33 L12,5 L16,5 L16,29.1715729 L18.1715729,27 L18,27 L18,5 L22,5 L22,23.1715729 L24.1715729,21 L24,21 L24,5 L28,5 L28,17.1715729 L30,15.1715729 L30,5 L34,5 L34,11.1715729 L35,10.1715729 L35,5 L39,5 L39,9.5 Z" fillRule="evenodd" /></svg> );
import router from 'next/router'; import { toaster } from '../../functions'; import { fetch } from '../../services/api'; const signup = async (ref, data) => { try { // execute google recaptcha data['g-recaptcha-response'] = await ref.current.executeAsync(); // execute main action await fetch(`signup`, { data, withAuth: false, method: 'POST' }); // notify user and other actions toaster.success('Your account has been created'); router.push('/thank-you'); } catch ({ message }) { toaster.error(message); // reset google recaptcha on invalid login ref.current.reset(); } }; export default signup;
const utils = require("util"); function oldFunction() { console.log("This is an old function!"); } function newFunction() { console.log("This is a new function!"); } exports.oF = utils.deprecate( oldFunction, "Function is oldest. Use a newFuinction!" ); exports.nF = newFunction;
import React, { Component } from 'react'; import Router, { withRouter } from 'next/router'; import { Navbar, NavbarBrand } from 'reactstrap'; import queryString from 'query-string'; import { contentGeneralEvent, libraryProgramBackClicked, searchProgramBackClicked } from '../../../utils/appier'; import '../../../assets/scss/components/navbar.scss'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import StatusNotification from './StatusNotification'; class NavbarDetail extends Component { constructor(props) { super(props); this.state = { is_top: true }; const segments = this.props.router.asPath.split(/\?/); this.reference = null; if (segments.length > 1) { const q = queryString.parse(segments[1]); if (q.ref) { this.reference = q.ref; } } } componentDidMount() { document.addEventListener('scroll', () => { const isTop = window.scrollY < 150; if (isTop !== this.state.is_top) { this.setState({ is_top: isTop }); } }); } goBack() { if (this.props.data && this.reference) { const data = this.props.data.data; const meta = this.props.data.meta; let genre = []; for (let i = 0; i < data.genre.length; i++) { genre.push(data.genre[i].name); } switch (this.reference) { case 'homepage': contentGeneralEvent('N/A', 'program', data.id, data.title, data.title, genre.join(','), meta.image_path + '593' + data.portrait_image, meta.image_path + '593' + data.landscape_image, 'mweb_homepage_program_back_clicked'); break; case 'library': libraryProgramBackClicked(data.title, data.id, 'program', 'mweb_library_program_back_clicked'); break; case 'search': searchProgramBackClicked(data.id, data.title, 'N/A', 'N/A', 'mweb_search_program_back_clicked'); break; } } Router.back(); } render() { return ( <div className="nav-home-container nav-fixed-top"> <Navbar expand="md" className={'nav-container nav-shadow ' + (this.state.is_top ? 'nav-transparent' : '')}> <div className="top-link"> <div className={'logo-top-wrapper ' + (this.state.is_top ? 'back-arrow-transparent' : '')}> <NavbarBrand onClick={this.goBack.bind(this)} style={{ color: 'white', fontSize: '1rem' }}> <ArrowBackIcon/> </NavbarBrand> </div> </div> <div className="header-nav-verif"> <p>{this.props.title}</p> </div> </Navbar> <StatusNotification/> </div> ); } } export default withRouter(NavbarDetail);
import List from "./component"; import enhance from "./container"; export default enhance(List);
class _Emitter { constructor() { this.events = {} } // Register an event listener on(event, listener) { if (typeof this.events[event] !== 'object') { this.events[event] = [] } this.events[event].push(listener) return () => this.off(event, listener) } // Unregister an event listener off(event, listener) { if (typeof this.events[event] === 'object') { const idx = this.events[event].indexOf(listener) if (idx > -1) { this.events[event].splice(idx, 1) } } } // Register an event listener which will be destroyed once it is called once(event, listener) { const remove = this.on(event, (...args) => { remove() listener.apply(this, args) }) } // Emit an event emit(event, ...args) { const nameSpaces = event.indexOf('.') !== -1 ? event.split('.') : [event] let partialNameSpace = nameSpaces[0] nameSpaces.forEach(name => { if (partialNameSpace !== name) { partialNameSpace += `.${name}` } if (typeof this.events[partialNameSpace] === 'object') { this.events[partialNameSpace].forEach(listener => listener.apply(this, args) ) } }) } } export const Emitter = new _Emitter()
const constants = { MOUSE_DEVICE: 100, TOUCH_DEVICE: 200, POINTER_DEVICE: 300, VIRTUAL_DEVICE: 400, MOUSE_POINTER_ID: 'mouse' } export default constants;
/* Copyright 2017 Vector Creations Ltd Copyright 2017 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import dis from '../../../dispatcher'; import Modal from '../../../Modal'; import * as sdk from '../../../index'; import { _t } from '../../../languageHandler'; import { GroupMemberType } from '../../../groups'; import GroupStore from '../../../stores/GroupStore'; import AccessibleButton from '../elements/AccessibleButton'; import MatrixClientContext from "../../../contexts/MatrixClientContext"; import AutoHideScrollbar from "../../structures/AutoHideScrollbar"; export default createReactClass({ displayName: 'GroupMemberInfo', statics: { contextType: MatrixClientContext, }, propTypes: { groupId: PropTypes.string, groupMember: GroupMemberType, isInvited: PropTypes.bool, }, getInitialState: function() { return { removingUser: false, isUserPrivilegedInGroup: null, }; }, componentWillMount: function() { this._unmounted = false; this._initGroupStore(this.props.groupId); }, componentWillReceiveProps(newProps) { if (newProps.groupId !== this.props.groupId) { this._unregisterGroupStore(this.props.groupId); this._initGroupStore(newProps.groupId); } }, componentWillUnmount() { this._unmounted = true; this._unregisterGroupStore(this.props.groupId); }, _initGroupStore(groupId) { GroupStore.registerListener(groupId, this.onGroupStoreUpdated); }, _unregisterGroupStore(groupId) { GroupStore.unregisterListener(this.onGroupStoreUpdated); }, onGroupStoreUpdated: function() { if (this._unmounted) return; this.setState({ isUserInvited: GroupStore.getGroupInvitedMembers(this.props.groupId).some( (m) => m.userId === this.props.groupMember.userId, ), isUserPrivilegedInGroup: GroupStore.isUserPrivileged(this.props.groupId), }); }, _onKick: function() { const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); Modal.createDialog(ConfirmUserActionDialog, { matrixClient: this.context, groupMember: this.props.groupMember, action: this.state.isUserInvited ? _t('Disinvite') : _t('Remove from community'), title: this.state.isUserInvited ? _t('Disinvite this user from community?') : _t('Remove this user from community?'), danger: true, onFinished: (proceed) => { if (!proceed) return; this.setState({removingUser: true}); this.context.removeUserFromGroup( this.props.groupId, this.props.groupMember.userId, ).then(() => { // return to the user list dis.dispatch({ action: "view_user", member: null, }); }).catch((e) => { const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, { title: _t('Error'), description: this.state.isUserInvited ? _t('Failed to withdraw invitation') : _t('Failed to remove user from community'), }); }).finally(() => { this.setState({removingUser: false}); }); }, }); }, _onCancel: function(e) { // Go back to the user list dis.dispatch({ action: "view_user", member: null, }); }, onRoomTileClick(roomId) { dis.dispatch({ action: 'view_room', room_id: roomId, }); }, render: function() { if (this.state.removingUser) { const Spinner = sdk.getComponent("elements.Spinner"); return <div className="mx_MemberInfo"> <Spinner /> </div>; } let adminTools; if (this.state.isUserPrivilegedInGroup) { const kickButton = ( <AccessibleButton className="mx_MemberInfo_field" onClick={this._onKick}> { this.state.isUserInvited ? _t('Disinvite') : _t('Remove from community') } </AccessibleButton> ); // No make/revoke admin API yet /*const opLabel = this.state.isTargetMod ? _t("Revoke Moderator") : _t("Make Moderator"); giveModButton = <AccessibleButton className="mx_MemberInfo_field" onClick={this.onModToggle}> {giveOpLabel} </AccessibleButton>;*/ if (kickButton) { adminTools = <div className="mx_MemberInfo_adminTools"> <h3>{ _t("Admin Tools") }</h3> <div className="mx_MemberInfo_buttons"> { kickButton } </div> </div>; } } const avatarUrl = this.props.groupMember.avatarUrl; let avatarElement; if (avatarUrl) { const httpUrl = this.context.mxcUrlToHttp(avatarUrl, 800, 800); avatarElement = (<div className="mx_MemberInfo_avatar"> <img src={httpUrl} /> </div>); } const groupMemberName = ( this.props.groupMember.displayname || this.props.groupMember.userId ); return ( <div className="mx_MemberInfo" role="tabpanel"> <AutoHideScrollbar> <AccessibleButton className="mx_MemberInfo_cancel" onClick={this._onCancel}> <img src={require("../../../../res/img/cancel.svg")} width="18" height="18" className="mx_filterFlipColor" /> </AccessibleButton> { avatarElement } <h2>{ groupMemberName }</h2> <div className="mx_MemberInfo_profile"> <div className="mx_MemberInfo_profileField"> { this.props.groupMember.userId } </div> </div> { adminTools } </AutoHideScrollbar> </div> ); }, });
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(window, function() { return /******/ (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, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // 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 = 9); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */, /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splineCurve", function() { return splineCurve; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bezierCurveTo", function() { return bezierCurveTo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPointInArea", function() { return isPointInArea; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateBezierControlPoints", function() { return updateBezierControlPoints; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "none", function() { return none; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isType", function() { return isType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepCopy", function() { return deepCopy; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlainObject", function() { return isPlainObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return extend; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataRangeAndStep", function() { return getDataRangeAndStep; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeUnit", function() { return changeUnit; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatX", function() { return formatX; }); /* eslint no-param-reassign: ["error", { "props": false }]*/ /* * @author: zimyuan */ /* * 判断JavaScript对象类型的函数 * @param {} */ function is(obj, type) { const { toString } = Object.prototype; let undefined; return (type === 'Null' && obj === null) || (type === 'Undefined' && obj === undefined) || toString.call(obj).slice(8, -1) === type; } /* * 深拷贝函数 * @param {Object} oldObj: 被拷贝的对象 * @param {Object} newObj: 需要拷贝的对象 * @ return {Object} newObj: 拷贝之后的对象 */ function deepCopy(oldObj = {}, newObj = {}) { /* eslint-disable */ for (const key in oldObj) { const copy = oldObj[key]; if (oldObj === copy) continue; // 如window.window === window,会陷入死循环,需要处理一下 if (is(copy, 'Object')) { newObj[key] = deepCopy(copy, newObj[key] || {}); } else if (is(copy, 'Array')) { newObj[key] = []; newObj[key] = deepCopy(copy, newObj[key] || []); } else { newObj[key] = copy; } } /* eslint-disable */ return newObj; } function isType(type, value) { return Object.prototype.toString.call(value).match(/\s(\w+)/)[1].toLowerCase() === type; } function isPlainObject(value) { return (!!value && isType('object', value)); } function extend(destination, source) { if (!isPlainObject(destination) || !isPlainObject(source)) throw 'destination and source must be type of object'; for (const property in source) destination[property] = source[property]; return destination; } /** * 数字取整逻辑 * 在计算坐标轴的最大最小值和区间的时候,预期的效果是最大最小值都是“整数” * 这里根据数字的大小定义取整逻辑 */ function getRoundForNumber(number) { let round; // 计算出当前数组位数减一的最小数字 if (number >= 100) round = String(number).split('') .reduce(sum => sum * 10, 0.01); // 数字介于10-100之间,逢5为整 else if (number >= 10) round = 5; else if (number > 1) round = 1; else round = 0.1; return round; } function roundForNumber(number, direction) { let result; const round = getRoundForNumber(number); if (number === 0) return 0; if (direction === 'up') result = number + (round - (number % round)); else if (direction === 'down') result = number - (number % round); return result; } /** * 给定最大值最小值和区间个数,给出优化后的最大最小值和单step值 */ function getDataRangeAndStep(maxSource, minSource, step) { let max = maxSource; let min = minSource; if (max === 0) { return { max: 4, min: 0, divider: 1, multiple: 1, }; } if (max === min) { return { max: max + 2, min: (min - 2 >= 0 ? min - 2 : 0), divider: 1, multiple: 1, }; } // console.log(1, max, min, step); let multiple = 1; // 每一步的值小于1的情况,先放大100倍方便计算 if ((max - min) / step < 1) { multiple = 10000; max *= multiple; min *= multiple; } const originMax = max; // console.log(2, max, min, step); let divider = Math.round((max - min) / step); // 如果divider为0,说明值放大后,最大值和最小值差值过小;后续过程没有意义,直接返回 if (divider === 0) { return { max: 4, min: 0, divider: 1, multiple: 1, }; } // console.log(3, divider); // 先将divider降低一点,后面慢慢增加逼近满意值 divider = roundForNumber(divider, 'down'); // console.log(4, divider); // 尽量保证整个图是居中而不是贴边的 max = max + (max % divider); min = min - (min % divider); // console.log(5, max, min); // 最小值取整,因为divider也是取整的,所以最后max也是取整的 min = roundForNumber(min, 'down'); // console.log(6, min); // 逼近求理想值 const round = getRoundForNumber(divider); // console.log(8, round) let flag = true; while (flag) { // console.log( min + divider * step , originMax, max, ); const temp = min + divider * step; if (temp >= max || temp - originMax >= round * 10) flag = false; divider += round; } // console.log(9, max, min, divider); return { max: (min + divider * step) / multiple, min: min / multiple, divider: divider / multiple, multiple, }; } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function isFloat(n) { return Number(n) === n && n % 1 !== 0; } function changeUnit(value, fixedParam = 1) { let fixed = fixedParam; // value是非数字的情况,直接返回value if (!isNumeric(value)) return value; const number = parseFloat(value); let unit = ''; let divider = 1; // 小于1000的值,保留小数点 if (isFloat(value) && number < 1000) return number.toFixed(fixed); if (number < 1e3) { unit = ''; divider = 1; } else if (number >= 1e3 && number < 1e4) { unit = 'k'; divider = 1e3; } else if (number < 1e7) { unit = 'w'; divider = 1e4; } else { unit = 'kw'; divider = 1e7; } const temp = number / divider; // 如果达不到保留小数的基本要求,取整 if (temp - Math.floor(temp) < 0.5 * (0.1 ** fixed)) { fixed = 0; } return temp.toFixed(fixed) + unit; } function none() {} function formatX(length, maxXPoint) { let step = Math.ceil(length / maxXPoint); let start = 0; // 记录原始的step长度 const origin = step; while (step * (maxXPoint - 1) >= length) { step -= 1; } if (step < origin) { start = Math.floor((length - step * (maxXPoint - 1)) / 2); } return { step, start: start > 1 ? start - 1 : start }; } function splineCurve(firstPoint, middlePoint, afterPoint, t) { // Props to Rob Spencer at scaled innovation for his post on splining between points // http://scaledinnovation.com/analytics/splines/aboutSplines.html // This function must also respect "skipped" points const previous = firstPoint.skip ? middlePoint : firstPoint; const current = middlePoint; const next = afterPoint.skip ? middlePoint : afterPoint; const d01 = Math.sqrt((current.x - previous.x) ** 2 + (current.y - previous.y) ** 2); const d12 = Math.sqrt((next.x - current.x) ** 2 + (next.y - current.y) ** 2); let s01 = d01 / (d01 + d12); let s12 = d12 / (d01 + d12); // If all points are the same, s01 & s02 will be inf s01 = isNaN(s01) ? 0 : s01; s12 = isNaN(s12) ? 0 : s12; const fa = t * s01; // scaling factor for triangle Ta const fb = t * s12; return { previous: { x: current.x - fa * (next.x - previous.x), y: current.y - fa * (next.y - previous.y), }, next: { x: current.x + fb * (next.x - previous.x), y: current.y + fb * (next.y - previous.y), }, }; } /** * @private */ function bezierCurveTo(ctx, previous, target, flip) { if (!previous) { return ctx.lineTo(target.x, target.y); } ctx.bezierCurveTo( flip ? previous.controlPointPreviousX : previous.controlPointNextX, flip ? previous.controlPointPreviousY : previous.controlPointNextY, flip ? target.controlPointNextX : target.controlPointPreviousX, flip ? target.controlPointNextY : target.controlPointPreviousY, target.x, target.y, ); } function capControlPoint(pt, min, max) { return Math.max(Math.min(pt, max), min); } /** * Returns true if the point is inside the rectangle * @param {object} point - The point to test * @param {object} area - The rectangle * @returns {boolean} * @private */ function isPointInArea(point, area) { const epsilon = 0.5; // margin - to match rounded decimals return point.x > area.left - epsilon && point.x < area.right + epsilon && point.y > area.top - epsilon && point.y < area.bottom + epsilon; } function capBezierPoints(points, area) { let i; let ilen; let point; for (i = 0, ilen = points.length; i < ilen; ++i) { point = points[i]; if (!isPointInArea(point, area)) { continue; } if (i > 0 && isPointInArea(points[i - 1], area)) { point.controlPointPreviousX = capControlPoint(point.controlPointPreviousX, area.left, area.right); point.controlPointPreviousY = capControlPoint(point.controlPointPreviousY, area.top, area.bottom); } if (i < points.length - 1 && isPointInArea(points[i + 1], area)) { point.controlPointNextX = capControlPoint(point.controlPointNextX, area.left, area.right); point.controlPointNextY = capControlPoint(point.controlPointNextY, area.top, area.bottom); } } } function updateBezierControlPoints(points, area) { let i; let ilen; let point; let controlPoints; const loop = false; let prev = loop ? points[points.length - 1] : points[0]; for (i = 0, ilen = points.length; i < ilen; ++i) { point = points[i]; controlPoints = splineCurve( prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], /* options.tension*/ 0.1, ); point.controlPointPreviousX = controlPoints.previous.x; point.controlPointPreviousY = controlPoints.previous.y; point.controlPointNextX = controlPoints.next.x; point.controlPointNextY = controlPoints.next.y; prev = point; } capBezierPoints(points, area); } /***/ }), /* 3 */, /* 4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /** * 所有组件通用配置 */ /* harmony default export */ __webpack_exports__["default"] = ({ debug: false, /** * 默认的图表宽度 */ width: 414, /** * 默认的图表高度 */ height: 200, // Y轴标签的单位 unit: '', /** * Y轴标签以及toolTip的单位换算函数 * 组件内置了changeUnit函数,可以自行设置 */ changeUnit: _util_js__WEBPACK_IMPORTED_MODULE_0__["changeUnit"], /** * 图表内本身的padding */ padding: { left: 10, right: 10, top: 10, bottom: 5, }, /** * 无数据时的文案配置 * */ emptyData: { content: '暂无数据', color: 'rgb(200,200,200)', fontSize: 16, }, }); /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Base; }); /* harmony import */ var _draw_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); /* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); /* harmony import */ var _easing_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); /* harmony import */ var _Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); // 太老的库,很多变量是下滑线开头的,暂时屏蔽先 /* eslint no-underscore-dangle: "off"*/ /* eslint no-param-reassign: ["error", { "props": false }] */ /* eslint no-restricted-syntax: "off"*/ const dpr = wx.getSystemInfoSync().pixelRatio; class Base extends _draw_js__WEBPACK_IMPORTED_MODULE_0__["default"] { constructor() { super(); this._dpr = dpr; // 用于性能数据打点 this._start = 0; // 寄存最终用于渲染的数据 this._render = {}; // 为了方便调试,在调试模式下会打出性能信息 this._performance = {}; // 实际绘图区域边界点信息 this._boundary = {}; this.aniTimer = null; } /** * 通用的CTX实例方法 * */ initCTX(canvasNode) { if (canvasNode.node) { //以节点传入 this._renderType = 'h5'; this._canvas = canvasNode.node; //清晰度调整 this._canvas.width = canvasNode.width * this._dpr; this._canvas.height = canvasNode.height * this._dpr; this._canvasNode = canvasNode; this.ctx = this._canvas.getContext('2d'); this.ctx.scale(this._dpr, this._dpr); } else { //以原生ctx传入 this._renderType = 'native'; this._canvas = { width: 100, height: 100, } this.ctx = Object(_Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__["default"])(canvasNode); } } /** * 性能数据打点 */ log(performancePointName) { this._performance[performancePointName] = new Date() - this._start; } /** * 获取本实例的配置 */ getConfig(cfg, sourceConfig) { if (!Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["isPlainObject"])(cfg)) throw new Error('options must be type of Object'); for (const key in sourceConfig) { if (cfg[key] !== undefined) { if (typeof sourceConfig[key] !== typeof cfg[key]) throw new Error(`TypeMismatch:${key} must be type of ${typeof sourceConfig[key]}`); // 对于对象类型的属性,递归调用来替换 if (Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["isPlainObject"])(cfg[key])) this.getConfig(cfg[key], sourceConfig[key]); else sourceConfig[key] = cfg[key]; } } return sourceConfig; } /** * 因为可以设置padding样式,所以需要维护真实的边界点 * 才可以实现精确绘制 */ calBoundaryPoint() { const { _config } = this; const { padding } = this._config; // 实际绘图区域的左上角 this._boundary.leftTop = { x: padding.left, y: padding.top, }; // 计算实际绘图区域的左下角信息 this._boundary.leftBottom = { x: padding.left, y: (_config.height - padding.bottom), }; if (_config.xAxis) { this._boundary.leftBottom.y -= (_config.xAxis.fontSize + _config.xAxis.marginTop); } // 计算实际绘图区域的右上角信息 this._boundary.rightTop = { x: _config.width - padding.right, y: padding.top, }; this._boundary.rightBottom = { x: _config.width - padding.right, y: this._boundary.leftBottom.y, }; this._boundary.size = { width: this._boundary.rightTop.x - this._boundary.leftTop.x, height: this._boundary.leftBottom.y - this._boundary.leftTop.y, }; this._area = { ...this._boundary.size, left: this._boundary.leftTop.x, top: this._boundary.leftTop.y, right: this._boundary.rightBottom.x, bottom: this._boundary.rightBottom.y, }; this.log('calBoundaryPoint'); return this._boundary; } // 计算用于绘制的点的信息 requestAnimFrame(callback) { if (typeof requestAnimationFrame !== 'undefined') { requestAnimationFrame(callback); } else { setTimeout(callback, 1000 / 60); } } animationLopp(config, draw) { const animationCount = 1 / (config.animationStep || 1); const easingFunction = _easing_js__WEBPACK_IMPORTED_MODULE_2__["default"][config.animationEasing]; // 动画完成的百分比 let percentComplete = (config.animation ? 0 : 1); const animationFrame = () => { let easeAdjustedAnimationPercent = (config.animation ? easingFunction(percentComplete) : 1); if (easeAdjustedAnimationPercent > 1) { easeAdjustedAnimationPercent = 1; } draw.call(this, easeAdjustedAnimationPercent); }; const animationLoop = () => { percentComplete += animationCount; animationFrame(); if (percentComplete <= 1) { this.requestAnimFrame(animationLoop); } else { config.onAnimationComplete && config.onAnimationComplete(); } }; this.requestAnimFrame(animationLoop); } } /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChartBase; }); /* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* eslint no-param-reassign: ["error", { "props": false }] */ /** * 图表组件基础类,封装一些canvas画图的基本方法 * 这里可用于兼容H5和小程序 * 因为小程序和H5的绘图API并不是完全一致的,通过基础类来兼容是最合适的 */ class ChartBase { wordWidth(words, fontSize) { if (words === undefined || words === null) return 0; let totLength = 0; for (let i = 0; i < words.length; i++) { const strCode = words.charCodeAt(i); if (strCode > 128) totLength += fontSize; else totLength += fontSize / 2; } return totLength; } measureText(ctx, word) { // 低版本兼容处理 if (!ctx.measureText) { return this.getWordWidth(word); } ctx.save(); if (typeof(word.text) === 'number') { word.text = word.text.toString(); } ctx.font = `${word.fontSize}px sans-serif`; const metrics = ctx.measureText(word.text); ctx.restore(); return metrics.width; } getWordWidth(word) { if (typeof(word.text) === 'number') { word.text = word.text.toString(); } const w = this.wordWidth(word.text, word.fontSize); return Math.ceil(w); } /** * 根据给定样式绘制文字 */ drawWord(ctx, word) { if (typeof(word.text) === 'number') word.text = word.text.toString(); ctx.beginPath(); if (word.isbottom) { // ctx.setTextBaseline('bottom'); ctx.textBaseline = 'bottom'; } if (word.baseline) { // ctx.setTextBaseline(word.baseline); ctx.textBaseline = word.baseline; } // ctx.setFontSize(word.fontSize); ctx.font = `${word.fontSize}px sans-serif`; // ctx.setFillStyle(word.color); ctx.fillStyle = word.color; // ctx.setTextAlign(word.textAlign || 'left'); ctx.textAlign = word.textAlign || 'left'; ctx.fillText(word.text, word.x, word.y); ctx.stroke(); ctx.closePath(); } /** * 绘制一个矩形 支持圆角矩形 * rect = { * fillColor * x * y * widht * height * r * } */ drawRect(ctx, rect) { if (rect.r && rect.r > 0) { ctx.save(); ctx.beginPath(); // 左上弧线 ctx.arc(rect.x + rect.r, rect.y + rect.r, rect.r, 1 * Math.PI, 1.5 * Math.PI); // 左直线 ctx.moveTo(rect.x, rect.y + rect.r); ctx.lineTo(rect.x, rect.y + rect.height - rect.r); // 左下弧线 ctx.arc(rect.x + rect.r, rect.y + rect.height - rect.r, rect.r, 0.5 * Math.PI, 1 * Math.PI); // 下直线 ctx.lineTo(rect.x + rect.r, rect.y + rect.height); ctx.lineTo(rect.x + rect.width - rect.r, rect.y + rect.height); // 右下弧线 ctx.arc(rect.x + rect.width - rect.r, rect.y + rect.height - rect.r, rect.r, 0 * Math.PI, 0.5 * Math.PI); // 右直线 ctx.lineTo(rect.x + rect.width, rect.y + rect.height - rect.r); ctx.lineTo(rect.x + rect.width, rect.y + rect.r); // 右上弧线 ctx.arc(rect.x + rect.width - rect.r, rect.y + rect.r, rect.r, 1.5 * Math.PI, 2 * Math.PI); // 上直线 ctx.lineTo(rect.x + rect.width - rect.r, rect.y); ctx.lineTo(rect.x + rect.r, rect.y); // ctx.setFillStyle(rect.fillColor); ctx.fillStyle = rect.fillColor; ctx.fill(); } else { ctx.beginPath(); // ctx.setStrokeStyle(rect.fillColor); ctx.strokeStyle = rect.fillColor; // ctx.setFillStyle(rect.fillColor); ctx.fillStyle = rect.fillColor; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); ctx.closePath(); } } /** * 根据给定样式绘制线条 */ drawLine(ctx, line) { ctx.beginPath(); // ctx.setLineWidth(line.width || 1); ctx.lineWidth = line.width || 1; ctx.strokeStyle = line.color; if (line.isDash) ctx.setLineDash(line.dashPattern, line.dashOffset); ctx.moveTo(line.start.x, line.start.y); ctx.lineTo(line.end.x, line.end.y); ctx.stroke(); ctx.closePath(); ctx.setLineDash([0], 0); } drawLongLine(ctx, line) { ctx.beginPath(); // ctx.setLineWidth(line.width || 1); // ctx.setStrokeStyle(line.color); ctx.lineWidth = line.width || 1; ctx.strokeStyle = line.color; if (line.isDash) ctx.setLineDash(line.dashPattern, line.dashOffset); const points = line.points || []; for (let index = 0; index < points.length; index++) { const point = points[index]; if (index === 0) ctx.moveTo(point.x, point.y); else ctx.lineTo(point.x, point.y); } // 需要填充背景颜色要在stroke之前填充,否则边界线会发虚 if (line.fill) { // ctx.setFillStyle(line.fillColor); ctx.fillStyle = line.fillColor; ctx.fill(); } ctx.stroke(); ctx.closePath(); ctx.setLineDash([0], 0); } /** * 绘制一条由线段连接在一起的长线 * 绘制多个线条时,效率更高的做法是,创建一个包含所有线条的路径, * 然后通过单个绘制调用进行绘制。也就是说,无需分别绘制各个线条。 * 当这条线由很多线段组成的时候,可以非常显著提升性能! */ drawLongLineWithFill(ctx, points, opts = { lineWidth: 1, lineColor: '#7587db', fillColor: 'rgba(117, 135, 219, 0.3)', needFill: false, }) { ctx.save(); ctx.beginPath(); // ctx.setFillStyle(opts.fillColor); ctx.fillStyle = opts.fillColor; // ctx.setLineWidth(opts.lineWidth); ctx.lineWidth = opts.lineWidth; // ctx.setStrokeStyle(opts.lineColor); ctx.strokeStyle = opts.lineColor; const start = points[0]; const end = points[points.length - 1]; ctx.moveTo(start.x, start.y); let prev; for (let index = 1; index < points.length - 1; index++) { const point = points[index]; // if ( index === 1 ) { // ctx.moveTo(point.x, point.y); // } else { if (points[index - 1].show === false) { ctx.moveTo(point.x, point.y); } else { if (point.show !== false) { if (opts.curve) { Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["bezierCurveTo"])(ctx, prev, point); } else { ctx.lineTo(point.x, point.y); } } } // } prev = point; } ctx.stroke(); // 闭合区域 ctx.lineTo(end.x, end.y); ctx.lineTo(start.x, start.y); if (opts.needFill !== false) { ctx.fill(); } ctx.closePath(); ctx.restore(); } /** * 根据给定样式绘制一个圆 */ drawCircle(ctx, circle) { ctx.beginPath(); // ctx.setStrokeStyle(circle.strokeColor); ctx.strokeStyle = circle.strokeColor; if (circle.fillColor) { // ctx.setFillStyle(circle.fillColor); ctx.fillStyle = circle.fillColor; } // ctx.setLineWidth(circle.lineWidth || 1); ctx.lineWidth = circle.lineWidth || 1; ctx.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI); ctx.stroke(); if (circle.fillColor) ctx.fill(); ctx.closePath(); } /** * 绘制无数据文案 * */ drawEmptyData() { const config = this._config.emptyData; //清空画布 this.ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); if (this._renderType == 'h5') { this.drawWord(this.ctx, { text: config.content, fontSize: config.fontSize, textAlign: 'center', color: config.color, x: this._canvasNode.width / 2, y: this._canvasNode.height / 2, }); } else { this.drawWord(this.ctx, { text: config.content, fontSize: config.fontSize, textAlign: 'center', color: config.color, x: this._config.width / 2, y: this._config.height / 2, }); this.ctx.draw(); } } clearCanvas(ctx, width, height) { ctx.clearRect(0, 0, width, height); // ctx.draw(); } } /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // Easing functions adapted from Robert Penner's easing equations // http://www.robertpenner.com/easing/ /* eslint-disable */ /* harmony default export */ __webpack_exports__["default"] = ({ linear(t) { return t; }, easeInQuad(t) { return t * t; }, easeOutQuad(t) { return -1 * t * (t - 2); }, easeInOutQuad(t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t; return -1 / 2 * ((--t) * (t - 2) - 1); }, easeInCubic(t) { return t * t * t; }, easeOutCubic(t) { return 1 * ((t = t / 1 - 1) * t * t + 1); }, easeInOutCubic(t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t; return 1 / 2 * ((t -= 2) * t * t + 2); }, easeInQuart(t) { return t * t * t * t; }, easeOutQuart(t) { return -1 * ((t = t / 1 - 1) * t * t * t - 1); }, easeInOutQuart(t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t; return -1 / 2 * ((t -= 2) * t * t * t - 2); }, easeInQuint(t) { return 1 * (t /= 1) * t * t * t * t; }, easeOutQuint(t) { return 1 * ((t = t / 1 - 1) * t * t * t * t + 1); }, easeInOutQuint(t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t; return 1 / 2 * ((t -= 2) * t * t * t * t + 2); }, easeInSine(t) { return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1; }, easeOutSine(t) { return 1 * Math.sin(t / 1 * (Math.PI / 2)); }, easeInOutSine(t) { return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1); }, easeInExpo(t) { return (t == 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1)); }, easeOutExpo(t) { return (t == 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1); }, easeInOutExpo(t) { if (t == 0) return 0; if (t == 1) return 1; if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1)); return 1 / 2 * (-Math.pow(2, -10 * --t) + 2); }, easeInCirc(t) { if (t >= 1) return t; return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1); }, easeOutCirc(t) { return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t); }, easeInOutCirc(t) { if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1); return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1); }, easeInElastic(t) { let s = 1.70158; let p = 0; let a = 1; if (t == 0) return 0; if ((t /= 1) == 1) return 1; if (!p) p = 1 * .3; if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p)); }, easeOutElastic(t) { let s = 1.70158; let p = 0; let a = 1; if (t == 0) return 0; if ((t /= 1) == 1) return 1; if (!p) p = 1 * .3; if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1; }, easeInOutElastic(t) { let s = 1.70158; let p = 0; let a = 1; if (t == 0) return 0; if ((t /= 1 / 2) == 2) return 1; if (!p) p = 1 * (.3 * 1.5); if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p)); return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * .5 + 1; }, easeInBack(t) { const s = 1.70158; return 1 * (t /= 1) * t * ((s + 1) * t - s); }, easeOutBack(t) { const s = 1.70158; return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1); }, easeInOutBack(t) { let s = 1.70158; if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)); return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); }, easeInBounce(t) { return 1 - animationOptions.easeOutBounce(1 - t); }, easeOutBounce(t) { if ((t /= 1) < (1 / 2.75)) { return 1 * (7.5625 * t * t); } if (t < (2 / 2.75)) { return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + .75); } if (t < (2.5 / 2.75)) { return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375); } return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375); }, easeInOutBounce(t) { if (t < 1 / 2) return animationOptions.easeInBounce(t * 2) * .5; return animationOptions.easeOutBounce(t * 2 - 1) * .5 + 1 * .5; }, }); /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Native2H5CTX; }); /** * * 原生Canvas绘图上下文胶水层 * 支持大部分 H5 Canvas API 直接转化为 原生CanvasAPI * 原生CanvasAPI也可以直接使用 * * 使用方法: * import Native2H5CTX from './base/Native2H5CTX.js'; const ctx = Native2H5CTX(nativeCtx); 请注意:由于原生API需要 draw() 完成最终渲染,因此开发者需要手动判断并执行 ctx.draw() * * * */ /** * 转化管理器 * */ class CONVERT { /** * Font 定义差异 * 原生Canvas仅支持设置 FontSize 因此要读取大小后直接设置,忽略文字字体的定义 * */ font(target, value) { const result = /[0-9]+px/i.exec(value); if (!result) { throw new Error('font 所接收的参数值不符合期望 例: ctx.font = \'23px\''); } const fontSize = result[0].slice(0, -2); target.setFontSize(fontSize); return true; } /** * lineWidth 定义差异 * 原生 lineWidth 采用 setLineWidth 进行设置 * */ lineWidth(target, value) { target.setLineWidth(value); return true; } /** * strokeStyle 定义差异 * 原生 strokeStyle 采用 setStrokeStyle 进行设置 * */ strokeStyle(target, value) { target.setStrokeStyle(value); return true; } /** * fillStyle 定义差异 * 原生 fillStyle 采用 setFillStyle 进行设置 * */ fillStyle(target, value) { target.setFillStyle(value); return true; } /** * textBaseline 定义差异 * 原生 textBaseline 采用 setTextBaseline 进行设置 * */ textBaseline(target, value) { target.setTextBaseline(value); return true; } /** * textAlign 定义差异 * 原生 textAlign 采用 setTextAlign 进行设置 * */ textAlign(target, value) { target.setTextAlign(value); return true; } } const convert = new CONVERT(); function Native2H5CTX(nativeCtx) { Object.defineProperty(nativeCtx, 'font', { set(v) { convert.font.apply(null, [nativeCtx, v]); }, }); Object.defineProperty(nativeCtx, 'lineWidth', { set(v) { convert.lineWidth.apply(null, [nativeCtx, v]); }, }); Object.defineProperty(nativeCtx, 'strokeStyle', { set(v) { convert.strokeStyle.apply(null, [nativeCtx, v]); }, }); Object.defineProperty(nativeCtx, 'fillStyle', { set(v) { convert.fillStyle.apply(null, [nativeCtx, v]); }, }); Object.defineProperty(nativeCtx, 'textBaseline', { set(v) { convert.textBaseline.apply(null, [nativeCtx, v]); }, }); Object.defineProperty(nativeCtx, 'textAlign', { set(v) { convert.textAlign.apply(null, [nativeCtx, v]); }, }); return nativeCtx; } /***/ }), /* 9 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BarChart; }); /* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _config_barchart_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10); /* harmony import */ var _base_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); /* harmony import */ var _base_Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); // 太老的库,很多变量是下滑线开头的,暂时屏蔽先 /* eslint no-underscore-dangle: "off"*/ /* eslint no-param-reassign: ["error", { "props": false }] */ /** * 小程序折线图绘制组件 */ class BarChart extends _base_index_js__WEBPACK_IMPORTED_MODULE_2__["default"] { /** * @param { canvasNode } canvasNode: canvas节点句柄 * @param { Object } cfg: 组件配置 */ constructor(canvasNode, cfg = {}) { super(); this.initCTX(canvasNode); this.chartType = 'bar'; /** * 约定!所有的内部变量都需要这里先声明 * 可以大大提高源码阅读性 */ // 本实例配置文件 this._config = this.getConfig(cfg, Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["deepCopy"])(_config_barchart_js__WEBPACK_IMPORTED_MODULE_1__["default"])); // 线条数据 this._datasets = []; } calLabelDataForItem(x, yStartParam, barLabel) { let yStart = yStartParam; const labelArr = (Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["isType"])('array', barLabel) ? barLabel : [barLabel]); let height = 0; const arr = []; labelArr.forEach((item) => { const labelConfig = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["deepCopy"])(this._config.barLabelStyle); const obj = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["isType"])('object', item) ? item : { name: item, style: labelConfig }; obj.style = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["extend"])(labelConfig, obj.style || {}); yStart -= obj.style.paddingBottom; height += obj.style.paddingBottom; arr.push({ text: obj.name || '', color: obj.style.color, fontSize: obj.style.fontSize, x, y: yStart, textAlign: 'center', }); yStart -= obj.style.fontSize; height += obj.style.fontSize; }); return { arr, height }; } calBarData() { const config = this._config; const render = this._render; const { barWidth } = config.barStyle; const { xCenterAxis } = render; const first = this._datasets[0]; const second = this._datasets[1]; const count = first.points.length; const { leftBottom } = this._boundary; let totalBarWidth = this._datasets.length * count * barWidth; if (second) { totalBarWidth += this._config.barStyle.compareBarMargin * count; } // 每组柱子的间距 const padding = this._config.barStyle.leftRightPadding * 2; const barPadding = (xCenterAxis.end.x - xCenterAxis.start.x - totalBarWidth - padding) / (count - 1); // 柱子的X轴开始位置 let xStart = xCenterAxis.start.x + this._config.barStyle.leftRightPadding; render.bars = []; render.barLabels = []; render.topbarLabels = []; const { xAxis } = config; const bottom = leftBottom.y + xAxis.marginTop + xAxis.fontSize; const { barStyle } = config; first.points.forEach((point, index) => { point.fillColor = first.fillColor || barStyle.fillColor; const barArr = [point]; if (second) { const cBar = second.points[index]; cBar.fillColor = second.fillColor || barStyle.fillColor; barArr.push(cBar); } let centerX = xStart + barWidth / 2; barArr.forEach((bar, barIndex) => { const height = (bar.value - render.min) * render.unitY * render.yMultiple; const y = leftBottom.y - height; const rect = { fillColor: bar.fillColor, x: xStart, y, width: barWidth, height, }; render.bars.push(rect); if (bar.barLabel) { const { arr } = this.calLabelDataForItem(xStart + barWidth / 2 + 1, y, bar.barLabel); render.topbarLabels = this._render.topbarLabels.concat(arr); } xStart += barWidth; if (second && barIndex === 0) { xStart += config.barStyle.compareBarMargin; centerX += (barWidth / 2 + config.barStyle.compareBarMargin / 2) + 0.5; } else { xStart += barPadding; } }); // X轴的标签 this._render.barLabels.push({ text: point.label || '', color: xAxis.color, fontSize: xAxis.fontSize, x: centerX, y: bottom, textAlign: 'center', }); }); } calXAxisLines() { const { yAxisWidth } = this._render; const { leftBottom } = this._boundary; const { rightBottom } = this._boundary; const { xAxisLine } = this._config; // 计算X轴中轴线数据 this._render.xCenterAxis = { start: { x: leftBottom.x + yAxisWidth, y: leftBottom.y, }, end: { x: rightBottom.x, y: leftBottom.y, }, width: xAxisLine.width, color: xAxisLine.color, }; } calYAxisLines() { const data = this._render; const { yAxisWidth } = data; const { leftTop } = this._boundary; const { leftBottom } = this._boundary; const rightTop = this._boundary.rightBottom; const { yAxisLine } = this._config; // 计算Y轴中轴线数据 this._render.yCenterAxis = { start: { x: leftTop.x + yAxisWidth, y: leftTop.y, }, end: { x: leftTop.x + yAxisWidth, y: leftBottom.y, }, width: yAxisLine.width, color: yAxisLine.color, }; this._render.yAxisLines = []; this._render.yAxisData.forEach((item, index) => { if (index > 0) { this._render.yAxisLines.push({ start: { x: item.x + yAxisWidth, y: item.y, }, end: { x: rightTop.x, y: item.y, }, width: yAxisLine.width, color: yAxisLine.color, }); } }); } /** * 计算Y轴的边界和阶梯值 */ calYAxis() { const { max, min, yDivider, maxYPoint, longestLine } = this.calYAxisBoundary(); let maxItem; this._datasets.forEach((dataset) => { dataset.points.forEach((item) => { if (!maxItem) { maxItem = item; } else { if (item.value > maxItem.value) { maxItem = item; } } }); }); const { height } = this.calLabelDataForItem(0, 0, maxItem.barLabel || []); const { yAxis } = this._config; // 用于绘制的数据 const yAxisData = []; // Y轴文案所占据的宽度 let yAxisWidth = 0; const cHeight = this._boundary.leftBottom.y - this._boundary.leftTop.y; // 计算Y轴上两个点之间的像素值 let unitY = cHeight / (yDivider * this._render.yMultiple * this._config.yAxis.yAxisCount); /** * 计算最长的条加上label之后的高度,如果超过绘图边界,将unitY更改成刚好使得最长的条填充满绘图区 * 这里仍然存在一种可能,很短的条有很多label导致超过绘图边界,不予考虑 */ const maxH = (maxItem.value - min) * unitY * this._render.yMultiple; if (maxH + height > cHeight) { unitY = (cHeight - height) / (maxItem.value - min) / this._render.yMultiple; } const leftStart = this._boundary.leftTop.x + yAxis.marginLeft; const bottomStart = this._boundary.leftBottom.y; const changeFunc = (this._config.changeUnit && this._config.changeUnit !== _util_js__WEBPACK_IMPORTED_MODULE_0__["none"] ? this._config.changeUnit : _util_js__WEBPACK_IMPORTED_MODULE_0__["changeUnit"]); const toFixed = ((max < 1 || max > 1e7) ? 2 : 1); for (let i = 0; i < this._config.yAxis.yAxisCount + 1; i++) { const word = { text: changeFunc(min + i * yDivider, toFixed) + this._config.yAxis.unit, color: yAxis.color, fontSize: yAxis.fontSize, x: leftStart, y: bottomStart - (i * yDivider * unitY * this._render.yMultiple), }; yAxisWidth = Math.max(this.getWordWidth(word), yAxisWidth); yAxisData.push(word); } // 考虑Y轴不需要文案的情况 yAxisWidth = (yAxis.show ? yAxisWidth + yAxis.marginRight : 0); this._render.unitY = unitY; this._render.yAxisWidth = yAxisWidth; this._render.yAxisData = yAxisData; this._render.longestLinePointCnt = maxYPoint; this._render.longestLine = longestLine; this.log('calYAxis'); } getMinY(data) { return data.reduce( (min, p) => (p.value < min ? p.value : min), data[0].value, ); } getMaxY(data) { return data.reduce( (max, p) => (p.value > max ? p.value : max), data[0].value, ); } /** * 计算用于Y轴绘制需要的数据 * https://codeburst.io/javascript-finding-minimum-and-maximum-values-in-an-array-of-objects-329c5c7e22a2 */ calYAxisBoundary() { const datasets = this._datasets; let maxYPoint = 0; let longestLine = datasets[0]; const { yAxisCount } = this._config.yAxis; let max = -Infinity; let min = Infinity; datasets.forEach((oneline) => { const points = oneline.points || []; if (points.length > maxYPoint) { maxYPoint = points.length; longestLine = oneline; } max = Math.max(this.getMaxY(points), max); min = Math.min(this.getMinY(points), min); }); const formatFunc = this._config.formatY || _util_js__WEBPACK_IMPORTED_MODULE_0__["getDataRangeAndStep"]; const range = formatFunc(max, min, yAxisCount); this._render.min = range.min; this._render.max = range.max; this._render.yMultiple = range.multiple || 1; return { max: range.max, min: range.min, yDivider: range.divider, maxYPoint, longestLine, }; } // 绘制X轴 drawXAxis() { if (this._config.xAxisLine.centerShow) { this.drawLine(this.ctx, this._render.xCenterAxis); } } // 绘制Y轴 drawYAxis() { // 绘制Y轴文案 if (this._config.yAxis.show) { this._render.yAxisData.forEach((item) => { this.drawWord(this.ctx, item); }); } // 根据配置来决定是否绘制Y中心轴 if (this._config.yAxis.centerShow) { this.drawLine(this.ctx, this._render.yCenterAxis); } } // 绘制Y轴横线 drawYAxisLine() { if (this._config.yAxisLine.show) { this._render.yAxisLines.forEach((line) => { this.drawLine(this.ctx, line); }); } } /** * 绘制所有的点 */ drawPoints() { this._render.pointData.forEach((oneline) => { if (oneline.points.length > 1) this.drawLongLineWithFill(this.ctx, oneline.points, oneline.style); }); this._render.circlePoints.forEach((point) => { this.drawCircle(this.ctx, point); }); } drawBars() { this._render.bars.forEach((bar) => { this.drawRect(this.ctx, bar); }); this._render.barLabels.forEach((label) => { this.drawWord(this.ctx, label); }); this._render.topbarLabels.forEach((label) => { this.drawWord(this.ctx, label); }); } /** * 将处理后的合法数据按照配置绘制到canvas上面 */ drawToCanvas() { //清空画布 this.ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); this.drawYAxis(); this.log('drawYAxis'); this.drawYAxisLine(); this.log('drawYAxisLine'); this.drawXAxis(); this.log('drawXAxis'); this.drawBars(); this.log('drawPoints'); } /** * 数据清洗和合法性判断 * 数据字段比较多,存在后面的函数调用依赖前面的计算结果的情况 * 因此不能随便调换initData里面的函数顺序 */ initData(data) { this._datasets = (data.datasets || []).filter(dataset => !!dataset.points && dataset.points.length); if (!this._datasets.length) { return; } // 为了绘制精确,首先要计算绘制的边界值,防止样式走位 this.calBoundaryPoint(); // 计算Y轴数据 this.calYAxis(); // 计算Y轴线条数据 this.calYAxisLines(); // 计算X轴线条数据 this.calXAxisLines(); this.calBarData(); this.log('initData'); } /** * 实际的绘制函数 */ draw(data, cfg = {}) { this._start = new Date(); this.getConfig(cfg, this._config); this.initData(data); if (!this._datasets.length) { this.drawEmptyData(); return; } this.drawToCanvas(); if (this._renderType == 'native') this.ctx.draw(); this.log('realDraw'); if (this._config.debug) { console.log(this._performance); } } } /***/ }), /* 10 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); /* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); const barchartConfig = { /** * 给定一组数据,Y轴标签的最大值最小值和每一步的值都是组件自动算出来的 * 有些场景组件算出来的可能不满足需求,或者调用者就是想自定义Y轴标签的数据, * 因此提供自定义的formatY(max, min, yAxisCount)函数,调用者按要求返回数据给组件处理即可 * @return { * max: 将原始的最大值处理之后的最大值 * min: 将原始的最小值处理之后的最小值 * divider: 每一步的值 * multiple: 如果处理过程中发现divider是小于1的小数,需要将上面三个数值相对应放大一定倍数 * 似的divider是大于1的数值,同时将放大的倍数告知组件,默认为1 * } */ formatY: null, // x轴文案的样式配置 xAxis: { show: true, marginTop: 10, color: '#B8B8B8', fontSize: 11, }, /** * X轴轴体的样式配置 */ xAxisLine: { show: false, centerShow: true, width: 0.6, color: '#C6C6C6', style: 'solid', }, /** * y轴的样式配置 */ yAxis: { show: true, marginLeft: 0, marginRight: 10, color: '#B8B8B8', fontSize: 11, unit: '', /** * 默认Y轴打四个点 * 也可以自行配置,但仍然会有保底逻辑 */ yAxisCount: 4, }, /** * Y轴轴体的样式 */ yAxisLine: { show: true, centerShow: false, width: 0.2, color: '#C6C6C6', }, barStyle: { fillColor: '#6684C7', compareBarMargin: 5, barWidth: 30, leftRightPadding: 10, }, barLabelStyle: { color: '#B8B8B8', fontSize: 11, paddingBottom: 5, }, }; /* harmony default export */ __webpack_exports__["default"] = (Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["extend"])(barchartConfig, _common_js__WEBPACK_IMPORTED_MODULE_0__["default"])); /***/ }) /******/ ]); });
import {expect} from 'chai'; import {mount} from 'enzyme'; import React from 'react'; import sinon from 'sinon'; import {AsyncTypeahead} from '../../src/'; import {change, focus, getMenuItems, keyDown, search} from '../helpers'; import {DOWN, RETURN} from '../../src/constants/keyCode'; describe('<AsyncTypeahead>', () => { let onSearch, wrapper; beforeEach(() => { onSearch = sinon.spy(); wrapper = mount( <AsyncTypeahead delay={0} isLoading={false} onSearch={onSearch} /> ); }); it('should display a search prompt when focused', () => { const promptText = 'Prompt text'; wrapper.setProps({ minLength: 0, promptText, }); focus(wrapper); const menuItems = getMenuItems(wrapper); expect(menuItems.length).to.equal(1); expect(menuItems.text()).to.equal(promptText); }); it('should display the search text while searching', (done) => { const searchText = 'Search text'; wrapper.setProps({searchText}); search(wrapper, 'search', () => { focus(wrapper); const menuItems = getMenuItems(wrapper); expect(menuItems.length).to.equal(1); expect(menuItems.text()).to.equal(searchText); done(); }); }); it('should display the empty label if there are no results', (done) => { const emptyLabel = 'empty label'; wrapper.setProps({ emptyLabel, isLoading: true, useCache: false, }); search(wrapper, 'search', () => { wrapper.setProps({isLoading: false}); focus(wrapper); const menuItems = getMenuItems(wrapper); expect(menuItems.length).to.equal(1); expect(menuItems.text()).to.equal(emptyLabel); done(); }); }); it('should delay the search by at least the specified amount', (done) => { const delay = 100; const preSearch = Date.now(); wrapper = mount( <AsyncTypeahead delay={delay} isLoading={false} onSearch={(query) => { expect(Date.now() - preSearch).to.be.at.least(delay); done(); }} /> ); // Perform search. change(wrapper, 'search'); }); it('should not call onSearch when a selection is made', (done) => { let selected = []; wrapper.setProps({ minLength: 0, onChange: (s) => selected = s, }); search(wrapper, 'o', () => { wrapper.setProps({ options: ['one', 'two', 'four'], }); focus(wrapper); keyDown(wrapper, DOWN); keyDown(wrapper, RETURN); expect(selected.length).to.equal(1); expect(onSearch.calledOnce).to.equal(true); done(); }); }); it('should use cached results and not perform a new search', (done) => { wrapper.setProps({isLoading: true}); // Initial search search(wrapper, 'search', () => { wrapper.setProps({ isLoading: false, options: [], }); expect(onSearch.callCount).to.equal(1); // Second search search(wrapper, 'newSearch', () => { wrapper.setProps({ isLoading: false, options: [], }); expect(onSearch.callCount).to.equal(2); // Perform the original search again. search(wrapper, 'search', () => { expect(onSearch.callCount).to.equal(2); done(); }); }); }); }); it('should not use cached results', (done) => { wrapper.setProps({ isLoading: true, useCache: false, }); // Initial search search(wrapper, 'search', () => { wrapper.setProps({isLoading: false, options: []}); expect(onSearch.callCount).to.equal(1); // Perform the search again. search(wrapper, 'search', () => { expect(onSearch.callCount).to.equal(2); done(); }); }); }); it('should perform a search when there is already a selection', (done) => { wrapper.setProps({ multiple: true, options: ['one', 'two'], selected: ['one'], }); search(wrapper, 'two', () => { expect(onSearch.callCount).to.equal(1); done(); }); }); it('receives an event as the second argument of `onInputChange`', () => { wrapper.setProps({ onInputChange: (text, e) => { expect(text).to.equal('x'); expect(e).to.not.equal(undefined); }, }); change(wrapper, 'x'); }); });
(self.webpackChunkfurion=self.webpackChunkfurion||[]).push([[7555],{3905:function(t,e,n){"use strict";n.d(e,{Zo:function(){return u},kt:function(){return m}});var r=n(7294);function o(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function a(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function p(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?a(Object(n),!0).forEach((function(e){o(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function i(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},a=Object.keys(t);for(r=0;r<a.length;r++)n=a[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(r=0;r<a.length;r++)n=a[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}var l=r.createContext({}),c=function(t){var e=r.useContext(l),n=e;return t&&(n="function"==typeof t?t(e):p(p({},e),t)),n},u=function(t){var e=c(t.components);return r.createElement(l.Provider,{value:e},t.children)},d={inlineCode:"code",wrapper:function(t){var e=t.children;return r.createElement(r.Fragment,{},e)}},s=r.forwardRef((function(t,e){var n=t.components,o=t.mdxType,a=t.originalType,l=t.parentName,u=i(t,["components","mdxType","originalType","parentName"]),s=c(n),m=o,h=s["".concat(l,".").concat(m)]||s[m]||d[m]||a;return n?r.createElement(h,p(p({ref:e},u),{},{components:n})):r.createElement(h,p({ref:e},u))}));function m(t,e){var n=arguments,o=e&&e.mdxType;if("string"==typeof t||o){var a=n.length,p=new Array(a);p[0]=s;var i={};for(var l in e)hasOwnProperty.call(e,l)&&(i[l]=e[l]);i.originalType=t,i.mdxType="string"==typeof t?t:o,p[1]=i;for(var c=2;c<a;c++)p[c]=n[c];return r.createElement.apply(null,p)}return r.createElement.apply(null,n)}s.displayName="MDXCreateElement"},6169:function(t,e,n){"use strict";n.r(e),n.d(e,{frontMatter:function(){return p},contentTitle:function(){return i},metadata:function(){return l},toc:function(){return c},default:function(){return d}});var r=n(4034),o=n(9973),a=(n(7294),n(3905)),p=(n(4996),{slug:"httpcontext",title:"1. HttpContext \u5e94\u7528",author:"dotNET China",author_title:"\u8ba9 .NET \u5f00\u53d1\u66f4\u7b80\u5355\uff0c\u66f4\u901a\u7528\uff0c\u66f4\u6d41\u884c\u3002",author_url:"https://www.chinadot.net",author_image_url:"https://i.loli.net/2021/01/19/M8q5a3OTZWUKicl.png",tags:["furion","furos",".net",".netcore",".net5","httpcontext"]}),i=void 0,l={permalink:"/furion/blog/httpcontext",editUrl:"https://gitee.com/dotnetchina/Furion/tree/master/handbook/blog/2021-02-01-httpcontext.mdx",source:"@site/blog/2021-02-01-httpcontext.mdx",title:"1. HttpContext \u5e94\u7528",description:"HttpContext \u91cd\u5927\u8c03\u6574",date:"2021-02-01T00:00:00.000Z",formattedDate:"February 1, 2021",tags:[{label:"furion",permalink:"/furion/blog/tags/furion"},{label:"furos",permalink:"/furion/blog/tags/furos"},{label:".net",permalink:"/furion/blog/tags/net"},{label:".netcore",permalink:"/furion/blog/tags/netcore"},{label:".net5",permalink:"/furion/blog/tags/net-5"},{label:"httpcontext",permalink:"/furion/blog/tags/httpcontext"}],readingTime:.775,truncated:!0,prevItem:{title:"2. \u6587\u4ef6\u4e0a\u4f20\u4e0b\u8f7d",permalink:"/furion/blog/fileupload-download"}},c=[{value:"HttpContext \u91cd\u5927\u8c03\u6574",id:"httpcontext-\u91cd\u5927\u8c03\u6574",children:[]},{value:"HttpContext \u591a\u79cd\u83b7\u53d6\u65b9\u5f0f",id:"httpcontext-\u591a\u79cd\u83b7\u53d6\u65b9\u5f0f",children:[{value:"\u5728 <code>ControllerBase</code> \u6d3e\u751f\u7c7b\u4e2d",id:"\u5728-controllerbase-\u6d3e\u751f\u7c7b\u4e2d",children:[]},{value:"\u901a\u8fc7\u6ce8\u5165 <code>IHttpContextAccessor</code>",id:"\u901a\u8fc7\u6ce8\u5165-ihttpcontextaccessor",children:[]},{value:"\u901a\u8fc7 <code>HttpContextLocal</code> \u9759\u6001\u7c7b",id:"\u901a\u8fc7-httpcontextlocal-\u9759\u6001\u7c7b",children:[]},{value:"\u901a\u8fc7 <code>App.HttpContext</code>",id:"\u901a\u8fc7-apphttpcontext",children:[]}]},{value:"<code>HttpContext</code> \u62d3\u5c55\u65b9\u6cd5",id:"httpcontext-\u62d3\u5c55\u65b9\u6cd5",children:[{value:"\u83b7\u53d6\u5f53\u524d\u8bf7\u6c42\u7684\u7279\u6027",id:"\u83b7\u53d6\u5f53\u524d\u8bf7\u6c42\u7684\u7279\u6027",children:[]},{value:"\u8bbe\u7f6e <code>Swagger</code> \u81ea\u52a8\u6388\u6743",id:"\u8bbe\u7f6e-swagger-\u81ea\u52a8\u6388\u6743",children:[]},{value:"\u9000\u51fa <code>Swagger</code> \u6388\u6743",id:"\u9000\u51fa-swagger-\u6388\u6743",children:[]},{value:"\u83b7\u53d6\u672c\u5730 IP \u5730\u5740",id:"\u83b7\u53d6\u672c\u5730-ip-\u5730\u5740",children:[]},{value:"\u83b7\u53d6\u5ba2\u6237\u7aef IP \u5730\u5740",id:"\u83b7\u53d6\u5ba2\u6237\u7aef-ip-\u5730\u5740",children:[]},{value:"\u5224\u65ad\u662f\u5426\u662f <code>Ajax</code> \u8bf7\u6c42",id:"\u5224\u65ad\u662f\u5426\u662f-ajax-\u8bf7\u6c42",children:[]}]}],u={toc:c};function d(t){var e=t.components,n=(0,o.Z)(t,["components"]);return(0,a.kt)("wrapper",(0,r.Z)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,a.kt)("h2",{id:"httpcontext-\u91cd\u5927\u8c03\u6574"},"HttpContext \u91cd\u5927\u8c03\u6574"),(0,a.kt)("p",null,"\u5728 ",(0,a.kt)("inlineCode",{parentName:"p"},"ASP.NET")," \u7684\u65f6\u4ee3\uff0c\u6211\u4eec\u901a\u5e38\u901a\u8fc7 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u5168\u5c40\u9759\u6001\u7c7b\u83b7\u53d6\u8bf7\u6c42\u4e0a\u4e0b\u6587\uff0c\u4f46\u5728 ",(0,a.kt)("inlineCode",{parentName:"p"},"ASP.NET Core")," \u4e2d\uff0c",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u662f\u4e00\u4e2a\u975e\u9759\u6001\u7684\u62bd\u8c61\u7c7b\uff0c\u65e0\u6cd5\u624b\u52a8\u521b\u5efa\uff0c\u4e5f\u65e0\u6cd5\u901a\u8fc7\u9759\u6001\u83b7\u53d6\u3002"),(0,a.kt)("p",null,"\u867d\u7136\u5728 ",(0,a.kt)("inlineCode",{parentName:"p"},"ASP.NET Core")," \u4e2d\u65e0\u6cd5\u76f4\u63a5\u83b7\u53d6 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u5bf9\u8c61\u3002\u4f46\u662f\u5fae\u8f6f\u4e5f\u63d0\u4f9b\u4e86\u6ce8\u5165 ",(0,a.kt)("inlineCode",{parentName:"p"},"IHttpContextAccessor")," \u65b9\u5f0f\u83b7\u53d6\u3002"),(0,a.kt)("h2",{id:"httpcontext-\u591a\u79cd\u83b7\u53d6\u65b9\u5f0f"},"HttpContext \u591a\u79cd\u83b7\u53d6\u65b9\u5f0f"),(0,a.kt)("h3",{id:"\u5728-controllerbase-\u6d3e\u751f\u7c7b\u4e2d"},"\u5728 ",(0,a.kt)("inlineCode",{parentName:"h3"},"ControllerBase")," \u6d3e\u751f\u7c7b\u4e2d"),(0,a.kt)("p",null,"\u5728 ",(0,a.kt)("inlineCode",{parentName:"p"},"ControllerBase")," \u6d3e\u751f\u7c7b\u4e2d\uff0c\u6211\u4eec\u53ef\u4ee5\u76f4\u63a5\u901a\u8fc7 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u5c5e\u6027\u83b7\u53d6 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u5bf9\u8c61\u3002"),(0,a.kt)("h3",{id:"\u901a\u8fc7\u6ce8\u5165-ihttpcontextaccessor"},"\u901a\u8fc7\u6ce8\u5165 ",(0,a.kt)("inlineCode",{parentName:"h3"},"IHttpContextAccessor")),(0,a.kt)("p",null,"\u5728 ",(0,a.kt)("inlineCode",{parentName:"p"},"Furion")," \u6846\u67b6\u4e2d\uff0c\u9ed8\u8ba4\u5df2\u7ecf\u6ce8\u518c\u4e86 ",(0,a.kt)("inlineCode",{parentName:"p"},"IHttpContextAccessor")," \u670d\u52a1\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u6784\u9020\u51fd\u6570\u6ce8\u5165\u8be5\u5bf9\u8c61\u83b7\u53d6\u3002"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs",metastring:"{3,5}","{3,5}":!0},"public class AppService\n{\n public AppService(IHttpContextAccessor httpContextAccessor)\n {\n var httpContext = httpContextAccessor.HttpContext;\n }\n}\n")),(0,a.kt)("h3",{id:"\u901a\u8fc7-httpcontextlocal-\u9759\u6001\u7c7b"},"\u901a\u8fc7 ",(0,a.kt)("inlineCode",{parentName:"h3"},"HttpContextLocal")," \u9759\u6001\u7c7b"),(0,a.kt)("p",null,(0,a.kt)("inlineCode",{parentName:"p"},"Furion")," \u6846\u67b6\u63d0\u4f9b\u4e86 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContextLocal")," \u9759\u6001\u7c7b\u65b9\u5f0f\u83b7\u53d6 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext"),"\uff0c\u5982\uff1a"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"var HttpContext = HttpContextLocal.Current();\n")),(0,a.kt)("h3",{id:"\u901a\u8fc7-apphttpcontext"},"\u901a\u8fc7 ",(0,a.kt)("inlineCode",{parentName:"h3"},"App.HttpContext")),(0,a.kt)("p",null,(0,a.kt)("inlineCode",{parentName:"p"},"App")," \u9759\u6001\u7c7b\u4e5f\u63d0\u4f9b\u4e86 ",(0,a.kt)("inlineCode",{parentName:"p"},"App.HttpContext")," \u83b7\u53d6 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u5bf9\u8c61\u3002"),(0,a.kt)("h2",{id:"httpcontext-\u62d3\u5c55\u65b9\u6cd5"},(0,a.kt)("inlineCode",{parentName:"h2"},"HttpContext")," \u62d3\u5c55\u65b9\u6cd5"),(0,a.kt)("p",null,(0,a.kt)("inlineCode",{parentName:"p"},"Furion")," \u6846\u67b6\u4e5f\u63d0\u4f9b\u4e86\u4e00\u4e9b\u5e38\u7528\u7684 ",(0,a.kt)("inlineCode",{parentName:"p"},"HttpContext")," \u62d3\u5c55\u65b9\u6cd5"),(0,a.kt)("h3",{id:"\u83b7\u53d6\u5f53\u524d\u8bf7\u6c42\u7684\u7279\u6027"},"\u83b7\u53d6\u5f53\u524d\u8bf7\u6c42\u7684\u7279\u6027"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"var attribute = httpContext.GetMetadata<SomeAttribute>();\n")),(0,a.kt)("h3",{id:"\u8bbe\u7f6e-swagger-\u81ea\u52a8\u6388\u6743"},"\u8bbe\u7f6e ",(0,a.kt)("inlineCode",{parentName:"h3"},"Swagger")," \u81ea\u52a8\u6388\u6743"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},'httpContext.SigninToSwagger("\u4f60\u7684token");\n')),(0,a.kt)("h3",{id:"\u9000\u51fa-swagger-\u6388\u6743"},"\u9000\u51fa ",(0,a.kt)("inlineCode",{parentName:"h3"},"Swagger")," \u6388\u6743"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"httpContext.SignoutToSwagger();\n")),(0,a.kt)("h3",{id:"\u83b7\u53d6\u672c\u5730-ip-\u5730\u5740"},"\u83b7\u53d6\u672c\u5730 IP \u5730\u5740"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"var ipv4 = httpContext.GetLocalIpAddressToIPv4();\nvar ipv6 = httpContext.GetLocalIpAddressToIPv6();\n")),(0,a.kt)("h3",{id:"\u83b7\u53d6\u5ba2\u6237\u7aef-ip-\u5730\u5740"},"\u83b7\u53d6\u5ba2\u6237\u7aef IP \u5730\u5740"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"var ipv4 = httpContext.GetRemoteIpAddressToIPv4();\nvar ipv6 = httpContext.GetRemoteIpAddressToIPv6();\n")),(0,a.kt)("h3",{id:"\u5224\u65ad\u662f\u5426\u662f-ajax-\u8bf7\u6c42"},"\u5224\u65ad\u662f\u5426\u662f ",(0,a.kt)("inlineCode",{parentName:"h3"},"Ajax")," \u8bf7\u6c42"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-cs"},"var isAjaxRequest = httpContext.IsAjaxRequest();\n")))}d.isMDXComponent=!0}}]);
const R = require('ramda'); const fs = require('fs'); const CloudformationClient = require('@src/clients/aws-client/cloudformation-client'); const S3Client = require('@src/clients/aws-client/s3-client'); const stringUtils = require('@src/utils/string-utils'); const retryUtils = require('@src/utils/retry-utility'); const alexaAwsRegionMap = { default: 'us-east-1', NA: 'us-east-1', EU: 'eu-west-1', FE: 'us-west-2' }; module.exports = { getAwsInformation, uploadArtifacts, deployStack, }; function getAwsInformation(awsProfile, alexaRegion, userConfig, deployState) { let awsRegion = alexaRegion === 'default' ? userConfig.awsRegion : R.view(R.lensPath(['regionalOverrides', alexaRegion, 'awsRegion']), userConfig); awsRegion = awsRegion || alexaAwsRegionMap[alexaRegion]; if (!stringUtils.isNonBlankString(awsRegion)) { throw `Unsupported Alexa region: ${alexaRegion}. Please check your region name or use "regionalOverrides" to specify AWS region.`; } const templatePath = R.view(R.lensPath(['regionalOverrides', alexaRegion, 'templatePath']), userConfig) || userConfig.templatePath; if (!stringUtils.isNonBlankString(templatePath)) { throw 'The template path in userConfig must be provided.'; } const bucketName = R.view(R.lensPath(['s3', 'bucket']), deployState) || S3Client.generateBucketName(awsProfile, awsRegion); const bucketObjectVersion = R.view(R.lensPath(['s3', 'objectVersion']), deployState); return { awsRegion, templatePath, bucketName, bucketObjectVersion }; } function uploadArtifacts(reporter, options, callback) { const { awsProfile, awsRegion, bucketName, bucketKey, bucketObjectVersion, artifactFilePath, isCodeModified } = options; if (isCodeModified === false) { reporter.updateStatus('No change on the code and skip the code s3 upload process.'); return process.nextTick(() => { callback(null, { versionId: bucketObjectVersion }); }); } const s3Client = new S3Client({ awsProfile, awsRegion }); reporter.updateStatus(`Uploading code artifact to s3://${bucketName}/${bucketKey}`); s3Client.provisionBucketAndPutObject(bucketName, bucketKey, awsRegion, artifactFilePath, (error, resp) => { callback(error, error ? null : { versionId: resp.VersionId }); }); } function deployStack(reporter, options, callback) { const { awsProfile, awsRegion, templatePath, skillId, stackName, stackId, lambdaRuntime, lambdaHandler, codeBucket, codeKey, codeVersion } = options; let templateContents, cloudformationClient; try { templateContents = fs.readFileSync(templatePath, 'utf-8'); cloudformationClient = new CloudformationClient({ awsProfile, awsRegion }); } catch (preErr) { return callback(preErr); } const stackOptions = { stackId, stackName, templateContents, stackParameters: [ { ParameterKey: 'SkillId', ParameterValue: skillId }, { ParameterKey: 'LambdaRuntime', ParameterValue: lambdaRuntime }, { ParameterKey: 'LambdaHandler', ParameterValue: lambdaHandler }, { ParameterKey: 'CodeBucket', ParameterValue: codeBucket }, { ParameterKey: 'CodeKey', ParameterValue: codeKey }, { ParameterKey: 'CodeVersion', ParameterValue: codeVersion } ] }; _createOrUpdateStack(reporter, cloudformationClient, stackOptions) .then(ensuredStackId => { _pollingStackStatus(reporter, cloudformationClient, ensuredStackId, (getStackErr, stackResult) => { if (getStackErr) { return callback(getStackErr); } const stackStatus = R.view(R.lensPath(['StackStatus']), stackResult); if (stackStatus === 'CREATE_COMPLETE' || stackStatus === 'UPDATE_COMPLETE') { _getEndpointOutput(stackResult, (endpointErr, endpointUri) => { if (endpointErr) { return callback(endpointErr); } callback(null, { stackId: ensuredStackId, endpointUri }); }); } else { _getStackResourcesFailureReason(reporter, cloudformationClient, ensuredStackId, (resourcesErr, reasons) => { if (resourcesErr) { return callback(resourcesErr); } callback(null, { stackId: ensuredStackId, reasons }); }); } }); }) .catch(callback); } async function _createOrUpdateStack(reporter, cloudformationClient, options) { const { stackId, stackName, templateContents, stackParameters } = options; const exists = await cloudformationClient.stackExists(stackId); if (!exists) { reporter.updateStatus(`No stack exists or stack has been deleted. Creating cloudformation stack "${stackName}"...`); const { StackId } = await cloudformationClient.createStack(stackName, templateContents, stackParameters); reporter.updateStatus(`Create stack (id: ${StackId}) in progress...`); return StackId; } reporter.updateStatus(`Updating stack (${stackId})...`); await cloudformationClient.updateStack(stackId, templateContents, stackParameters); return stackId; } function _pollingStackStatus(reporter, cloudformationClient, stackId, callback) { const retryConfig = { base: 2000, factor: 1.1, maxRetry: 50 }; const retryCall = (loopCallback) => { cloudformationClient.describeStack(stackId, (stackErr, stackResponse) => { if (stackErr) { return loopCallback(stackErr); } const stackStatus = R.view(R.lensPath(['StackStatus']), stackResponse); const statusReason = R.view(R.lensPath(['StackStatusReason']), stackResponse); const reasonMsg = statusReason ? `Status reason: ${statusReason}.` : ''; reporter.updateStatus(`Current stack status: ${stackStatus}... ${reasonMsg}`); loopCallback(null, stackResponse); }); }; const shouldRetryCondition = retryResponse => !retryResponse || retryResponse.StackStatus.endsWith('IN_PROGRESS'); retryUtils.retry(retryConfig, retryCall, shouldRetryCondition, (err, res) => callback(err, err ? null : res)); } function _getEndpointOutput(resp, callback) { const endpoint = resp.Outputs.filter(output => output.OutputKey === 'SkillEndpoint'); if (!endpoint[0] || !endpoint[0].OutputValue) { return callback('No "SkillEndpoint" result returned in the stack outputs. ' + 'Make sure you have a "SkillEndpoint" output in your template which points to the endpoint URL.'); } callback(null, endpoint[0].OutputValue); } function _getStackResourcesFailureReason(reporter, cloudformationClient, stackId, callback) { const errorsList = []; reporter.updateStatus('Checking the failure details for the stack resources...'); cloudformationClient.describeStackResources(stackId, (err, stackResources) => { if (err) { return callback(err); } stackResources.forEach((stackResource) => { if (stackResource.ResourceStatus.endsWith('_FAILED')) { errorsList.push({ logicalId: stackResource.LogicalResourceId, resourceType: stackResource.ResourceType, resourceStatus: stackResource.ResourceStatus, reason: stackResource.ResourceStatusReason }); } if (stackResource.ResourceStatus === 'DELETE_COMPLETE') { errorsList.push({ logicalId: stackResource.LogicalResourceId, resourceType: stackResource.ResourceType, resourceStatus: stackResource.ResourceStatus, reason: `Resource deleted. For detailed reasoning, \ please check the "events" tab in the AWS console for CloudFormation stackId (${stackId}).` }); } }); callback(null, errorsList); }); }
//>>built define("dojox/storage/CookieStorageProvider",["dojo","dijit","dojox","dojo/require!dojox/storage/Provider,dojox/storage/manager,dojo/cookie"],function(_1,_2,_3){ _1.provide("dojox.storage.CookieStorageProvider"); _1.require("dojox.storage.Provider"); _1.require("dojox.storage.manager"); _1.require("dojo.cookie"); _1.declare("dojox.storage.CookieStorageProvider",[_3.storage.Provider],{store:null,cookieName:"dojoxStorageCookie",storageLife:730,initialize:function(){ this.store=_1.fromJson(_1.cookie(this.cookieName))||{}; this.initialized=true; _3.storage.manager.loaded(); },isAvailable:function(){ return _1.cookie.isSupported(); },put:function(_4,_5,_6,_7){ this._assertIsValidKey(_4); _7=_7||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(_7); fullKey=this.getFullKey(_4,_7); this.store[fullKey]=_1.toJson(_5); this._save(); var _8=_1.toJson(this.store)===_1.cookie(this.cookieName); if(!_8){ this.remove(_4,_7); } if(_6){ _6(_8?this.SUCCESS:this.FAILED,_4,null,_7); } },get:function(_9,_a){ this._assertIsValidKey(_9); _a=_a||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(_a); _9=this.getFullKey(_9,_a); return this.store[_9]?_1.fromJson(this.store[_9]):null; },getKeys:function(_b){ _b=_b||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(_b); _b="__"+_b+"_"; var _c=[]; for(var _d in this.store){ if(this._beginsWith(_d,_b)){ _d=_d.substring(_b.length); _c.push(_d); } } return _c; },clear:function(_e){ _e=_e||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(_e); _e="__"+_e+"_"; for(var _f in this.store){ if(this._beginsWith(_f,_e)){ delete (this.store[_f]); } } this._save(); },remove:function(key,_10){ _10=_10||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(_10); this._assertIsValidKey(key); key=this.getFullKey(key,_10); delete this.store[key]; this._save(); },getNamespaces:function(){ var _11=[this.DEFAULT_NAMESPACE]; var _12={}; _12[this.DEFAULT_NAMESPACE]=true; var _13=/^__([^_]*)_/; for(var _14 in this.store){ if(_13.test(_14)==true){ var _15=_14.match(_13)[1]; if(typeof _12[_15]=="undefined"){ _12[_15]=true; _11.push(_15); } } } return _11; },isPermanent:function(){ return true; },getMaximumSize:function(){ return 4; },hasSettingsUI:function(){ return false; },isValidKey:function(_16){ if(_16===null||_16===undefined){ return false; } return /^[0-9A-Za-z_-]*$/.test(_16); },isValidNamespace:function(_17){ if(_17===null||_17===undefined){ return false; } return /^[0-9A-Za-z-]*$/.test(_17); },getFullKey:function(key,_18){ return "__"+_18+"_"+key; },_save:function(){ _1.cookie(this.cookieName,_1.toJson(this.store),{expires:this.storageLife}); },_beginsWith:function(_19,_1a){ if(_1a.length>_19.length){ return false; } return _19.substring(0,_1a.length)===_1a; },_assertIsValidNamespace:function(_1b){ if(this.isValidNamespace(_1b)===false){ throw new Error("Invalid namespace given: "+_1b); } },_assertIsValidKey:function(key){ if(this.isValidKey(key)===false){ throw new Error("Invalid key given: "+key); } }}); _3.storage.manager.register("dojox.storage.CookieStorageProvider",new _3.storage.CookieStorageProvider()); });
module.exports = cli => { cli.injectFeature({ name: 'TypeScript', value: 'ts', short: 'TS', description: 'Add support for the TypeScript language', link: 'https://github.com/wmzy/svelte-cli/tree/dev/packages/%40svel/cli-plugin-typescript', plugins: ['typescript'] }) cli.injectPrompt({ name: 'tsClassComponent', when: answers => answers.features.includes('ts'), type: 'confirm', message: 'Use class-style component syntax?', description: 'Use the @Component decorator on classes.', link: 'https://vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components', default: true }) cli.injectPrompt({ name: 'useTsWithBabel', when: answers => answers.features.includes('ts'), type: 'confirm', message: 'Use Babel alongside TypeScript for auto-detected polyfills?', description: 'It will output ES2015 and delegate the rest to Babel for auto polyfill based on browser targets.', default: answers => answers.features.includes('babel') }) cli.onPromptComplete((answers, options) => { if (answers.features.includes('ts')) { const tsOptions = { classComponent: answers.tsClassComponent } if (answers.eslintConfig === 'tslint') { tsOptions.tsLint = true tsOptions.lintOn = answers.lintOn } if (answers.useTsWithBabel) { tsOptions.useTsWithBabel = true } options.plugins['@svel/cli-plugin-typescript'] = tsOptions } }) }
import { isEmpty } from 'lodash'; import { state } from 'cerebral'; /** * validates the respondent on the form for the edit counsel page * * @param {object} providers the providers object * @param {object} providers.applicationContext the application context needed for getting the use case * @param {object} providers.get the cerebral get function used for getting state.form * @param {object} providers.path the cerebral path which contains the next path in the sequence (path of success or error) * @returns {object} the next path based on if validation was successful or error */ export const validateEditRespondentCounselAction = ({ applicationContext, get, path, store, }) => { const { SERVICE_INDICATOR_ERROR, SERVICE_INDICATOR_TYPES } = applicationContext.getConstants(); const respondentCounsel = get(state.form); const { irsPractitioners: oldRespondentCounsels } = get(state.caseDetail); let errors = {}; const oldRespondentCounsel = oldRespondentCounsels.find( foundRespondent => foundRespondent.userId === respondentCounsel.userId, ); if ( [ SERVICE_INDICATOR_TYPES.SI_PAPER, SERVICE_INDICATOR_TYPES.SI_NONE, ].includes(oldRespondentCounsel.serviceIndicator) && respondentCounsel.serviceIndicator === SERVICE_INDICATOR_TYPES.SI_ELECTRONIC ) { errors = { ...errors, ...SERVICE_INDICATOR_ERROR, }; } store.set(state.validationErrors, errors); if (isEmpty(errors)) { return path.success(); } else { return path.error({ alertError: { title: 'Errors were found. Please correct your form and resubmit.', }, errors, }); } };
const BackboneElement = require('./BackboneElement'); const UnsignedIntScalar = require('./scalars/UnsignedInt.scalar'); class CapabilityStatementMessaging extends BackboneElement { constructor ( opt ) { super( opt ); this.__resourceType = 'CapabilityStatementMessaging'; Object.assign(this, opt); } // This is a CapabilityStatementMessaging resource static get __resourceType () { return 'CapabilityStatementMessaging'; } // An endpoint (network accessible address) to which messages and/or replies are to be sent. get endpoint () { return this.__endpoint; } set endpoint (new_value) { const CapabilityStatementMessagingEndpoint = require('./CapabilityStatementMessagingEndpoint'); this.__endpoint = Array.isArray(new_value) ? new_value.map(val => new CapabilityStatementMessagingEndpoint(val)) : [new CapabilityStatementMessagingEndpoint(new_value)]; } // Length if the receiver\'s reliable messaging cache in minutes (if a receiver) or how long the cache length on the receiver should be (if a sender). get reliableCache () { return this.__reliableCache; } set reliableCache (new_value) { // Throw if new value does not match the pattern let pattern = UnsignedIntScalar.regex(); if ( new_value && !pattern.test(new_value) ) { throw new Error(`Invalid format for ${new_value} on field reliableCache`); } this.__reliableCache = new_value; } // Documentation about the system\'s messaging capabilities for this endpoint not otherwise documented by the capability statement. For example, the process for becoming an authorized messaging exchange partner. get documentation () { return this.__documentation; } set documentation (new_value) { this.__documentation = new_value; } // References to message definitions for messages this system can send or receive. get supportedMessage () { return this.__supportedMessage; } set supportedMessage (new_value) { const CapabilityStatementMessagingSupportedMessage = require('./CapabilityStatementMessagingSupportedMessage'); this.__supportedMessage = Array.isArray(new_value) ? new_value.map(val => new CapabilityStatementMessagingSupportedMessage(val)) : [new CapabilityStatementMessagingSupportedMessage(new_value)]; } // A description of the solution\'s support for an event at this end-point. get event () { return this.__event; } set event (new_value) { const CapabilityStatementMessagingEvent = require('./CapabilityStatementMessagingEvent'); this.__event = Array.isArray(new_value) ? new_value.map(val => new CapabilityStatementMessagingEvent(val)) : [new CapabilityStatementMessagingEvent(new_value)]; } toJSON () { return Object.assign(super.toJSON(), { endpoint: this.__endpoint && this.__endpoint.map(v => v.toJSON()), reliableCache: this.__reliableCache, documentation: this.__documentation, supportedMessage: this.__supportedMessage && this.__supportedMessage.map(v => v.toJSON()), event: this.__event && this.__event.map(v => v.toJSON()) }); } } module.exports = CapabilityStatementMessaging;
import Enzyme from 'enzyme'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import { createSerializer } from 'enzyme-to-json'; Enzyme.configure({ adapter: new Adapter() }); expect.addSnapshotSerializer(createSerializer({ mode: 'deep' }));
Object.defineProperty(exports, "__esModule", { value: true }); var DISPLAY_FORMAT = exports.DISPLAY_FORMAT = 'L'; var ISO_FORMAT = exports.ISO_FORMAT = 'YYYY-MM-DD'; var ISO_MONTH_FORMAT = exports.ISO_MONTH_FORMAT = 'YYYY-MM'; var START_DATE = exports.START_DATE = 'startDate'; var END_DATE = exports.END_DATE = 'endDate'; var HORIZONTAL_ORIENTATION = exports.HORIZONTAL_ORIENTATION = 'horizontal'; var VERTICAL_ORIENTATION = exports.VERTICAL_ORIENTATION = 'vertical'; var VERTICAL_SCROLLABLE = exports.VERTICAL_SCROLLABLE = 'verticalScrollable'; var ICON_BEFORE_POSITION = exports.ICON_BEFORE_POSITION = 'before'; var ICON_AFTER_POSITION = exports.ICON_AFTER_POSITION = 'after'; var INFO_POSITION_TOP = exports.INFO_POSITION_TOP = 'top'; var INFO_POSITION_BOTTOM = exports.INFO_POSITION_BOTTOM = 'bottom'; var INFO_POSITION_BEFORE = exports.INFO_POSITION_BEFORE = 'before'; var INFO_POSITION_AFTER = exports.INFO_POSITION_AFTER = 'after'; var ANCHOR_LEFT = exports.ANCHOR_LEFT = 'left'; var ANCHOR_RIGHT = exports.ANCHOR_RIGHT = 'right'; var OPEN_DOWN = exports.OPEN_DOWN = 'down'; var OPEN_UP = exports.OPEN_UP = 'up'; var DAY_SIZE = exports.DAY_SIZE = 24; var BLOCKED_MODIFIER = exports.BLOCKED_MODIFIER = 'blocked'; var WEEKDAYS = exports.WEEKDAYS = [0, 1, 2, 3, 4, 5, 6]; var FANG_WIDTH_PX = exports.FANG_WIDTH_PX = 20; var FANG_HEIGHT_PX = exports.FANG_HEIGHT_PX = 10; var DEFAULT_VERTICAL_SPACING = exports.DEFAULT_VERTICAL_SPACING = 22; var MODIFIER_KEY_NAMES = exports.MODIFIER_KEY_NAMES = new Set(['Shift', 'Control', 'Alt', 'Meta']);
// MIT License: // // Copyright (c) 2010-2012, Joe Walnes // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /** * This behaves like a WebSocket in every way, except if it fails to connect, * or it gets disconnected, it will repeatedly poll until it successfully connects * again. * * It is API compatible, so when you have: * ws = new WebSocket('ws://....'); * you can replace with: * ws = new ReconnectingWebSocket('ws://....'); * * The event stream will typically look like: * onconnecting * onopen * onmessage * onmessage * onclose // lost connection * onconnecting * onopen // sometime later... * onmessage * onmessage * etc... * * It is API compatible with the standard WebSocket API, apart from the following members: * * - `bufferedAmount` * - `extensions` * - `binaryType` * * Latest version: https://github.com/joewalnes/reconnecting-websocket/ * - Joe Walnes * * Syntax * ====== * var socket = new ReconnectingWebSocket(url, protocols, options); * * Parameters * ========== * url - The url you are connecting to. * protocols - Optional string or array of protocols. * options - See below * * Options * ======= * Options can either be passed upon instantiation or set after instantiation: * * var socket = new ReconnectingWebSocket(url, null, { debug: true, reconnectInterval: 4000 }); * * or * * var socket = new ReconnectingWebSocket(url); * socket.debug = true; * socket.reconnectInterval = 4000; * * debug * - Whether this instance should log debug messages. Accepts true or false. Default: false. * * automaticOpen * - Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close(). * * reconnectInterval * - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000. * * maxReconnectInterval * - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000. * * reconnectDecay * - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5. * * timeoutInterval * - The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. Accepts integer. Default: 2000. * */ (function (global, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module !== 'undefined' && module.exports){ module.exports = factory(); } else { global.ReconnectingWebSocket = factory(); } })(this, function () { if (!global.window || !('WebSocket' in global.window)) { return; } function ReconnectingWebSocket(url, protocols, options) { // Default settings var settings = { /** Whether this instance should log debug messages. */ debug: false, /** Whether or not the websocket should attempt to connect immediately upon instantiation. */ automaticOpen: true, /** The number of milliseconds to delay before attempting to reconnect. */ reconnectInterval: 1000, /** The maximum number of milliseconds to delay a reconnection attempt. */ maxReconnectInterval: 30000, /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */ reconnectDecay: 1.5, /** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */ timeoutInterval: 2000, /** The maximum number of reconnection attempts to make. Unlimited if null. */ maxReconnectAttempts: null, /** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */ binaryType: 'blob' } if (!options) { options = {}; } // Overwrite and define settings with options if they exist. for (var key in settings) { if (typeof options[key] !== 'undefined') { this[key] = options[key]; } else { this[key] = settings[key]; } } // These should be treated as read-only properties /** The URL as resolved by the constructor. This is always an absolute URL. Read only. */ this.url = url; /** The number of attempted reconnects since starting, or the last successful connection. Read only. */ this.reconnectAttempts = 0; /** * The current state of the connection. * Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED * Read only. */ this.readyState = WebSocket.CONNECTING; /** * A string indicating the name of the sub-protocol the server selected; this will be one of * the strings specified in the protocols parameter when creating the WebSocket object. * Read only. */ this.protocol = null; // Private state variables var self = this; var ws; var forcedClose = false; var timedOut = false; var eventTarget = document.createElement('div'); // Wire up "on*" properties as event handlers eventTarget.addEventListener('open', function(event) { self.onopen(event); }); eventTarget.addEventListener('close', function(event) { self.onclose(event); }); eventTarget.addEventListener('connecting', function(event) { self.onconnecting(event); }); eventTarget.addEventListener('message', function(event) { self.onmessage(event); }); eventTarget.addEventListener('error', function(event) { self.onerror(event); }); // Expose the API required by EventTarget this.addEventListener = eventTarget.addEventListener.bind(eventTarget); this.removeEventListener = eventTarget.removeEventListener.bind(eventTarget); this.dispatchEvent = eventTarget.dispatchEvent.bind(eventTarget); /** * This function generates an event that is compatible with standard * compliant browsers and IE9 - IE11 * * This will prevent the error: * Object doesn't support this action * * http://stackoverflow.com/questions/19345392/why-arent-my-parameters-getting-passed-through-to-a-dispatched-event/19345563#19345563 * @param s String The name that the event should use * @param args Object an optional object that the event will use */ function generateEvent(s, args) { var evt = document.createEvent("CustomEvent"); evt.initCustomEvent(s, false, false, args); return evt; }; this.open = function (reconnectAttempt) { ws = new WebSocket(self.url, protocols || []); ws.binaryType = this.binaryType; if (reconnectAttempt) { if (this.maxReconnectAttempts && this.reconnectAttempts > this.maxReconnectAttempts) { return; } } else { eventTarget.dispatchEvent(generateEvent('connecting')); this.reconnectAttempts = 0; } if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'attempt-connect', self.url); } var localWs = ws; var timeout = setTimeout(function() { if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'connection-timeout', self.url); } timedOut = true; localWs.close(); timedOut = false; }, self.timeoutInterval); ws.onopen = function(event) { clearTimeout(timeout); if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'onopen', self.url); } self.protocol = ws.protocol; self.readyState = WebSocket.OPEN; self.reconnectAttempts = 0; var e = generateEvent('open'); e.isReconnect = reconnectAttempt; reconnectAttempt = false; eventTarget.dispatchEvent(e); }; ws.onclose = function(event) { clearTimeout(timeout); ws = null; if (forcedClose) { self.readyState = WebSocket.CLOSED; eventTarget.dispatchEvent(generateEvent('close')); } else { self.readyState = WebSocket.CONNECTING; var e = generateEvent('connecting'); e.code = event.code; e.reason = event.reason; e.wasClean = event.wasClean; eventTarget.dispatchEvent(e); if (!reconnectAttempt && !timedOut) { if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'onclose', self.url); } eventTarget.dispatchEvent(generateEvent('close')); } var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts); setTimeout(function() { self.reconnectAttempts++; self.open(true); }, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout); } }; ws.onmessage = function(event) { if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'onmessage', self.url, event.data); } var e = generateEvent('message'); e.data = event.data; eventTarget.dispatchEvent(e); }; ws.onerror = function(event) { if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'onerror', self.url, event); } eventTarget.dispatchEvent(generateEvent('error')); }; } // Whether or not to create a websocket upon instantiation if (this.automaticOpen == true) { this.open(false); } /** * Transmits data to the server over the WebSocket connection. * * @param data a text string, ArrayBuffer or Blob to send to the server. */ this.send = function(data) { if (ws) { if (self.debug || ReconnectingWebSocket.debugAll) { console.debug('ReconnectingWebSocket', 'send', self.url, data); } return ws.send(data); } else { throw 'INVALID_STATE_ERR : Pausing to reconnect websocket'; } }; /** * Closes the WebSocket connection or connection attempt, if any. * If the connection is already CLOSED, this method does nothing. */ this.close = function(code, reason) { // Default CLOSE_NORMAL code if (typeof code == 'undefined') { code = 1000; } forcedClose = true; if (ws) { ws.close(code, reason); } }; /** * Additional public API method to refresh the connection if still open (close, re-open). * For example, if the app suspects bad data / missed heart beats, it can try to refresh. */ this.refresh = function() { if (ws) { ws.close(); } }; } /** * An event listener to be called when the WebSocket connection's readyState changes to OPEN; * this indicates that the connection is ready to send and receive data. */ ReconnectingWebSocket.prototype.onopen = function(event) {}; /** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */ ReconnectingWebSocket.prototype.onclose = function(event) {}; /** An event listener to be called when a connection begins being attempted. */ ReconnectingWebSocket.prototype.onconnecting = function(event) {}; /** An event listener to be called when a message is received from the server. */ ReconnectingWebSocket.prototype.onmessage = function(event) {}; /** An event listener to be called when an error occurs. */ ReconnectingWebSocket.prototype.onerror = function(event) {}; /** * Whether all instances of ReconnectingWebSocket should log debug messages. * Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true. */ ReconnectingWebSocket.debugAll = false; ReconnectingWebSocket.CONNECTING = WebSocket.CONNECTING; ReconnectingWebSocket.OPEN = WebSocket.OPEN; ReconnectingWebSocket.CLOSING = WebSocket.CLOSING; ReconnectingWebSocket.CLOSED = WebSocket.CLOSED; return ReconnectingWebSocket; });
export const lupa = require('../assets/lupa.png') export const ajustes = require('../assets/ajustes.png') export default { lupa,ajustes }
/** * In this script, we will login and run a few tests that use GitHub API. * * Steps summary * 1. Create a new repo. * 2. Run tests that programmatically create new issues. * 3. Delete the repo. */ const { test, expect } = require('@playwright/test'); const user = process.env.GITHUB_USER; const repo = 'Test-Repo-1'; test.use({ baseURL: 'https://api.github.com', extraHTTPHeaders: { 'Accept': 'application/vnd.github.v3+json', // Add authorization token to all requests. 'Authorization': `token ${process.env.API_TOKEN}`, } }); test.beforeAll(async ({ request }) => { // Create repo const response = await request.post('/user/repos', { data: { name: repo } }); expect(response.ok()).toBeTruthy(); }); test.afterAll(async ({ request }) => { // Delete repo const response = await request.delete(`/repos/${user}/${repo}`); expect(response.ok()).toBeTruthy(); }); test('should create bug report', async ({ request }) => { const newIssue = await request.post(`/repos/${user}/${repo}/issues`, { data: { title: '[Bug] report 1', body: 'Bug description', } }); expect(newIssue.ok()).toBeTruthy(); const issues = await request.get(`/repos/${user}/${repo}/issues`); expect(issues.ok()).toBeTruthy(); expect(await issues.json()).toContainEqual(expect.objectContaining({ title: '[Bug] report 1', body: 'Bug description' })); }); test('should create feature request', async ({ request }) => { const newIssue = await request.post(`/repos/${user}/${repo}/issues`, { data: { title: '[Feature] request 1', body: 'Feature description', } }); expect(newIssue.ok()).toBeTruthy(); const issues = await request.get(`/repos/${user}/${repo}/issues`); expect(issues.ok()).toBeTruthy(); expect(await issues.json()).toContainEqual(expect.objectContaining({ title: '[Feature] request 1', body: 'Feature description' })); });
/*! Webcasting Studio JQuery Player 2013-12-11 */ /*! Author: Carlos Galan Cladera < cgcladera@gmail.com > */ !function(a){var b=function(c,d,e){var f;if("string"==typeof c){if(0!==c.indexOf("#")&&(c="#"+c),f=a(c),b.webcasts[f.attr("id")])return b.webcasts[f.attr("id")]}else f=a(c);if(!f.length)throw new TypeError("The element ID supplied is not valid.");return new b.Webcast(f,d,e)};window.wsplayer=window.wsp=b,b.options={video:{skin:"vjs-default-skin",poster:"http://video-js.zencoder.com/oceans-clip.png",preload:"auto",autoplay:!1,controls:!0,width:640,height:264,sources:[{src:"http://video-js.zencoder.com/oceans-clip.mp4",type:"video/mp4"}]},components:{}},b.webcasts={},b.obj={},b.obj.create=Object.create||function(a){function b(){}return b.prototype=a,new b},b.guid=1,b.CoreObject=function(){},b.CoreObject.extend=function(a){var c,d;a=a||{},c=a.init||this.prototype.init||function(){},d=function(){c.apply(this,arguments)},d.prototype=b.obj.create(this.prototype),d.prototype.constructor=d,d.extend=b.CoreObject.extend,d.create=b.CoreObject.create;for(var e in a)a.hasOwnProperty(e)&&(d.prototype[e]=a[e]);return d},b.CoreObject.create=function(){var a=b.obj.create(this.prototype);return this.apply(a,arguments),a},b.Webcast=b.CoreObject.extend({init:function(c,d,e){this.ready=e||this.ready;var f=this.container_=a(c);f.addClass("wsp-container"),f=a(c),f.addClass("wsp-container");var g=void 0!==f.attr("id")?f.attr("id"):"wsplayer";f.attr("id",g),b.webcasts[g]=this,this.options=a.extend(!0,{},b.options,d),this.createPlayer();var h=this;this.options.plugins&&a.each(h.options.plugins,function(a,b){h[a](b)})}}),b.Webcast.prototype.dispose=function(){this.player&&this.player.dispose&&this.player.dispose(),this.player=null,this.components_&&a.each(this.components_,function(a,b){b.dispose&&b.dispose()}),this.components_=null,this.isReady_=!1},b.Webcast.prototype.ready=function(){},b.Webcast.prototype.triggerReady_=function(){this.isReady_=!0,this.ready.call(this)},b.Webcast.prototype.isReady_=!1,b.Webcast.prototype.player={},b.Webcast.prototype.components_={},b.Webcast.prototype.options=null,b.Webcast.prototype.container_={},b.Webcast.prototype.container=function(){return this.container_},b.Webcast.prototype.id=function(){return this.container_.attr("id")},b.Webcast.prototype.createPlayer=function(){var b=this.container_,c=a("#"+b.attr("id")+" > video");if(c.length?void 0===c.attr("id")&&(c.attr("id","wsp-video"),c.addClass("wsplayer"),c.addClass("wsp-component")):(c=a("<video></video>"),c.attr("id","wsplayer-video"),c.addClass("video-js"),c.addClass(this.options.video.skin),c.addClass("wsplayer"),c.addClass("wsp-component"),a.each(this.options.video.sources,function(b,d){c.append(a('<source src="'+d.src+'" type="'+d.type+'">'))}),c.attr("width",this.options.video.width),c.attr("height",this.options.video.height),c.attr("controls",this.options.video.controls),c.attr("preload",this.options.video.preload),c.attr("autoplay",this.options.video.autoplay),c.attr("poster",this.options.video.poster),this.options.video.setup&&c.attr("data-setup",JSON.stringify(this.options.video.setup)),b.append(c)),"function"!=typeof videojs)throw new TypeError("VideoJS player not found");var d=this;videojs(c.attr("id"),{},function(){d.player=this,"function"==typeof d.player.cuepoints&&d.player.cuepoints(),d.appendChildren_(),d.triggerReady_()})},b.Webcast.prototype.appendElement=function(a){return this.container_.append(a),this},b.Webcast.prototype.addClass=function(a){return this.container_.addClass(a),this},b.Webcast.prototype.removeClass=function(a){return this.container_.removeClass(a),this},b.Webcast.prototype.hide=function(a){a=a||function(){};var b=this;this.container_.fadeOut(function(){a.call(b)})},b.Webcast.prototype.show=function(a){a=a||function(){};var b=this;this.container_.fadeIn(function(){a.call(b)})},b.Webcast.prototype.appendChildren_=function(){var c=this;this.options.components&&(c.components_={},a.each(this.options.components,function(a,d){a in b.components&&(b.components[a].build(c,d),c.components_[a]=b.components[a])}))},b.Webcast.prototype.addCuepoint=function(b,c,d,e){var f={};if(this.isReady_){var g=this,h=e||"default",i={namespace:h,start:b,end:c,params:d||{}};i.onStart=function(b){a.each(g.components_,function(a,c){c.act("onStart",h,b)})},i.onEnd=function(b){a.each(g.components_,function(a,c){c.act("onEnd",h,b)})},f=this.player.addCuepoint(i),a.each(g.components_,function(a,b){b.act("setup",h,d)})}return f},b.Component=b.CoreObject.extend({init:function(b,c){this.name_=b;var d=["build","dispose"];a.each(d,function(a,b){c[b]=b in c&&"function"==typeof c[b]?c[b]:function(){}});var e=["setup","onStart","onEnd"];c.handlers=c.handlers||{},a.each(c.handlers,function(b,d){a.each(e,function(a,e){c.handlers[b][e]=e in d&&"function"==typeof d[e]?d[e]:function(){}})}),this.definition_=c}}),b.Component.prototype.definition_={},b.Component.prototype.webcast={},b.Component.prototype.name_="",b.Component.prototype.name=function(){return this.name_},b.Component.prototype.options={},b.Component.prototype.build=function(a,b){this.webcast=a,this.options=b||{},this.definition_.build.call(this,a,b)},b.Component.prototype.dispose=function(){this.definition_.dispose.call(this)},b.Component.prototype.act=function(a,b,c){b=b||"default",b in this.definition_.handlers&&a in this.definition_.handlers[b]&&this.definition_.handlers[b][a].call(this,c)},b.components={},b.component=function(a,c){return b.components[a]=new b.Component(a,c),b.components[a]},b.plugin=function(a,c){b.Webcast.prototype[a]=c},b.component("slideshow",{build:function(b,c){var d=this.el=a("<div id='slideshow'></div>");d.addClass("slideshow"),d.addClass("wsplayer"),d.addClass("wsp-component"),this.options.width&&d.css({width:c.width+"px"}),this.options.height&&d.css({height:c.height+"px"}),d.css({position:"relative"}),b.appendElement(d)},dispose:function(){this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null},handlers:{layout:{onStart:function(a){var b=this.webcast.options.components.layout.manifest[a.layout]||a.layout;b.slideshow?(b.slideshow.height&&this.el.css({height:b.slideshow.height+"px"}),b.slideshow.width&&(this.el.css({width:b.slideshow.width+"px"}),this.el.find("img").css({width:b.slideshow.width+"px"}))):(this.options.width&&(this.el.css({width:this.options.width+"px"}),this.el.find("img").css({width:this.options.width+"px"})),this.options.height&&this.el.css({height:this.options.height+"px"}))}},slideshow:{setup:function(b){var c=this.el.children("img#"+b.id);c.length?c.attr("src",b.src):(c=a("<img/>"),c.attr("id",b.id),c.attr("src",b.src),c.css({position:"absolute",top:"0px",left:"0px"}),this.options.width&&c.css({width:a(this.el).width()+"px"}),c.hide(),a(this.el).append(c)),c.css({"z-index":this.el.children("img").length})},onStart:function(a){var b=this.el.children("img#"+a.id);this.el.children("img:visible").length?(this.el.children("img:visible").fadeOut("slow"),b.fadeIn("slow")):b.fadeIn("slow"),this.el.height(b.height())},onEnd:function(a){var b=this.el.children("img#"+a.id);b.fadeOut()}}}}),b.component("layout",{build:function(a,b){b.manifest=b.manifest||{},this.currentLayout=""},handlers:{layout:{onStart:function(a){var b=this.options.manifest[a.layout]?this.options.manifest[a.layout]:a.layout;if(b.class!==this.currentLayout){var c=this;a.smooth?this.webcast.hide(function(){this.removeClass(c.currentLayout),this.addClass(b.class),c.currentLayout=b.class,this.show()}):(this.webcast.removeClass(this.currentLayout),this.webcast.addClass(b.class),this.currentLayout=b.class),b.video?this.webcast.player.dimensions(b.video.width||this.webcast.options.video.width,b.video.height||this.webcast.options.video.height):this.webcast.player.dimensions(this.webcast.options.video.width,this.webcast.options.video.height)}}}}})}(jQuery);
import { build } from 'esbuild'; import { eslintPlugin } from 'esbuild-plugin-eslinter'; const DEV = process.argv.includes('--dev'); const esbuildBase = { bundle: true, watch: DEV, minify: !DEV, incremental: DEV, plugins: [eslintPlugin()], entryPoints: ['src/index.ts'], sourcemap: DEV && 'inline', legalComments: 'none', globalName: 'Slidy', }; const builds = { cjs: { outfile: './dist/index.cjs', }, esm: { outfile: './dist/index.mjs', }, iife: { outfile: './dist/index.js', }, }; if (DEV) { build({ ...esbuildBase, outfile: './dist/index.mjs', format: 'esm', }).then(() => console.log('watching @slidy/animation...')); } else { for (const key in builds) { build({ ...esbuildBase, ...builds[key], format: key, }); } }
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function() { "use strict"; const matches = (value,pattern,functional,routing) => { const type = typeof(value); if(typeof(pattern)!=="object" && type!=="object") { if(value===pattern) { return true; } if(routing && type==="string" && typeof(pattern)==="string") { const pparts = pattern.split("/"), vparts = value.split("/"); if(pparts[0]==="") { pparts.shift(); } if(vparts[0]==="") { vparts.shift(); } let part; if(pparts.length!==vparts.length) { return false; } while(pparts.length>0) { const ppart = pparts.shift(), vpart = vparts.shift(); if(ppart[0]===":") { if(!routing.params) { routing.params = {}; } let value = vpart; try { value = JSON.parse(value); } catch(e) { true; } routing.params[ppart.substring(1)] = value; } else if(vpart!==ppart) { return false; } } return true; } } if(pattern instanceof Date) { if(value instanceof Date) { return pattern.getTime()===value.getTime(); } return false; } if(pattern instanceof RegExp) { if(["boolean","number","string"].includes(type)) { return pattern.test(value); } return false; } if(pattern instanceof Function) { return !!pattern(value); } return Object.keys(pattern).every((key) => { let pvalue = pattern[key], ptype = typeof(pvalue), test = (value) => value===pvalue; if(ptype==="undefined" || (pvalue && ptype==="object" && Object.keys(pvalue).length===0)) { return true; } if(key.startsWith("/")) { const i = key.lastIndexOf("/"); if(i>0) { try { const regexp = new RegExp(key.substring(1,i),key.substring(i+1)); test = (key) => regexp.test(key); } catch(e) { true; } } } else if(key.includes("=>")) { try { test = Function("return " + key)(); } catch(e) { true; } } return Object.keys(value).every((vkey) => { let vtest = () => vkey===key; if(vkey.startsWith("/")) { const i = vkey.lastIndexOf("/"); if(i>0) { try { const regexp = new RegExp(vkey.substring(1,i),vkey.substring(i+1)); vtest = regexp.test(key); } catch(e) { true; } } } else if(vkey.includes("=>")) { try { vtest = Function("return " + vkey)(); } catch(e) { true; } } if(test(vkey) || vtest()) { const vvalue = value[vkey], vtype = typeof(vvalue); if(functional && ptype==="function") { return pvalue(vvalue); } if(pvalue && ptype==="object" && vtype==="object") { return vvalue ? matches(vvalue,pvalue,functional) : false; } return pvalue===vvalue; } return true; }); }); }, deepFreeze = (data) => { if(data && typeof(data)==="object") { Object.freeze(data); Object.keys(data).forEach((key) => deepFreeze(data[key])); } return data; }, getPath = (object) => { if(object.path) { return object.path; } if(object.location && object.location.pathname) { return object.path = object.location.pathname; } if(object.url || object.URL || object.newURL) { if(!object.location) { object.location = new URL(object.url || object.URL || object.newURL); } if(object.location.pathname) { return object.path = object.location.pathname; } return object.path = new URL(object.url || object.URL || object.newURL).pathname; } }, switchcase = (cases={},defaults={}) => { let switches = []; if(defaults && typeof(defaults)!=="object") { defaults = {strict:defaults}; } if(cases!=null && typeof cases[Symbol.iterator] === "function") { switches = cases.slice(); } else { Object.keys(cases).forEach((key) => { let test = key; try { test = Function("return " + key)(); } catch(e) { true; } switches.push([test,cases[key]]); }); } const switcher = Function("defaults","switches","matches","deepFreeze","getPath","switcher", `return ${defaults.async ? "async " : ""}(value,options={},...args) => { delete options.pathRouter; delete options.continuable; options = Object.assign({},defaults,options); if(options.pathRouter) { options.continuable = true; } if(options.continuable) { options.call = true; } let target = value, setParams; if(options.pathRouter) { const type = typeof(options.pathRouter.route); if(type==="function") { target = options.pathRouter.route(value); } else if(type==="string") { target = value[options.pathRouter.route]; } else if(value.req) { target = getPath(value.req); } else if(value.request) { target = getPath(value.request); } else { target = getPath(value); } setParams = options.pathRouter.setParams; if(!setParams) { setParams = (value,params) => { if(value.req) { value.req.params = Object.assign({},value.req.params,params); } else if(value.request) { value.request.params = Object.assign({},value.request.params,params); } else { value.params = Object.assign({},value.params,params); } }; } } const routing = options.pathRouter ? {} : null; let results; // for collecting items when using as an object matcher for(let item of switches) { const key = Array.isArray(item) ? item[0] : item, type = typeof(key); let pattern = key, result = item[1]; if(key===item) { // swap target and pattern if using for object matching target = key; pattern = value; } if(key && key!==item && type==="object" && !Object.isFrozen(key)) { // doesn't check deep but good enough and fast deepFreeze(key); } if((key && (type==="object" || routing) && matches(target,pattern,result===undefined ? true : options.functionalMatch,routing)) || (result!==undefined && type==="function" && ${defaults.async ? "await " : ""} key(target,...args)) || (result!==undefined && options.strict && key===target) || (result!==undefined && !options.strict && key==target)) { if(result===undefined) { // case is an object to match if(!results) { results = []; } results.push(target); continue; } if(typeof(result)==="function" && options.call) { if(setParams && routing.params) { setParams(value,routing.params); } const resolved = ${defaults.async ? "await " : ""} result(value,...args); if(resolved!==undefined || !options.continuable) { return resolved; } if(options.continuable) { continue; } result = resolved; } return result; } } const result = options.call && typeof(switcher().otherwise)==="function" ? ${defaults.async ? "await " : ""} switcher().otherwise(value) : switcher().otherwise; return result === undefined ? results : result; }` )(defaults,switches,matches,deepFreeze,getPath,() => switcher); switcher.otherwise = cases.default; switcher.case = (test,value) => { switches.push([test,value]); return switcher; }; switcher.route = (test,value) => { defaults.pathRouter = true; switches.push([test,value]); return switcher; }; switcher.default = (value) => { switcher.otherwise = value; return switcher; }; switcher.match = (value) => switcher(value); switcher.handle = switcher.match; return switcher; } if(typeof(module)!=="undefined") { module.exports = switchcase; } if(typeof(window)!=="undefined") { window.switchcase = switchcase; } }()); },{}]},{},[1]);
'use strict'; var _analytics = global.analytics; /* * Module dependencies. */ var Alias = require('segmentio-facade').Alias; var Emitter = require('component-emitter'); var Facade = require('segmentio-facade'); var Group = require('segmentio-facade').Group; var Identify = require('segmentio-facade').Identify; var SourceMiddlewareChain = require('./middleware').SourceMiddlewareChain; var IntegrationMiddlewareChain = require('./middleware') .IntegrationMiddlewareChain; var Page = require('segmentio-facade').Page; var Track = require('segmentio-facade').Track; var bindAll = require('bind-all'); var clone = require('@ndhoule/clone'); var extend = require('extend'); var cookie = require('./cookie'); var metrics = require('./metrics'); var debug = require('debug'); var defaults = require('@ndhoule/defaults'); var each = require('@ndhoule/each'); var foldl = require('@ndhoule/foldl'); var group = require('./group'); var is = require('is'); var isMeta = require('@segment/is-meta'); var keys = require('@ndhoule/keys'); var memory = require('./memory'); var nextTick = require('next-tick'); var normalize = require('./normalize'); var on = require('component-event').bind; var pageDefaults = require('./pageDefaults'); var pick = require('@ndhoule/pick'); var prevent = require('@segment/prevent-default'); var querystring = require('component-querystring'); var store = require('./store'); var user = require('./user'); var type = require('component-type'); /** * Initialize a new `Analytics` instance. */ function Analytics() { this._options({}); this.Integrations = {}; this._sourceMiddlewares = new SourceMiddlewareChain(); this._integrationMiddlewares = new IntegrationMiddlewareChain(); this._integrations = {}; this._readied = false; this._timeout = 300; // XXX: BACKWARDS COMPATIBILITY this._user = user; this.log = debug('analytics.js'); bindAll(this); var self = this; this.on('initialize', function(settings, options) { if (options.initialPageview) self.page(); self._parseQuery(window.location.search); }); } /** * Mix in event emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function(plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function(Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Define a new `SourceMiddleware` * * @param {Function} Middleware * @return {Analytics} */ Analytics.prototype.addSourceMiddleware = function(middleware) { if (this.initialized) throw new Error( 'attempted to add a source middleware after initialization' ); this._sourceMiddlewares.add(middleware); return this; }; /** * Define a new `IntegrationMiddleware` * * @param {Function} Middleware * @return {Analytics} */ Analytics.prototype.addIntegrationMiddleware = function(middleware) { if (this.initialized) throw new Error( 'attempted to add an integration middleware after initialization' ); this._integrationMiddlewares.add(middleware); return this; }; /** * Initialize with the given integration `settings` and `options`. * * Aliased to `init` for convenience. * * @param {Object} [settings={}] * @param {Object} [options={}] * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function( settings, options ) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(function(opts, name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }, settings); // add integrations each(function(opts, name) { // Don't load disabled integrations if (options.integrations) { if ( options.integrations[name] === false || (options.integrations.All === false && !options.integrations[name]) ) { return; } } var Integration = self.Integrations[name]; var clonedOpts = {}; extend(true, clonedOpts, opts); // deep clone opts var integration = new Integration(clonedOpts); self.log('initialize %o - %o', name, opts); self.add(integration); }, settings); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var readyCallCount = 0; var integrationCount = keys(integrations).length; var ready = function() { readyCallCount++; if (readyCallCount >= integrationCount) { self._readied = true; self.emit('ready'); } }; // init if no integrations if (integrationCount <= 0) { ready(); } // initialize integrations, passing ready // create a list of any integrations that did not initialize - this will be passed with all events for replay support: this.failedInitializations = []; var initialPageSkipped = false; each(function(integration) { if ( options.initialPageview && integration.options.initialPageview === false ) { // We've assumed one initial pageview, so make sure we don't count the first page call. var page = integration.page; integration.page = function() { if (initialPageSkipped) { return page.apply(this, arguments); } initialPageSkipped = true; return; }; } integration.analytics = self; integration.once('ready', ready); try { metrics.increment('analytics_js.integration.invoke', { method: 'initialize', integration_name: integration.name }); integration.initialize(); } catch (e) { var integrationName = integration.name; metrics.increment('analytics_js.integration.invoke.error', { method: 'initialize', integration_name: integration.name }); self.failedInitializations.push(integrationName); self.log('Error initializing %s integration: %o', integrationName, e); // Mark integration as ready to prevent blocking of anyone listening to analytics.ready() integration.ready(); } }, integrations); // backwards compat with angular plugin and used for init logic checks this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Set the user's `id`. * * @param {Mixed} id */ Analytics.prototype.setAnonymousId = function(id) { this.user().anonymousId(id); return this; }; /** * Add an integration. * * @param {Integration} integration */ Analytics.prototype.add = function(integration) { this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {string} [id=user.id()] User ID. * @param {Object} [traits=null] User traits. * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.identify = function(id, traits, options, fn) { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(traits)) (fn = traits), (options = null), (traits = null); if (is.object(id)) (options = traits), (traits = id), (id = user.id()); /* eslint-enable no-unused-expressions, no-sequences */ // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); var msg = this.normalize({ options: options, traits: user.traits(), userId: user.id() }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('identify', new Identify(msg)); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function() { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {string} [id=group.id()] Group ID. * @param {Object} [traits=null] Group traits. * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics|Object} */ Analytics.prototype.group = function(id, traits, options, fn) { /* eslint-disable no-unused-expressions, no-sequences */ if (!arguments.length) return group; if (is.fn(options)) (fn = options), (options = null); if (is.fn(traits)) (fn = traits), (options = null), (traits = null); if (is.object(id)) (options = traits), (traits = id), (id = group.id()); /* eslint-enable no-unused-expressions, no-sequences */ // grab from group again to make sure we're taking from the source group.identify(id, traits); var msg = this.normalize({ options: options, traits: group.traits(), groupId: group.id() }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('group', new Group(msg)); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {string} event * @param {Object} [properties=null] * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.track = function(event, properties, options, fn) { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(properties)) (fn = properties), (options = null), (properties = null); /* eslint-enable no-unused-expressions, no-sequences */ // figure out if the event is archived. var plan = this.options.plan || {}; var events = plan.track || {}; var planIntegrationOptions = {}; // normalize var msg = this.normalize({ properties: properties, options: options, event: event }); // plan. plan = events[event]; if (plan) { this.log('plan %o - %o', event, plan); if (plan.enabled === false) { // Disabled events should always be sent to Segment. planIntegrationOptions = { All: false, 'Segment.io': true }; } else { planIntegrationOptions = plan.integrations || {}; } } else { var defaultPlan = events.__default || { enabled: true }; if (!defaultPlan.enabled) { // Disabled events should always be sent to Segment. planIntegrationOptions = { All: false, 'Segment.io': true }; } } // Add the initialize integrations so the server-side ones can be disabled too defaults( msg.integrations, this._mergeInitializeAndPlanIntegrations(planIntegrationOptions) ); this._invoke('track', new Track(msg)); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element|Array} links * @param {string|Function} event * @param {Object|Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function( links, event, properties ) { if (!links) return this; // always arrays, handles jquery if (type(links) === 'element') links = [links]; var self = this; each(function(el) { if (type(el) !== 'element') { throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.'); } on(el, 'click', function(e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; var href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || el.getAttribute('xlink:href'); self.track(ev, props); if (href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function() { window.location.href = href; }); } }); }, links); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element|Array} forms * @param {string|Function} event * @param {Object|Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function( forms, event, properties ) { if (!forms) return this; // always arrays, handles jquery if (type(forms) === 'element') forms = [forms]; var self = this; each(function(el) { if (type(el) !== 'element') throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.'); function handler(e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function() { el.submit(); }); } // Support the events happening through jQuery or Zepto instead of through // the normal DOM API, because `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }, forms); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {string} [category] * @param {string} [name] * @param {Object|string} [properties] (or path) * @param {Object} [options] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.page = function(category, name, properties, options, fn) { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(properties)) (fn = properties), (options = properties = null); if (is.fn(name)) (fn = name), (options = properties = name = null); if (type(category) === 'object') (options = name), (properties = category), (name = category = null); if (type(name) === 'object') (options = properties), (properties = name), (name = null); if (type(category) === 'string' && type(name) !== 'string') (name = category), (category = null); /* eslint-enable no-unused-expressions, no-sequences */ properties = clone(properties) || {}; if (name) properties.name = name; if (category) properties.category = category; // Ensure properties has baseline spec properties. // TODO: Eventually move these entirely to `options.context.page` var defs = pageDefaults(); defaults(properties, defs); // Mirror user overrides to `options.context.page` (but exclude custom properties) // (Any page defaults get applied in `this.normalize` for consistency.) // Weird, yeah--moving special props to `context.page` will fix this in the long term. var overrides = pick(keys(defs), properties); if (!is.empty(overrides)) { options = options || {}; options.context = options.context || {}; options.context.page = overrides; } var msg = this.normalize({ properties: properties, category: category, options: options, name: name }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('page', new Page(msg)); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * FIXME: BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {string} [url] * @return {Analytics} * @api private */ Analytics.prototype.pageview = function(url) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {string} to * @param {string} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function(to, from, options, fn) { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(from)) (fn = from), (options = null), (from = null); if (is.object(from)) (options = from), (from = null); /* eslint-enable no-unused-expressions, no-sequences */ var msg = this.normalize({ options: options, previousId: from, userId: to }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('alias', new Alias(msg)); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function(fn) { if (is.fn(fn)) { if (this._readied) { nextTick(fn); } else { this.once('ready', fn); } } return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function(timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {string|boolean} str */ Analytics.prototype.debug = function(str) { if (!arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function(options) { options = options || {}; this.options = options; cookie.options(options.cookie); metrics.options(options.metrics); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function(fn) { if (is.fn(fn)) { this._timeout ? setTimeout(fn, this._timeout) : nextTick(fn); } return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {string} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function(method, facade) { var self = this; try { this._sourceMiddlewares.applyMiddlewares( extend(true, new Facade({}), facade), this._integrations, function(result) { // A nullified payload should not be sent. if (result === null) { self.log( 'Payload with method "%s" was null and dropped by source a middleware.', method ); return; } // Check if the payload is still a Facade. If not, convert it to one. if (!(result instanceof Facade)) { result = new Facade(result); } self.emit('invoke', result); metrics.increment('analytics_js.invoke', { method: method }); applyIntegrationMiddlewares(result); } ); } catch (e) { metrics.increment('analytics_js.invoke.error', { method: method }); self.log( 'Error invoking .%s method of %s integration: %o', method, name, e ); } return this; function applyIntegrationMiddlewares(facade) { var failedInitializations = self.failedInitializations || []; each(function(integration, name) { var facadeCopy = extend(true, new Facade({}), facade); if (!facadeCopy.enabled(name)) return; // Check if an integration failed to initialize. // If so, do not process the message as the integration is in an unstable state. if (failedInitializations.indexOf(name) >= 0) { self.log( 'Skipping invocation of .%s method of %s integration. Integration failed to initialize properly.', method, name ); } else { try { // Apply any integration middlewares that exist, then invoke the integration with the result. self._integrationMiddlewares.applyMiddlewares( facadeCopy, integration.name, function(result) { // A nullified payload should not be sent to an integration. if (result === null) { self.log( 'Payload to integration "%s" was null and dropped by a middleware.', name ); return; } // Check if the payload is still a Facade. If not, convert it to one. if (!(result instanceof Facade)) { result = new Facade(result); } metrics.increment('analytics_js.integration.invoke', { method: method, integration_name: integration.name }); integration.invoke.call(integration, method, result); } ); } catch (e) { metrics.increment('analytics_js.integration.invoke.error', { method: method, integration_name: integration.name }); self.log( 'Error invoking .%s method of %s integration: %o', method, name, e ); } } }, self._integrations); } }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args) { var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Reset group and user traits and id's. * * @api public */ Analytics.prototype.reset = function() { this.user().logout(); this.group().logout(); }; /** * Parse the query string for callable methods. * * @param {String} query * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function(query) { // Parse querystring to an object var q = querystring.parse(query); // Create traits and properties objects, populate from querysting params var traits = pickPrefix('ajs_trait_', q); var props = pickPrefix('ajs_prop_', q); // Trigger based on callable parameters in the URL if (q.ajs_uid) this.identify(q.ajs_uid, traits); if (q.ajs_event) this.track(q.ajs_event, props); if (q.ajs_aid) user.anonymousId(q.ajs_aid); return this; /** * Create a shallow copy of an input object containing only the properties * whose keys are specified by a prefix, stripped of that prefix * * @param {String} prefix * @param {Object} object * @return {Object} * @api private */ function pickPrefix(prefix, object) { var length = prefix.length; var sub; return foldl( function(acc, val, key) { if (key.substr(0, length) === prefix) { sub = key.substr(length); acc[sub] = val; } return acc; }, {}, object ); } }; /** * Normalize the given `msg`. * * @param {Object} msg * @return {Object} */ Analytics.prototype.normalize = function(msg) { msg = normalize(msg, keys(this._integrations)); if (msg.anonymousId) user.anonymousId(msg.anonymousId); msg.anonymousId = user.anonymousId(); // Ensure all outgoing requests include page data in their contexts. msg.context.page = defaults(msg.context.page || {}, pageDefaults()); return msg; }; /** * Merges the tracking plan and initialization integration options. * * @param {Object} planIntegrations Tracking plan integrations. * @return {Object} The merged integrations. */ Analytics.prototype._mergeInitializeAndPlanIntegrations = function( planIntegrations ) { // Do nothing if there are no initialization integrations if (!this.options.integrations) { return planIntegrations; } // Clone the initialization integrations var integrations = extend({}, this.options.integrations); var integrationName; // Allow the tracking plan to disable integrations that were explicitly // enabled on initialization if (planIntegrations.All === false) { integrations = { All: false }; } for (integrationName in planIntegrations) { if (planIntegrations.hasOwnProperty(integrationName)) { // Don't allow the tracking plan to re-enable disabled integrations if (this.options.integrations[integrationName] !== false) { integrations[integrationName] = planIntegrations[integrationName]; } } } return integrations; }; /** * No conflict support. */ Analytics.prototype.noConflict = function() { window.analytics = _analytics; return this; }; /* * Exports. */ module.exports = Analytics; module.exports.cookie = cookie; module.exports.memory = memory; module.exports.store = store; module.exports.metrics = metrics;
define([ '../Core/defaultValue', '../Core/defined', '../Core/DeveloperError', '../Renderer/modernizeShader', '../Shaders/Builtin/CzmBuiltins', './AutomaticUniforms' ], function( defaultValue, defined, DeveloperError, modernizeShader, CzmBuiltins, AutomaticUniforms) { 'use strict'; function removeComments(source) { // remove inline comments source = source.replace(/\/\/.*/g, ''); // remove multiline comment block return source.replace(/\/\*\*[\s\S]*?\*\//gm, function(match) { // preserve the number of lines in the comment block so the line numbers will be correct when debugging shaders var numberOfLines = match.match(/\n/gm).length; var replacement = ''; for (var lineNumber = 0; lineNumber < numberOfLines; ++lineNumber) { replacement += '\n'; } return replacement; }); } function getDependencyNode(name, glslSource, nodes) { var dependencyNode; // check if already loaded for (var i = 0; i < nodes.length; ++i) { if (nodes[i].name === name) { dependencyNode = nodes[i]; } } if (!defined(dependencyNode)) { // strip doc comments so we don't accidentally try to determine a dependency for something found // in a comment glslSource = removeComments(glslSource); // create new node dependencyNode = { name : name, glslSource : glslSource, dependsOn : [], requiredBy : [], evaluated : false }; nodes.push(dependencyNode); } return dependencyNode; } function generateDependencies(currentNode, dependencyNodes) { if (currentNode.evaluated) { return; } currentNode.evaluated = true; // identify all dependencies that are referenced from this glsl source code var czmMatches = currentNode.glslSource.match(/\bczm_[a-zA-Z0-9_]*/g); if (defined(czmMatches) && czmMatches !== null) { // remove duplicates czmMatches = czmMatches.filter(function(elem, pos) { return czmMatches.indexOf(elem) === pos; }); czmMatches.forEach(function(element) { if (element !== currentNode.name && ShaderSource._czmBuiltinsAndUniforms.hasOwnProperty(element)) { var referencedNode = getDependencyNode(element, ShaderSource._czmBuiltinsAndUniforms[element], dependencyNodes); currentNode.dependsOn.push(referencedNode); referencedNode.requiredBy.push(currentNode); // recursive call to find any dependencies of the new node generateDependencies(referencedNode, dependencyNodes); } }); } } function sortDependencies(dependencyNodes) { var nodesWithoutIncomingEdges = []; var allNodes = []; while (dependencyNodes.length > 0) { var node = dependencyNodes.pop(); allNodes.push(node); if (node.requiredBy.length === 0) { nodesWithoutIncomingEdges.push(node); } } while (nodesWithoutIncomingEdges.length > 0) { var currentNode = nodesWithoutIncomingEdges.shift(); dependencyNodes.push(currentNode); for (var i = 0; i < currentNode.dependsOn.length; ++i) { // remove the edge from the graph var referencedNode = currentNode.dependsOn[i]; var index = referencedNode.requiredBy.indexOf(currentNode); referencedNode.requiredBy.splice(index, 1); // if referenced node has no more incoming edges, add to list if (referencedNode.requiredBy.length === 0) { nodesWithoutIncomingEdges.push(referencedNode); } } } // if there are any nodes left with incoming edges, then there was a circular dependency somewhere in the graph var badNodes = []; for (var j = 0; j < allNodes.length; ++j) { if (allNodes[j].requiredBy.length !== 0) { badNodes.push(allNodes[j]); } } //>>includeStart('debug', pragmas.debug); if (badNodes.length !== 0) { var message = 'A circular dependency was found in the following built-in functions/structs/constants: \n'; for (var k = 0; k < badNodes.length; ++k) { message = message + badNodes[k].name + '\n'; } throw new DeveloperError(message); } //>>includeEnd('debug'); } function getBuiltinsAndAutomaticUniforms(shaderSource) { // generate a dependency graph for builtin functions var dependencyNodes = []; var root = getDependencyNode('main', shaderSource, dependencyNodes); generateDependencies(root, dependencyNodes); sortDependencies(dependencyNodes); // Concatenate the source code for the function dependencies. // Iterate in reverse so that dependent items are declared before they are used. var builtinsSource = ''; for (var i = dependencyNodes.length - 1; i >= 0; --i) { builtinsSource = builtinsSource + dependencyNodes[i].glslSource + '\n'; } return builtinsSource.replace(root.glslSource, ''); } function combineShader(shaderSource, isFragmentShader, context) { var i; var length; // Combine shader sources, generally for pseudo-polymorphism, e.g., czm_getMaterial. var combinedSources = ''; var sources = shaderSource.sources; if (defined(sources)) { for (i = 0, length = sources.length; i < length; ++i) { // #line needs to be on its own line. combinedSources += '\n#line 0\n' + sources[i]; } } combinedSources = removeComments(combinedSources); // Extract existing shader version from sources var version; combinedSources = combinedSources.replace(/#version\s+(.*?)\n/gm, function(match, group1) { //>>includeStart('debug', pragmas.debug); if (defined(version) && version !== group1) { throw new DeveloperError('inconsistent versions found: ' + version + ' and ' + group1); } //>>includeEnd('debug'); // Extract #version to put at the top version = group1; // Replace original #version directive with a new line so the line numbers // are not off by one. There can be only one #version directive // and it must appear at the top of the source, only preceded by // whitespace and comments. return '\n'; }); // Extract shader extensions from sources var extensions = []; combinedSources = combinedSources.replace(/#extension.*\n/gm, function(match) { // Extract extension to put at the top extensions.push(match); // Replace original #extension directive with a new line so the line numbers // are not off by one. return '\n'; }); // Remove precision qualifier combinedSources = combinedSources.replace(/precision\s(lowp|mediump|highp)\s(float|int);/, ''); // Replace main() for picked if desired. var pickColorQualifier = shaderSource.pickColorQualifier; if (defined(pickColorQualifier)) { combinedSources = ShaderSource.createPickFragmentShaderSource(combinedSources, pickColorQualifier); } // combine into single string var result = ''; // #version must be first // defaults to #version 100 if not specified if (defined(version)) { result = '#version ' + version + '\n'; } var extensionsLength = extensions.length; for (i = 0; i < extensionsLength; i++) { result += extensions[i]; } if (isFragmentShader) { result += '\ #ifdef GL_FRAGMENT_PRECISION_HIGH\n\ precision highp float;\n\ #else\n\ precision mediump float;\n\ #endif\n\n'; } // Prepend #defines for uber-shaders var defines = shaderSource.defines; if (defined(defines)) { for (i = 0, length = defines.length; i < length; ++i) { var define = defines[i]; if (define.length !== 0) { result += '#define ' + define + '\n'; } } } // GLSLModernizer inserts its own layout qualifiers // at this position in the source if (context.webgl2) { result += '#define OUTPUT_DECLARATION\n\n'; } // append built-ins if (shaderSource.includeBuiltIns) { result += getBuiltinsAndAutomaticUniforms(combinedSources); } // reset line number result += '\n#line 0\n'; // append actual source result += combinedSources; // modernize the source if (context.webgl2) { result = modernizeShader(result, isFragmentShader, true); } return result; } /** * An object containing various inputs that will be combined to form a final GLSL shader string. * * @param {Object} [options] Object with the following properties: * @param {String[]} [options.sources] An array of strings to combine containing GLSL code for the shader. * @param {String[]} [options.defines] An array of strings containing GLSL identifiers to <code>#define</code>. * @param {String} [options.pickColorQualifier] The GLSL qualifier, <code>uniform</code> or <code>varying</code>, for the input <code>czm_pickColor</code>. When defined, a pick fragment shader is generated. * @param {Boolean} [options.includeBuiltIns=true] If true, referenced built-in functions will be included with the combined shader. Set to false if this shader will become a source in another shader, to avoid duplicating functions. * * @exception {DeveloperError} options.pickColorQualifier must be 'uniform' or 'varying'. * * @example * // 1. Prepend #defines to a shader * var source = new Cesium.ShaderSource({ * defines : ['WHITE'], * sources : ['void main() { \n#ifdef WHITE\n gl_FragColor = vec4(1.0); \n#else\n gl_FragColor = vec4(0.0); \n#endif\n }'] * }); * * // 2. Modify a fragment shader for picking * var source = new Cesium.ShaderSource({ * sources : ['void main() { gl_FragColor = vec4(1.0); }'], * pickColorQualifier : 'uniform' * }); * * @private */ function ShaderSource(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var pickColorQualifier = options.pickColorQualifier; //>>includeStart('debug', pragmas.debug); if (defined(pickColorQualifier) && pickColorQualifier !== 'uniform' && pickColorQualifier !== 'varying') { throw new DeveloperError('options.pickColorQualifier must be \'uniform\' or \'varying\'.'); } //>>includeEnd('debug'); this.defines = defined(options.defines) ? options.defines.slice(0) : []; this.sources = defined(options.sources) ? options.sources.slice(0) : []; this.pickColorQualifier = pickColorQualifier; this.includeBuiltIns = defaultValue(options.includeBuiltIns, true); } ShaderSource.prototype.clone = function() { return new ShaderSource({ sources : this.sources, defines : this.defines, pickColorQualifier : this.pickColorQualifier, includeBuiltIns : this.includeBuiltIns }); }; ShaderSource.replaceMain = function(source, renamedMain) { renamedMain = 'void ' + renamedMain + '()'; return source.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, renamedMain); }; /** * Create a single string containing the full, combined vertex shader with all dependencies and defines. * * @param {Context} context The current rendering context * * @returns {String} The combined shader string. */ ShaderSource.prototype.createCombinedVertexShader = function(context) { return combineShader(this, false, context); }; /** * Create a single string containing the full, combined fragment shader with all dependencies and defines. * * @param {Context} context The current rendering context * * @returns {String} The combined shader string. */ ShaderSource.prototype.createCombinedFragmentShader = function(context) { return combineShader(this, true, context); }; /** * For ShaderProgram testing * @private */ ShaderSource._czmBuiltinsAndUniforms = {}; // combine automatic uniforms and Cesium built-ins for ( var builtinName in CzmBuiltins) { if (CzmBuiltins.hasOwnProperty(builtinName)) { ShaderSource._czmBuiltinsAndUniforms[builtinName] = CzmBuiltins[builtinName]; } } for ( var uniformName in AutomaticUniforms) { if (AutomaticUniforms.hasOwnProperty(uniformName)) { var uniform = AutomaticUniforms[uniformName]; if (typeof uniform.getDeclaration === 'function') { ShaderSource._czmBuiltinsAndUniforms[uniformName] = uniform.getDeclaration(uniformName); } } } ShaderSource.createPickVertexShaderSource = function(vertexShaderSource) { var renamedVS = ShaderSource.replaceMain(vertexShaderSource, 'czm_old_main'); var pickMain = 'attribute vec4 pickColor; \n' + 'varying vec4 czm_pickColor; \n' + 'void main() \n' + '{ \n' + ' czm_old_main(); \n' + ' czm_pickColor = pickColor; \n' + '}'; return renamedVS + '\n' + pickMain; }; ShaderSource.createPickFragmentShaderSource = function(fragmentShaderSource, pickColorQualifier) { var renamedFS = ShaderSource.replaceMain(fragmentShaderSource, 'czm_old_main'); var pickMain = pickColorQualifier + ' vec4 czm_pickColor; \n' + 'void main() \n' + '{ \n' + ' czm_old_main(); \n' + ' if (gl_FragColor.a == 0.0) { \n' + ' discard; \n' + ' } \n' + ' gl_FragColor = czm_pickColor; \n' + '}'; return renamedFS + '\n' + pickMain; }; ShaderSource.findVarying = function(shaderSource, names) { var sources = shaderSource.sources; var namesLength = names.length; for (var i = 0; i < namesLength; ++i) { var name = names[i]; var sourcesLength = sources.length; for (var j = 0; j < sourcesLength; ++j) { if (sources[j].indexOf(name) !== -1) { return name; } } } return undefined; }; var normalVaryingNames = ['v_normalEC', 'v_normal']; ShaderSource.findNormalVarying = function(shaderSource) { return ShaderSource.findVarying(shaderSource, normalVaryingNames); }; var positionVaryingNames = ['v_positionEC']; ShaderSource.findPositionVarying = function(shaderSource) { return ShaderSource.findVarying(shaderSource, positionVaryingNames); }; return ShaderSource; });
import React from 'react'; import { mountWithTheme, renderWithTheme } from '@sfitzpatrick/enzyme-context-helpers'; import Icon from '../Icon'; import icons from '../../Icon/icons'; describe('Icons', () => { let wrapper, component; const icon = 'close'; const defaultProps = { icon, size: '16' }; beforeEach(() => { component = <Icon {...defaultProps} />; wrapper = mountWithTheme(component); }); test('should match snapshot', () => { const snap = renderWithTheme(component).toJSON(); expect(snap).toMatchSnapshot(); expect(snap).toHaveStyleRule('fill', 'currentColor'); expect(snap).toHaveStyleRule('height', '16px'); expect(snap).toHaveStyleRule('width', '16px'); }); test('should render Icon', () => { expect(wrapper.is(Icon)).toBeTruthy(); }); test('should render correct SVG for requested icon', () => { expect(wrapper.find('svg')).toHaveLength(1); expect(wrapper.find('path').props().d).toEqual(icons[icon].path); }); });
const { ADD_TO_WATCHLIST, GET_WATCHLIST } = require("../actionTypes"); const initialState = { movies: null, error: null, }; const WatchlistReducer = (state = initialState, actions) => { const { type, payload } = actions; switch (type) { case GET_WATCHLIST: if (payload.error) { return { ...state, error: payload }; } else { return { ...state, admin: payload }; } case ADD_TO_WATCHLIST: if (payload.error) { return { ...state, error: payload }; } else { return { ...state, admin: payload }; } default: return state; } }; export default WatchlistReducer;
import { h } from 'vue' export default { name: "PlayCircleLine", vendor: "Rx", type: "", tags: ["play","circle","line"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"rx-play-circle-line","innerHTML":" <g> <path fill='none' d='M0 0h24v24H0z'/> <path d='M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zM10.622 8.415l4.879 3.252a.4.4 0 0 1 0 .666l-4.88 3.252a.4.4 0 0 1-.621-.332V8.747a.4.4 0 0 1 .622-.332z'/> </g>"}, ) } }
import github from './configurations/configuration-github'; import gitlab from './configurations/configuration-gitlab'; const CONFIGURATIONS = [github, gitlab]; export default host => { const split_host = host.split('.'); for (let i = 0; i < CONFIGURATIONS.length; i++) { const conf_host = CONFIGURATIONS[i].HOST; const number_of_tokens = conf_host.split('.').length; if (number_of_tokens > split_host.length) { continue; } if (conf_host === split_host.slice(-1 * number_of_tokens).join('.')) { return CONFIGURATIONS[i]; } } throw new Error(`Could not find configuration for host "${host}"`); };
/*! localForage -- Offline Storage, Improved Version 0.8.1 http://mozilla.github.io/localForage (c) 2013-2014 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, require, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = require = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());// Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? require('promise') : this.Promise; var db = null; var dbInfo = {}; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function withStoreOnError() { reject(openreq.error); }; openreq.onupgradeneeded = function withStoreOnUpgradeNeeded() { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); }; openreq.onsuccess = function withStoreOnSuccess() { db = openreq.result; resolve(); }; }); } function getItem(key, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (callback) { callback(value); } resolve(value); }; req.onerror = function() { if (callback) { callback(null, req.error); } reject(req.error); }; }); }); } function setItem(key, value, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readwrite') .objectStore(dbInfo.storeName); // Cast to undefined so the value passed to callback/promise is // the same as what one would get out of `getItem()` later. // This leads to some weirdness (setItem('foo', undefined) will // return "null"), but it's not my fault localStorage is our // baseline and that it's weird. if (value === undefined) { value = null; } var req = store.put(value, key); req.onsuccess = function() { if (callback) { callback(value); } resolve(value); }; req.onerror = function() { if (callback) { callback(null, req.error); } reject(req.error); }; }); }); } function removeItem(key, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readwrite') .objectStore(dbInfo.storeName); // We use `['delete']` instead of `.delete` because IE 8 will // throw a fit if it sees the reserved word "delete" in this // scenario. See: https://github.com/mozilla/localForage/pull/67 // // This can be removed once we no longer care about IE 8, for // what that's worth. // TODO: Write a test against this? Maybe IE in general? Also, // make sure the minify step doesn't optimise this to `.delete`, // though it currently doesn't. var req = store['delete'](key); req.onsuccess = function() { if (callback) { callback(); } resolve(); }; req.onerror = function() { if (callback) { callback(req.error); } reject(req.error); }; // The request will be aborted if we've exceeded our storage // space. In this case, we will reject with a specific // "QuotaExceededError". req.onabort = function(event) { var error = event.target.error; if (error === 'QuotaExceededError') { if (callback) { callback(error); } reject(error); } }; }); }); } function clear(callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readwrite') .objectStore(dbInfo.storeName); var req = store.clear(); req.onsuccess = function() { if (callback) { callback(); } resolve(); }; req.onerror = function() { if (callback) { callback(null, req.error); } reject(req.error); }; }); }); } function length(callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { if (callback) { callback(req.result); } resolve(req.result); }; req.onerror = function() { if (callback) { callback(null, req.error); } reject(req.error); }; }); }); } function key(n, callback) { var _this = this; return new Promise(function(resolve, reject) { if (n < 0) { if (callback) { callback(null); } resolve(null); return; } _this.ready().then(function() { var store = db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys if (callback) { callback(null); } resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. if (callback) { callback(cursor.key); } resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. if (callback) { callback(cursor.key); } resolve(cursor.key); } } }; req.onerror = function() { if (callback) { callback(null, req.error); } reject(req.error); }; }); }); } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key }; if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = asyncStorage; } else { this.asyncStorage = asyncStorage; } }).call(this); // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; var keyPrefix = ''; var dbInfo = {}; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? require('promise') : this.Promise; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { if (options) { for (var i in options) { dbInfo[i] = options[i]; } } keyPrefix = dbInfo.name + '/'; return Promise.resolve(); } var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var _this = this; return new Promise(function(resolve) { _this.ready().then(function() { localStorage.clear(); if (callback) { callback(); } resolve(); }); }); } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { try { var result = localStorage.getItem(keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = _deserialize(result); } if (callback) { callback(result, null); } resolve(result); } catch (e) { if (callback) { callback(null, e); } reject(e); } }); }); } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var _this = this; return new Promise(function(resolve) { _this.ready().then(function() { var result = localStorage.key(n); // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(keyPrefix.length); } if (callback) { callback(result); } resolve(result); }); }); } // Supply the number of keys in the datastore to the callback function. function length(callback) { var _this = this; return new Promise(function(resolve) { _this.ready().then(function() { var result = localStorage.length; if (callback) { callback(result); } resolve(result); }); }); } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var _this = this; return new Promise(function(resolve) { _this.ready().then(function() { localStorage.removeItem(keyPrefix + key); if (callback) { callback(); } resolve(); }); }); } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function _deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); // Fill the string into a ArrayBuffer. var buffer = new ArrayBuffer(serializedString.length * 2); // 2 bytes for each char var bufferView = new Uint16Array(buffer); for (var i = serializedString.length - 1; i >= 0; i--) { bufferView[i] = serializedString.charCodeAt(i); } // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return new Blob([buffer]); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } // Converts a buffer to a string to store, serialized, in the backend // storage library. function _bufferToString(buffer) { var str = ''; var uint16Array = new Uint16Array(buffer); try { str = String.fromCharCode.apply(null, uint16Array); } catch (e) { // This is a fallback implementation in case the first one does // not work. This is required to get the phantomjs passing... for (var i = 0; i < uint16Array.length; i++) { str += String.fromCharCode(uint16Array[i]); } } return str; } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function _serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error("Failed to get type for BinaryArray")); } } callback(marker + _bufferToString(buffer)); } else if (valueString === "[object Blob]") { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { var str = _bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { if (this.console && this.console.error) { this.console.error("Couldn't convert value into a JSON string: ", value); } callback(null, e); } } } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; _serialize(value, function(value, error) { if (error) { if (callback) { callback(null, error); } reject(error); } else { try { localStorage.setItem(keyPrefix + key, value); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { if (callback) { callback(null, e); } reject(e); } } if (callback) { callback(originalValue); } resolve(originalValue); } }); }); }); } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key }; if (typeof define === 'function' && define.amd) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = localStorageWrapper; } else { this.localStorageWrapper = localStorageWrapper; } }).call(this); /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL is Base64 serializing // it, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? require('promise') : this.Promise; var openDatabase = this.openDatabase; var db = null; var dbInfo = {}; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var _this = this; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } return new Promise(function(resolve) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { db = openDatabase(dbInfo.name, dbInfo.version, dbInfo.description, dbInfo.size); } catch (e) { return _this.setDriver('localStorageWrapper').then(resolve); } // Create our key/value table if it doesn't exist. db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { resolve(); }, null); }); }); } function getItem(key, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = _deserialize(result); } if (callback) { callback(result); } resolve(result); }, function(t, error) { if (callback) { callback(null, error); } reject(error); }); }); }); }); } function setItem(key, value, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; _serialize(value, function(value, error) { if (error) { reject(error); } else { db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { if (callback) { callback(originalValue); } resolve(originalValue); }, function(t, error) { if (callback) { callback(null, error); } reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. if (callback) { callback(null, sqlError); } reject(sqlError); } }); } }); }); }); } function removeItem(key, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { if (callback) { callback(); } resolve(); }, function(t, error) { if (callback) { callback(error); } reject(error); }); }); }); }); } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { if (callback) { callback(); } resolve(); }, function(t, error) { if (callback) { callback(error); } reject(error); }); }); }); }); } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; if (callback) { callback(result); } resolve(result); }, function(t, error) { if (callback) { callback(null, error); } reject(error); }); }); }); }); } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var _this = this; return new Promise(function(resolve, reject) { _this.ready().then(function() { db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; if (callback) { callback(result); } resolve(result); }, function(t, error) { if (callback) { callback(null, error); } reject(error); }); }); }); }); } // Converts a buffer to a string to store, serialized, in the backend // storage library. function _bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var i; var base64String = ''; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + "="; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + "=="; } return base64String; } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function _deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === "=") { bufferLength--; if (serializedString[serializedString.length - 2] === "=") { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return new Blob([buffer]); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function _serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error("Failed to get type for BinaryArray")); } } callback(marker + _bufferToString(buffer)); } else if (valueString === "[object Blob]") { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { var str = _bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { if (this.console && this.console.error) { this.console.error("Couldn't convert value into a JSON string: ", value); } callback(null, e); } } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key }; if (typeof define === 'function' && define.amd) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(this); (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? require('promise') : this.Promise; // Avoid those magic constants! var MODULE_TYPE_DEFINE = 1; var MODULE_TYPE_EXPORT = 2; var MODULE_TYPE_WINDOW = 3; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = MODULE_TYPE_WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof define === 'function' && define.amd) { moduleType = MODULE_TYPE_DEFINE; } else if (typeof module !== 'undefined' && module.exports) { moduleType = MODULE_TYPE_EXPORT; } // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; var supportsIndexedDB = indexedDB && indexedDB.open('_localforage_spec_test', 1) .onupgradeneeded === null; // Check for WebSQL. var openDatabase = this.openDatabase; // The actual localForage object that we expose as a module or via a global. // It's extended by pulling in one of our other libraries. var _this = this; var localForage = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage', _config: { description: '', name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }, // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. config: function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + "has been used."); } for (var i in options) { this._config[i] = options[i]; } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }, driver: function() { return this._driver || null; }, _ready: Promise.reject(new Error("setDriver() wasn't called")), setDriver: function(driverName, callback) { var driverSet = new Promise(function(resolve, reject) { if ((!supportsIndexedDB && driverName === localForage.INDEXEDDB) || (!openDatabase && driverName === localForage.WEBSQL)) { reject(localForage); return; } localForage._ready = null; // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === MODULE_TYPE_DEFINE) { require([driverName], function(lib) { localForage._extend(lib); resolve(localForage); }); // Return here so we don't resolve the promise twice. return; } else if (moduleType === MODULE_TYPE_EXPORT) { // Making it browserify friendly var driver; switch (driverName) { case localForage.INDEXEDDB: driver = require('./drivers/indexeddb'); break; case localForage.LOCALSTORAGE: driver = require('./drivers/localstorage'); break; case localForage.WEBSQL: driver = require('./drivers/websql'); } localForage._extend(driver); } else { localForage._extend(_this[driverName]); } resolve(localForage); }); driverSet.then(callback, callback); return driverSet; }, ready: function(callback) { if (this._ready === null) { this._ready = this._initStorage(this._config); } this._ready.then(callback, callback); return this._ready; }, _extend: function(libraryMethodsAndProperties) { for (var i in libraryMethodsAndProperties) { if (libraryMethodsAndProperties.hasOwnProperty(i)) { this[i] = libraryMethodsAndProperties[i]; } } } }; // Select our storage library. var storageLibrary; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 if (supportsIndexedDB) { storageLibrary = localForage.INDEXEDDB; } else if (openDatabase) { // WebSQL is available, so we'll use that. storageLibrary = localForage.WEBSQL; } else { // If nothing else is available, we use localStorage. storageLibrary = localForage.LOCALSTORAGE; } // If window.localForageConfig is set, use it for configuration. if (this.localForageConfig) { localForage.config = this.localForageConfig; } // Set the (default) driver. localForage.setDriver(storageLibrary); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === MODULE_TYPE_DEFINE) { define(function() { return localForage; }); } else if (moduleType === MODULE_TYPE_EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(this);
(function() { var module = angular.module('loom_chapter_title', []); module.directive('loomChapterTitle', function($compile) { var template = '<p>{{ chapterContent }}</p>'; return { link: function(scope, element, attrs) { element.html(template).show(); $compile(element.contents())(scope); }, scope: { chapterContent: '=' } }; }); })();
/** * Created by jhjc on 2017-6-30. */ import Vue from 'vue' export var bus = new Vue()