text
stringlengths
2
6.14k
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Discount = mongoose.model('Discount'); /** * Globals */ var user, discount; /** * Unit tests */ describe('Discount Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'password' }); user.save(function() { discount = new Discount({ name: 'Discount Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return discount.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { discount.name = ''; return discount.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { Discount.remove().exec(); User.remove().exec(); done(); }); });
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/indicators/trendline', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'indicators/trendline.src.js', [_modules['parts/Utilities.js']], function (U) { /* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var isArray = U.isArray, seriesType = U.seriesType; /** * The Trend line series type. * * @private * @class * @name Highcharts.seriesTypes.trendline * * @augments Highcharts.Series */ seriesType('trendline', 'sma', /** * Trendline (linear regression) fits a straight line to the selected data * using a method called the Sum Of Least Squares. This series requires the * `linkedTo` option to be set. * * @sample stock/indicators/trendline * Trendline indicator * * @extends plotOptions.sma * @since 7.1.3 * @product highstock * @requires stock/indicators/indicators * @requires stock/indicators/trendline * @optionparent plotOptions.trendline */ { /** * @excluding period */ params: { /** * The point index which indicator calculations will base. For * example using OHLC data, index=2 means the indicator will be * calculated using Low values. * * @default 3 */ index: 3 } }, /** * @lends Highcharts.Series# */ { nameBase: 'Trendline', nameComponents: false, getValues: function (series, params) { var xVal = series.xData, yVal = series.yData, LR = [], xData = [], yData = [], sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, xValLength = xVal.length, index = params.index, alpha, beta, i, x, y; // Get sums: for (i = 0; i < xValLength; i++) { x = xVal[i]; y = isArray(yVal[i]) ? yVal[i][index] : yVal[i]; sumX += x; sumY += y; sumXY += x * y; sumX2 += x * x; } // Get slope and offset: alpha = (xValLength * sumXY - sumX * sumY) / (xValLength * sumX2 - sumX * sumX); if (isNaN(alpha)) { alpha = 0; } beta = (sumY - alpha * sumX) / xValLength; // Calculate linear regression: for (i = 0; i < xValLength; i++) { x = xVal[i]; y = alpha * x + beta; // Prepare arrays required for getValues() method LR[i] = [x, y]; xData[i] = x; yData[i] = y; } return { xData: xData, yData: yData, values: LR }; } }); /** * A `TrendLine` series. If the [type](#series.trendline.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.trendline * @since 7.1.3 * @product highstock * @excluding dataParser, dataURL * @requires stock/indicators/indicators * @requires stock/indicators/trendline * @apioption series.trendline */ ''; // to include the above in the js output }); _registerModule(_modules, 'masters/indicators/trendline.src.js', [], function () { }); }));
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pagesWithRedirects = ['/manage-va-debt/your-debt/']; const shouldIgnore = url => { const parsedUrl = new URL(url); return ( !url.endsWith('auth/login/callback/') && !url.includes('playbook/') && !url.includes('pittsburgh-health-care/') && !/.*opt-out-information-sharing.*/.test(url) && !pagesWithRedirects.some(redirectUrl => parsedUrl.pathname === redirectUrl) ); }; function sitemapURLs() { return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), ) .then(urls => { const onlyTest508Rules = [ // 404 page contains 2 search auto-suggest elements with the same element ID, // which violates WCAG 2.0 standards. This element id is referenced by // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID // of one of the elements, search won't work. '/404.html', // This is here because aXe bug flags the custom select component on this page '/find-locations/', // This is here because an aXe bug flags the autosuggest component on this page '/education/gi-bill-comparison-tool/', /* Using the Microsoft Healthbot framework, the chatbot currently violates two rules in the WCAG 2.0(A) ruleset: aria-valid-attr-value and aria-required-children. There are open Github issues with Microsoft to address these. The 508 ruleset is slightly less strict to test on chatbot for now. */ '/coronavirus-chatbot/', ]; // Whitelist of URLs to only test against the 'section508' rule set and not // the stricter 'wcag2a' rule set. For each URL added to this list, please // add a comment explaining why it cannot be tested against stricter rules. return { urls, onlyTest508Rules }; }); } module.exports = { sitemapURLs };
import settings from './../settings' import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './general' module.exports = { applyLimbForces: (Eves) => { for(var i = 0; i < Eves.length; i++) { var eve = Eves[i]; for(var j = 0; j < eve.limbs.length; j++) { var limb = eve.limbs[j]; var b0 = eve.bodyParts[limb.connections[0]]; var b1 = eve.bodyParts[limb.connections[1]]; var displacement, force; limb.currentLength = findDistance(b0.pos, b1.pos) if(limb.growing) { displacement = limb.maxLength - limb.currentLength; force = displacement * 0.1 - 1.5; if(limb.currentLength >= limb.maxLength) { limb.growing = false; } } else { displacement = limb.initialLength - limb.currentLength; force = displacement * 0.1 + 1.5; if(limb.currentLength <= limb.initialLength) { limb.growing = true; } } var xPosDiff = b1.pos.x - b0.pos.x; var yPosDiff = b1.pos.y - b0.pos.y; if(xPosDiff === 0) { var theta = Math.PI; } else { var theta = Math.atan(yPosDiff / xPosDiff); } if (xPosDiff >= 0) { force *= -1; } var movementFactor = 1; if(limb.growing) { movementFactor = 0.5; } var dVx0 = force / b0.mass * Math.cos(theta); var dVy0 = force / b0.mass * Math.sin(theta); var dVx1 = -force / b1.mass * Math.cos(theta) * movementFactor; var dVy1 = -force / b1.mass * Math.sin(theta) * movementFactor; b0.vel.x = Math.min( 20, Math.max( b0.vel.x + dVx0, -20 )); b0.vel.y = Math.min( 20, Math.max( b0.vel.y + dVy0, -20 )); b1.vel.x = Math.min( 20, Math.max( b1.vel.x + dVx1, -20 )); b1.vel.y = Math.min( 20, Math.max( b1.vel.y + dVy1, -20 )); } } }, updateBodyPartPositions: (Eves) => { for(var i = 0; i < Eves.length; i++) { var eve = Eves[i]; for(var j = 0; j < eve.bodyParts.length; j++) { var bodyPart = eve.bodyParts[j]; bodyPart.pos.x += bodyPart.vel.x; //check if offscreen if(bodyPart.pos.x <= bodyPart.mass || bodyPart.pos.x >= settings.width - bodyPart.mass) { bodyPart.pos.x = limitPositions(bodyPart.pos.x, 1, bodyPart.mass)[0]; bodyPart.vel.x = -1 * bodyPart.vel.x; } bodyPart.pos.y += bodyPart.vel.y; if(bodyPart.pos.y <= bodyPart.mass || bodyPart.pos.y >= settings.height - bodyPart.mass) { bodyPart.pos.y = limitPositions(1, bodyPart.pos.y, bodyPart.mass)[1]; bodyPart.vel.y = -1 * bodyPart.vel.y; } //check if offscreen //NEEEDS TO GO ON CLIENT ONLY?? // d3.select('#' + eve.id + 'b' + j) // .attr('cx', bodyPart.pos.x).attr('cy', bodyPart.pos.y); // } for(var k = 0; k < eve.limbs.length; k++) { var b0 = eve.bodyParts[eve.limbs[k].connections[0]]; var b1 = eve.bodyParts[eve.limbs[k].connections[1]]; //NEEDS TO GO ON CLIENT ONLY?? // d3.select('#' + eve.id + 'l' + k) // .attr('x1', b0.pos.x).attr('y1', b0.pos.y) // .attr('x2', b1.pos.x).attr('y2', b1.pos.y); // } } } }
import { editMenu, viewMenu, windowMenu, helpMenu } from './common-menus' import { addDarwinMenuItems } from './darwin-menus' import { app, Menu } from 'electron' const initialMenu = [ editMenu, viewMenu, windowMenu, helpMenu ] export const setupMenus = () => { const menuItems = (process.platform === 'darwin') ? addDarwinMenuItems(initialMenu) : initialMenu const menu = Menu.buildFromTemplate(menuItems) Menu.setApplicationMenu(menu) }
var debug = process.env.NODE_ENV !== "production" var webpack = require('webpack') module.exports = { context: __dirname, devtool: debug ? "inline-sourcemap" : null, entry: "./js/app.jsx", module: { loaders: [ { test: /\.jsx?$/, exclude:/(node_modules|bower_components)/, loader: 'babel-loader', query:{ presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'] } } ] }, output: { path: __dirname + "/js", filename: "bundle.js" }, plugins: debug ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
// // This file made available under CC0 1.0 Universal (https://creativecommons.org/publicdomain/zero/1.0/legalcode) // var aws = require('aws-sdk'); var s3 = new aws.S3(); var zlib = require('zlib'); var config = new aws.ConfigService(); var iam = new aws.IAM(); // Helper function used to validate input function checkDefined(reference, referenceName) { if (!reference) { console.log("Error: " + referenceName + " is not defined"); throw referenceName; } return reference; } // Extract the account ID from the event function getAccountId(invokingEvent) { checkDefined(invokingEvent, "invokingEvent"); checkDefined(invokingEvent.s3ObjectKey, "invokingEvent.s3ObjectKey"); var accountIdPattern = /AWSLogs\/(\d+)\/Config/; return accountIdPattern.exec(invokingEvent.s3ObjectKey)[1]; } // This is the handler that's invoked by Lambda exports.handler = function(event, context) { checkDefined(event, "event"); var invokingEvent = JSON.parse(event.invokingEvent); var ruleParameters = JSON.parse(event.ruleParameters); var s3key = invokingEvent.s3ObjectKey; var s3bucket = invokingEvent.s3Bucket; var accountId = getAccountId(invokingEvent); var orderingTimestamp = invokingEvent.notificationCreationTime; config.describeConfigurationRecorders({}, function(err, data) { var compliance = 'NON_COMPLIANT'; if (!err) { for (var i = 0; i < data.ConfigurationRecorders.length; i++) { if (data.ConfigurationRecorders[i].recordingGroup.allSupported && data.ConfigurationRecorders[i].recordingGroup.includeGlobalResourceTypes) { compliance = 'COMPLIANT'; } } } evaluation = { ComplianceResourceType: 'AWS::::Account', ComplianceResourceId: accountId, ComplianceType: compliance, OrderingTimestamp: orderingTimestamp }; putEvaluationsRequest = { Evaluations: [ evaluation ], ResultToken: event.resultToken }; config.putEvaluations(putEvaluationsRequest, function (err, data) { if (err) { context.fail(err); } else { context.succeed(data); } }); }); };
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) export class PlacePicker { @bindable location; constructor(element, mapsApi) { this.element = element; this.mapsApi = mapsApi; } attached() { // This loads the Google Maps API asynchronously. this.mapsApi.then(maps => { // Now that it's loaded, add a map to our HTML. var mapContainer = this.element.querySelector('.place-picker-map'); var map = new maps.Map(mapContainer, { center: {lat: -33.8688, lng: 151.2195}, zoom: 13 }); // Also convert our input field into a place autocomplete field. var input = this.element.querySelector('input'); var autocomplete = new google.maps.places.Autocomplete(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); autocomplete.bindTo('bounds', map); // Create a marker that will show where the selected place is. var marker = new google.maps.Marker({ map: map, anchorPoint: new google.maps.Point(0, -29) }); // Create a lambda that moves the marker and the map viewport. let updateMarker = () => { var position = new google.maps.LatLng(this.location.lat, this.location.lng); map.setCenter(position); marker.setPosition(position); marker.setVisible(true); }; // Ensure that the current location is shown properly. updateMarker(); // Update the location and its marker every time a new place is selected. autocomplete.addListener('place_changed', () => { marker.setVisible(false); var place = autocomplete.getPlace(); if (place.geometry) { this.location.name = place.name; this.location.lat = place.geometry.location.lat(); this.location.lng = place.geometry.location.lng(); updateMarker(); } }); }); } }
(function () { 'use strict'; angular .module('tierraDeColoresApp') .service('fiscalService', fiscalService); fiscalService.$inject = ['$q', '$http', 'cookieService', 'BaseURL', 'toaster', '$rootScope']; function fiscalService($q, $http, cookieService, BaseURL, toaster, $rootScope) { const exec = require('child_process').exec; const http = require('http'); const fs = require('fs'); const path = require('path'); var parser = document.createElement('a'); parser.href = BaseURL; var Auth = { 'usuario': 'AFIP_SMH/P-441F', 'password': 'T13RR4$7j15vker4L-L' }; this.read = function () { var datosRecu = null; var deferred = $q.defer(); var filePath = path.join(__dirname, 'FILE.ans'); fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) { if (!err) { datosRecu = data; deferred.resolve(datosRecu); } }); return deferred.promise; }; function print(tipo) { exec('wspooler.exe -p4 -l -f FILE.200', function (err, stdout, stderr) { if (err !== null) { console.log(err); $rootScope.$broadcast("printState", {tipo: tipo, status: false}); } else { $rootScope.$broadcast("printState", {tipo: tipo, status: true}); } }); } this.cleanFiles = function () { fs.unlink('FILE.200', function (err) { if (err) { console.log(err); } console.log('successfully deleted FILE.200'); }); fs.unlink('FILE.ans', function (err) { if (err) { console.log(err); } console.log('successfully deleted FILE.ans'); }); return true; }; this.factura_aOrFactura_b = function (factura, cliente, type) { var options = null; var token = cookieService.get('token'); var tipo; token.then(function (data) { options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (type === 0) { options.path = '/fiscal/factura_a?factura=' + factura + "&cliente=" + cliente; tipo = "Factura A"; } else if (1) { options.path = '/fiscal/factura_b?factura=' + factura + "&cliente=" + cliente; tipo = "Factura B"; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(tipo); } }); }); }; this.ticketOrRegalo = function (factura, serial) { var token = cookieService.get('token'); var type; token.then(function (data) { var options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (serial !== null & typeof serial !== 'undefined') { options.path = '/fiscal/regalo?factura=' + factura + "&serial=" + serial; type = "Regalo"; } else { options.path = '/fiscal/ticket?factura=' + factura; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(); } }); }); }; this.comprobanteZ = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f compZ.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; this.isConnected = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f CONNECTED.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; } })();
/**! * LibreMoney DgsListing api 0.2 * Copyright (c) LibreMoney Team <libremoney@yandex.com> * CC0 license */ /* import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONStreamAware; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_DESCRIPTION; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_NAME; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_TAGS; import static nxt.http.JSONResponses.MISSING_NAME; */ //super(new APITag[] {APITag.DGS, APITag.CREATE_TRANSACTION}, "name", "description", "tags", "quantity", "priceNQT"); function DgsListing(req, res) { res.send('This is not implemented'); /* String name = Convert.emptyToNull(req.getParameter("name")); String description = Convert.nullToEmpty(req.getParameter("description")); String tags = Convert.nullToEmpty(req.getParameter("tags")); long priceNQT = ParameterParser.getPriceNQT(req); int quantity = ParameterParser.getGoodsQuantity(req); if (name == null) { return MISSING_NAME; } name = name.trim(); if (name.length() > Constants.MAX_DGS_LISTING_NAME_LENGTH) { return INCORRECT_DGS_LISTING_NAME; } if (description.length() > Constants.MAX_DGS_LISTING_DESCRIPTION_LENGTH) { return INCORRECT_DGS_LISTING_DESCRIPTION; } if (tags.length() > Constants.MAX_DGS_LISTING_TAGS_LENGTH) { return INCORRECT_DGS_LISTING_TAGS; } Account account = ParameterParser.getSenderAccount(req); Attachment attachment = new Attachment.DigitalGoodsListing(name, description, tags, quantity, priceNQT); return createTransaction(req, account, attachment); */ } module.exports = DgsListing;
import Timeouts from 'platform/testing/e2e/timeouts'; class Confirmation { validatePageLoaded = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); }; validatePageContent = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); cy.get("[data-testid='confirmation-wrapper']"); cy.get("p[data-testid='appointment-day-location']"); cy.get("[data-testid='appointment-list']"); cy.get("h3[data-testid='appointment-questions']") .should('be.visible') .and('have.text', 'What if I have questions about my appointment?'); }; validateConfirmWithUpdates = () => { cy.get("[data-testid='confirmation-update-alert']") .should('be.visible') .and( 'have.text', 'A staff member will help you on the day of your appointment to update your information.', ); }; validateConfirmNoUpdates = () => { cy.get("[data-testid='confirmation-update-alert']").should('not.exist'); }; } export default new Confirmation();
/* ========================================================================== Shallow Extends Copyright (c) 2014 Alexey Maslennikov ========================================================================== */ 'use strict'; /** * @param {object} JavaScript object. * @returns {boolean} True if object is plain Javascript object. */ function _isPlainObject( object ) { return toString.call( object ) === '[object Object]'; } /** * Copies properties of all sources to the destination object overriding its own * existing properties. When extending from multiple sources, fields of every * next source will override same named fields of previous sources. * * @param {object} destination object. * @returns {bbject} extended destination object. */ function extend( destination ) { destination = destination || {}; for ( var i = 1; i < arguments.length; i++ ) { var source = arguments[i] || {}; for ( var key in source ) { if ( source.hasOwnProperty( key ) ) { var value = source[key]; if ( _isPlainObject( value ) ) { extend( destination[key] = {}, value ); }else { destination[key] = source[key]; } } } } return destination; } // Expose public methods. module.exports = { extend: extend };
import React from "react" import { Link, graphql } from "gatsby" import Bio from "../components/bio" import Layout from "../components/layout" import SEO from "../components/seo" import { rhythm } from "../utils/typography" class BlogIndex extends React.Component { render() { const { data } = this.props const siteTitle = data.site.siteMetadata.title const posts = data.allMarkdownRemark.edges return ( <Layout location={this.props.location} title={siteTitle}> <SEO title="All posts" keywords={[`blog`, `gatsby`, `javascript`, `react`]} /> <Bio /> {posts.map(({ node }) => { const title = node.frontmatter.title || node.fields.slug; var desc = node.frontmatter.excerpt || node.frontmatter.description; if (!desc || desc.length === 0) { desc = node.excerpt; } return ( <div key={node.fields.slug}> <h3 style={{ marginBottom: rhythm(1 / 4), }} > <Link style={{ boxShadow: `none` }} to={node.fields.slug}> {title} </Link> </h3> <small>{node.frontmatter.date}</small> <p dangerouslySetInnerHTML={{ __html: desc }} /> </div> ) })} </Layout> ) } } export default BlogIndex export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { edges { node { excerpt fields { slug } frontmatter { date(formatString: "MMMM DD, YYYY") title description excerpt } } } } } `
(function($) { $.Redactor.opts.langs['uk'] = { html: 'Код', video: 'Відео', image: 'Зображення', table: 'Таблиця', link: 'Посилання', link_insert: 'Вставити посилання ...', link_edit: 'Edit link', unlink: 'Видалити посилання', formatting: 'Стилі', paragraph: 'Звичайний текст', quote: 'Цитата', code: 'Код', header1: 'Заголовок 1', header2: 'Заголовок 2', header3: 'Заголовок 3', header4: 'Заголовок 4', header5: 'Заголовок 5', bold: 'Жирний', italic: 'Похилий', fontcolor: 'Колір тексту', backcolor: 'Заливка тексту', unorderedlist: 'Звичайний список', orderedlist: 'Нумерований список', outdent: 'Зменшити відступ', indent: 'Збільшити відступ', cancel: 'Скасувати', insert: 'Вставити', save: 'Зберегти', _delete: 'Видалити', insert_table: 'Вставити таблицю', insert_row_above: 'Додати рядок зверху', insert_row_below: 'Додати рядок знизу', insert_column_left: 'Додати стовпець ліворуч', insert_column_right: 'Додати стовпець праворуч', delete_column: 'Видалити стовпець', delete_row: 'Видалити рядок', delete_table: 'Видалити таблицю', rows: 'Рядки', columns: 'Стовпці', add_head: 'Додати заголовок', delete_head: 'Видалити заголовок', title: 'Підказка', image_view: 'Завантажити зображення', image_position: 'Обтікання текстом', none: 'ні', left: 'ліворуч', right: 'праворуч', image_web_link: 'Посилання на зображення', text: 'Текст', mailto: 'Ел. пошта', web: 'URL', video_html_code: 'Код відео ролика', file: 'Файл', upload: 'Завантажити', download: 'Завантажити', choose: 'Вибрати', or_choose: 'Або виберіть', drop_file_here: 'Перетягніть файл сюди', align_left: 'По лівому краю', align_center: 'По центру', align_right: 'По правому краю', align_justify: 'Вирівняти текст по ширині', horizontalrule: 'Горизонтальная лінійка', fullscreen: 'На весь екран', deleted: 'Закреслений', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline', alignment: 'Alignment', filename: 'Name (optional)', edit: 'Edit', center: 'Center' }; })(jQuery);
module.exports = function(context) { const fs = require('fs'); const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'); let projectRoot = cordova_util.isCordova(); let configXML = cordova_util.projectConfig(projectRoot); let data = fs.readFileSync(configXML, 'utf8'); for (var envVar in process.env) { data = data.replace('$' + envVar, process.env[envVar]); } fs.writeFileSync(configXML, data, 'utf8'); };
// Copyright © 2014 John Watson // Licensed under the terms of the MIT License var GameState = function(game) { }; // Load images and sounds GameState.prototype.preload = function() { this.game.load.image('ground', 'assets/gfx/ground.png'); this.game.load.image('player', 'assets/gfx/player.png'); }; // Setup the example GameState.prototype.create = function() { // Set stage background to something sky colored this.game.stage.backgroundColor = 0x4488cc; // Define movement constants this.MAX_SPEED = 500; // pixels/second // Create a player sprite this.player = this.game.add.sprite(this.game.width/2, this.game.height - 64, 'player'); // Enable physics on the player this.game.physics.enable(this.player, Phaser.Physics.ARCADE); // Make player collide with world boundaries so he doesn't leave the stage this.player.body.collideWorldBounds = true; // Capture certain keys to prevent their default actions in the browser. // This is only necessary because this is an HTML5 game. Games on other // platforms may not need code like this. this.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.UP, Phaser.Keyboard.DOWN ]); // Create some ground for the player to walk on this.ground = this.game.add.group(); for(var x = 0; x < this.game.width; x += 32) { // Add the ground blocks, enable physics on each, make them immovable var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground'); this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE); groundBlock.body.immovable = true; groundBlock.body.allowGravity = false; this.ground.add(groundBlock); } }; // The update() method is called every frame GameState.prototype.update = function() { // Collide the player with the ground this.game.physics.arcade.collide(this.player, this.ground); if (this.leftInputIsActive()) { // If the LEFT key is down, set the player velocity to move left this.player.body.velocity.x = -this.MAX_SPEED; } else if (this.rightInputIsActive()) { // If the RIGHT key is down, set the player velocity to move right this.player.body.velocity.x = this.MAX_SPEED; } else { // Stop the player from moving horizontally this.player.body.velocity.x = 0; } }; // This function should return true when the player activates the "go left" control // In this case, either holding the right arrow or tapping or clicking on the left // side of the screen. GameState.prototype.leftInputIsActive = function() { var isActive = false; isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT); isActive |= (this.game.input.activePointer.isDown && this.game.input.activePointer.x < this.game.width/4); return isActive; }; // This function should return true when the player activates the "go right" control // In this case, either holding the right arrow or tapping or clicking on the right // side of the screen. GameState.prototype.rightInputIsActive = function() { var isActive = false; isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT); isActive |= (this.game.input.activePointer.isDown && this.game.input.activePointer.x > this.game.width/2 + this.game.width/4); return isActive; }; var game = new Phaser.Game(640, 320, Phaser.AUTO, 'game'); game.state.add('game', GameState, true);
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var game = new Phaser.Game(config); function preload () { this.load.image('bunny', 'assets/sprites/bunny.png'); this.load.atlas('gems', 'assets/tests/columns/gems.png', 'assets/tests/columns/gems.json'); } function create () { delta = this.add.text(32, 32); time = this.add.text(500, 400); image = this.add.image(0, 200, 'bunny'); this.anims.create({ key: 'diamond', frames: this.anims.generateFrameNames('gems', { prefix: 'diamond_', end: 15, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'prism', frames: this.anims.generateFrameNames('gems', { prefix: 'prism_', end: 6, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'ruby', frames: this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'square', frames: this.anims.generateFrameNames('gems', { prefix: 'square_', end: 14, zeroPad: 4 }), repeat: -1 }); this.add.sprite(400, 100, 'gems').play('diamond'); this.add.sprite(400, 200, 'gems').play('prism'); this.add.sprite(400, 300, 'gems').play('ruby'); this.add.sprite(400, 400, 'gems').play('square'); } function update (timestep, dt) { image.x += speed * dt; if (image.x > 1000) { image.x = 0; } time.setText('time: ' + this.sys.game.loop.time.toString()); delta.setText(this.sys.game.loop.deltaHistory); }
/********************************************************** * Common JS function calls. * * Copyright © 2001-2007 E-Blah. * * Part of the E-Blah Software. Released under the GPL. * * Last Update: September 17, 2007 * **********************************************************/ // AJAX: developer.apple.com/internet/webcontent/xmlhttpreq.html var req; function EditMessage(url,saveopen,savemessage,messageid) { EditMessage2(url,saveopen,savemessage); function EditMessage2(url,saveopen,savemessage,messageid) { req = false; if(window.XMLHttpRequest) { // Non IE browsers try { req = new XMLHttpRequest(encoding="utf-8"); } catch(e) { req = false; } } else if(window.ActiveXObject) { // IE try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } } } if(req) { req.onreadystatechange = processReqChange; req.open("POST", url, true); // Use POST so we don't get CACHED items! if(saveopen == 1) { req.send("message="+encodeURIComponent(savemessage)); } else if(saveopen == 2) { req.send(savemessage); } else { req.send('TEMP'); } } else { alert('There was an error loading this page.'); } } function processReqChange() { if(req.readyState != 4) { document.getElementById(messageid).innerHTML = '<div class="loading">&nbsp;</div>'; } if(req.readyState == 4) { if (req.status == 200) { document.getElementById(messageid).innerHTML = req.responseText; } else { alert('There was an error loading this page.'); } } } } // Let's do some menus ... // Some code based from: www.quirksmode.org/js/findpos.html function findPosX(obj) { var curleft = 0; if(obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft obj = obj.offsetParent; } } else if(obj.x) curleft += obj.x; return curleft; } function findPosY(obj,plussize) { var curtop = plussize; if(navigator.userAgent.indexOf("Firefox") != -1) { curtop = (curtop/2); } if(navigator.userAgent.indexOf("IE") != -1) { curtop = (curtop+12); } if(obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop obj = obj.offsetParent; } } else if(obj.y) curtop += obj.y; return curtop; } // Creating Menus ... function CreateMenus(obj,plussize,JSinput) { var newX = findPosX(obj); var newY = findPosY(obj,plussize); var x = document.getElementById('menu-eblah'); x.style.top = newY + 'px'; x.style.left = newX + 'px'; document.getElementById('menu-eblah').innerHTML = ConstructLinks(JSinput); document.getElementById('menu-eblah').style.visibility = ''; } function ClearMenu() { document.getElementById('menu-eblah').innerHTML = ''; document.getElementById('menu-eblah').style.visibility = 'hidden'; } function ConstructLinks(JSinput) { GetLinks(JSinput); var link = ''; for(x in MenuItems) { link += '<div style="padding: 5px;" class="win3">' + MenuItems[x] + '</div>'; } return(link); } // Image Resize; from Martin's Mod for E-Blah function resizeImg() { var _resizeWidth = 750; var ResizeMsg = 'Click to view original size ...'; var _resizeClass = 'imgcode'; var imgArray = document.getElementsByTagName('img'); for(var i = 0; i < imgArray.length; i++) { var imgObj = imgArray[i]; if(imgObj.className == _resizeClass && imgObj.width > _resizeWidth) { imgObj.style.width = _resizeWidth + 'px'; imgObj.onclick = ImagecodeWinOpen; imgObj.title = ResizeMsg; imgObj.style.cursor = 'pointer'; } } } function ImagecodeWinOpen(e) { var img = (e)?e.target.src:window.event.srcElement.src; var w = window.open('','IMG','titlebar,scrollbars,resizable'); if (w) { w.document.write('<html><body><div align="center"><a href="#" onclick="window.close(); return false"><img src="'+img+'"></a></div></body></html>'); w.document.close(); } } window.onload = resizeImg;
'use strict'; import BaseContentService from './BaseContentService.js'; import {Question} from 'common/models.js'; import {Injector} from 'kusema.js'; var I = new Injector('$http', '$q'); var QuestionService = function() { BaseContentService.call(this, true); I.init(); this.urlStem = 'api/questions'; } QuestionService.prototype = Object.create(BaseContentService.prototype, { model: {writable: false, enumerable: false, value: Question} }); QuestionService.prototype.getNextTenQuestions = function (requestNumber, group) { var groupURL = (group) ? ('/'+group) : ''; return I.$http.get(this.urlBase + '/tenMore' + groupURL + '/' + requestNumber) .then(function(response) { return this.createClientModels(response.data); }.bind(this)); }; QuestionService.prototype.getFeed = function(requestNumber, group) { var groupURL = (group) ? (group+'/') : ''; return I.$http.get(this.urlBase+'/feed/'+groupURL+requestNumber) .then( (response) => { if (response.status == 204) { return I.$q.reject(new Error('No more questions')); } return this.createClientModels(response.data) } ); } import kusema from 'kusema.js'; kusema.service('questionService', QuestionService);
/** A modal view for handling user logins @class LoginView @extends Discourse.ModalBodyView @namespace Discourse @module Discourse **/ Discourse.LoginView = Discourse.ModalBodyView.extend({ templateName: 'modal/login', siteBinding: 'Discourse.site', title: Em.String.i18n('login.title'), authenticate: null, loggingIn: false, showView: function(view) { return this.get('controller').show(view); }, newAccount: function() { return this.showView(Discourse.CreateAccountView.create()); }, forgotPassword: function() { return this.showView(Discourse.ForgotPasswordView.create()); }, loginButtonText: (function() { if (this.get('loggingIn')) { return Em.String.i18n('login.logging_in'); } return Em.String.i18n('login.title'); }).property('loggingIn'), loginDisabled: (function() { if (this.get('loggingIn')) { return true; } if (this.blank('loginName') || this.blank('loginPassword')) { return true; } return false; }).property('loginName', 'loginPassword', 'loggingIn'), login: function() { var _this = this; this.set('loggingIn', true); $.post("/session", { login: this.get('loginName'), password: this.get('loginPassword') }).success(function(result) { if (result.error) { _this.set('loggingIn', false); if( result.reason === 'not_activated' ) { return _this.showView(Discourse.NotActivatedView.create({username: _this.get('loginName'), sentTo: result.sent_to_email, currentEmail: result.current_email})); } _this.flash(result.error, 'error'); } else { return window.location.reload(); } }).fail(function(result) { _this.flash(Em.String.i18n('login.error'), 'error'); return _this.set('loggingIn', false); }); return false; }, authMessage: (function() { if (this.blank('authenticate')) { return ""; } return Em.String.i18n("login." + (this.get('authenticate')) + ".message"); }).property('authenticate'), twitterLogin: function() { var left, top; this.set('authenticate', 'twitter'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/twitter", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, facebookLogin: function() { var left, top; this.set('authenticate', 'facebook'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/facebook", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, openidLogin: function(provider) { var left, top; left = this.get('lastX') - 400; top = this.get('lastY') - 200; if (provider === "yahoo") { this.set("authenticate", 'yahoo'); return window.open("/auth/yahoo", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); } else { window.open("/auth/google", "_blank", "menubar=no,status=no,height=500,width=850,left=" + left + ",top=" + top); return this.set("authenticate", 'google'); } }, githubLogin: function() { var left, top; this.set('authenticate', 'github'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/github", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, personaLogin: function() { navigator.id.request(); }, authenticationComplete: function(options) { if (options.awaiting_approval) { this.flash(Em.String.i18n('login.awaiting_approval'), 'success'); this.set('authenticate', null); return; } if (options.awaiting_activation) { this.flash(Em.String.i18n('login.awaiting_confirmation'), 'success'); this.set('authenticate', null); return; } // Reload the page if we're authenticated if (options.authenticated) { window.location.reload(); return; } return this.showView(Discourse.CreateAccountView.create({ accountEmail: options.email, accountUsername: options.username, accountName: options.name, authOptions: Em.Object.create(options) })); }, mouseMove: function(e) { this.set('lastX', e.screenX); return this.set('lastY', e.screenY); }, didInsertElement: function(e) { var _this = this; return Em.run.next(function() { return $('#login-account-password').keydown(function(e) { if (e.keyCode === 13) { return _this.login(); } }); }); } });
/* global Package, Npm */ Package.describe({ name: 'procempa:keycloak-auth', version: '1.0.0', summary: 'Meteor Keycloak Handshake flow', git: 'https://github.com/Procempa/meteor-keycloak-auth.git', documentation: 'README.md' }); Package.onUse(function(api) { api.use('ecmascript@0.1.4'); api.use('service-configuration@1.0.1'); api.export('KeycloakServer', 'server'); api.export('KeycloakClient', 'client'); api.mainModule('client-main.js', 'client'); api.mainModule('server-main.js', 'server'); }); Npm.depends({ 'lodash': '4.16.1', 'fallbackjs': '1.1.8', 'localforage': '1.4.2', 'keycloak-auth-utils': '2.2.1', 'babel-plugin-transform-decorators-legacy': '1.3.4', 'babel-plugin-transform-class-properties': '6.11.5', 'babel-plugin-transform-strict-mode': '6.11.3', 'q': '1.4.1' });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery-ui-1.9.2.js //= require jquery_ujs //= require jquery_mods //= require jquery.mobile.custom.js //= require jquery.waypoints.js //= require bootstrap //= require bootstrap-notify.js //= require notify.js //= require intro.js //= require modern-business/modern-business.js //= require cocoon //= require smart_listing //= require highcharts/highcharts.js //= require highcharts/highcharts-more.js //= require highcharts/highcharts-3d.js //= require startup.js //= require scrollspy.js //= require typeahead.bundle.js //= require charts.js //= require reports.js //= require stats.js //= require users.js //= require dashboard.js //= require ls_reports.js //= require ls_reports_filter.js //= require ls_reports_graph.js //= require ls_reports_spreadsheet.js //= require_tree ./assignments //= require sync_triggers.js //= require dataTables/dataTables.js //= require dataTables/extensions/TableTools/js/dataTables.tableTools.js //= require sessions.js //= require animations.js //= require form-utils.js //= require select2 //= require simplemde/simplemde.min.js
import { computed, toRefs } from '@vue/composition-api' export const useInputValueToggleProps = { label: { type: String }, options: { type: Array, default: () => ([ { value: 0 }, { value: 1, color: 'var(--primary)' } ]) }, hints: { type: Array } } export const useInputValueToggle = (valueProps, props, context) => { const { value: rxValue, onInput: rxOnInput } = valueProps const { options } = toRefs(props) // middleware const txValue = computed(() => options.value.findIndex(map => { if (!map.value && !rxValue.value) return true // compare False(y) w/ [null|undefined] else return `${map.value}` === `${rxValue.value}` // compare String(s) })) const txOnInput = value => { const { 0: { value: defaultValue } = {}, // 0th option is default [value]: { value: mappedValue } = {}, // map value (N) w/ Nth option [value]: { promise: mappedPromise } = {} // map promise } = options.value const rxValue = (mappedValue !== undefined) ? mappedValue : defaultValue if (mappedPromise) // handle Promise return mappedPromise(rxValue, props, context) else // otherwise emit return rxOnInput(rxValue) } // state const max = computed(() => `${options.value.length - 1}`) const label = computed(() => { const { 0: { label: defaultLabel } = {} , [txValue.value]: { label: mappedLabel } = {} } = options.value return mappedLabel || defaultLabel }) const color = computed(() => { const { 0: { color: defaultColor } = {} , [txValue.value]: { color: mappedColor } = {} } = options.value return mappedColor || defaultColor }) const icon = computed(() => { const { 0: { icon: defaultIcon } = {} , [txValue.value]: { icon: mappedIcon } = {} } = options.value return mappedIcon || defaultIcon }) const tooltip = computed(() => { const { 0: { tooltip: defaultTooltip } = {} , [txValue.value]: { tooltip: mappedTooltip } = {} } = options.value return mappedTooltip || defaultTooltip }) return { // middleware value: txValue, onInput: txOnInput, // state max, label, color, icon, tooltip } }
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = require('../../model/engine'); var util = require('../../lib/util'); module.exports = function(face, rootPath) { face.post('/api/register', bodyParser.json(), bodyParser.urlencoded(), register); face.get('/groups/:token', function(req, res) { res.sendFile(rootPath + 'assets/static/groups.html'); }); face.get('/api/groups/:token', function(req, res) { Account.getByToken(req.params.token).then(function(account) { return Engine.get(account.eid); }).then(function(engine) { var e = chip.getEngine(engine.sid); // I dunno what's going on here, but sometimes this gets weird e.loadGroups().then(function() { res.json({ synd: e.synd, groups: e.groups }); }); }); }); face.route('/api/group/:gid') .get(getGroup) .post(bodyParser.json(), bodyParser.urlencoded(), updateGroup, getGroup); face.put('/api/group', createGroup); }; function register(req, res) { return Syndicate.getByName(req.body.synd).then(function(synd) { if (synd) { return Engine.getBySynd(synd.sid).then(function(engine) { if (engine) { res.json({ error: 'Syndicate already registered' }); } else { var e = Engine.create({ sid: synd.sid }); var token = Math.random().toString(36).slice(2); return e.save().then(function() { return chip.db.queryAsync('INSERT INTO account SET ?', { email: req.body.email, eid: e.eid, token: token }); }).then(function(result) { chip.addEngine(e); res.json({ token: token }); }); } }); } else { res.json({ error: 'Syndicate not found' }); } }) }; function getGroup(req, res) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); res.json(g); }) } function createGroup(req, res) { var g = Group.create({ sid: req.body.sid, groupme_id: req.body.groupme_id, bot_key: req.body.bot_key, output: req.body.output == 'true', scout: req.body.scout == 'true', debug: req.body.debug == 'true' }); return g.save().then(function() { req.params.gid = g.gid; chip.addGroup(g); res.json(g); }); } function updateGroup(req, res, next) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); if (g) chip.removeGroup(g.groupme_id); else g = group; g.groupme_id = req.body.groupme_id; g.bot_key = req.body.bot_key; g.bot_id = null; g.output = req.body.output == 'true'; g.scout = req.body.scout == 'true'; g.debug = req.body.debug == 'true'; return g.save().then(function() { delete g.bot_id; g.getEngine().loadGroups().then(function() { res.json(g); }); }); }); } passport.use(new LocalStrategy( function(key, password, done) { //chip.db.queryAsync( /* connection.query("SELECT * FROM player p WHERE sid IS NOT NULL AND name='"+username+"'", function(err, result) { if (err) throw err; if (result.length > 0 && password == 'oredic37') { var player = User.createPlayer(result[0]); done(null, player); } else { done(null, null, { message: 'Invalid login' }); } }); */ }) ); passport.serializeUser(function(player, done) { done(null, player.pid); }); passport.deserializeUser(function(pid, done) { User.getUser(pid).then(function(user) { done(null, user); }); }); function loggedIn(req, res, next) { if (req.isAuthenticated()) { next(); } else { req.session.loginRedirect = req.url; res.redirect('/'); } }
module.exports = { user : 'Your Github Username', cal : 'Google calendar id to update' };
/** * Util of json ajax. * author: firstboy * require: jquery */ function Jsoncallback(url, callback, method, data, loadid) { if (loadid) $('#'+loadid).fadeIn(200); $.ajax({ type: method, data: data, scriptCharset: 'UTF-8', dataType: 'json', url: url, success: function(json) { if (loadid) $('#'+loadid).fadeOut(200); callback(json); }, error: function(json, textStatus, errorThrown) { if (loadid) $('#'+loadid).fadeOut(200); alert('[ERROR] -- JSON CALLBACK:\n' + '[ERROR:textStatus]: ' + textStatus + '[ERROR:errorThrown]: ' + errorThrown + '[ERROR:json.responseText]: ' + json.responseText); } }); } function getURLParameter(name) { return decodeURI( (RegExp(name + "=" + "(.+?)(&|$)").exec(location.search)||[,null])[1] ); } function addslashes(string) { return string.replace(/\\/g, '\\\\'). replace(/\u0008/g, '\\b'). replace(/\t/g, '\\t'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/'/g, '\\\''). replace(/"/g, '\\"'); } function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); } function ltrim(str){ return str.replace(/(^\s*)/g,""); } function rtrim(str){ return str.replace(/(\s*$)/g,""); }
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), DS = "/"; var settings = { port: 8080, indexFile: "index.html", folder: { serverside: "serverside", clientside: "clientside", static: "static_server", admin: "admin" } }; var paths = {}; paths.origin = process.cwd(); paths.base = paths.origin.slice(0, -1 * settings.folder.serverside.length - 1); paths.clientside = paths.base + DS + settings.folder.clientside; paths.serverside = paths.base + DS + settings.folder.serverside; paths.static = paths.base + DS + settings.folder.serverside + DS + settings.folder.static; clientside_exists = false; path.exists(paths.clientside, function(exists) { clientside_exists = exists; }); var static_server = http.createServer(function(request, response) { var uri = url.parse(request.url).pathname, filename; var DS_admin = DS + settings.folder.admin + DS; if (uri.slice(0, DS_admin.length) === DS_admin) { filename = path.join(paths.static, uri); } else if (clientside_exists) { filename = path.join(paths.clientside, uri); } else { filename = path.join(paths.origin, uri); } fs.exists(filename, function(exists) { if (!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } if (fs.statSync(filename).isDirectory()) { var indexFound = false; var rawlist = fs.readdirSync(filename); var filelist = []; rawlist.forEach(function(element) { if (!fs.statSync(path.join(filename, element)).isDirectory() && !indexFound) { if (element === settings.indexFile) { indexFound = true; } else { filelist.push(element); } } }); if (filelist.length > 0 && !indexFound) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(JSON.stringify(filelist)); response.end(); return; } filename = path.join(filename, settings.indexFile); } fs.readFile(filename, "binary", function(err, file) { if (err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file, "binary"); response.end(); }); }); }); static_server.listen(parseInt(settings.port, 10)); module.exports = static_server;
/*global gdn, jQuery*/ jQuery(($) => { const $preview = $('<div class="Preview"></div>') .insertBefore('#ConversationForm .bodybox-wrap, #Form_ConversationMessage .bodybox-wrap') .hide(); const $textbox = $('#ConversationForm textarea[name="Body"], #Form_ConversationMessage textarea[name="Body"]'); $('<a class="Button PreviewButton">' + gdn.getMeta('conversationsPreview.preview') + '</a>') .insertBefore('#ConversationForm input[type="submit"], #Form_ConversationMessage input[type="submit"]') .click(({target}) => { const $this = $(target); if ($this.hasClass('WriteButton')) { $preview.hide(); $textbox.show(); $this .addClass('PreviewButton') .removeClass('WriteButton') .text(gdn.getMeta('conversationsPreview.preview')); return; } gdn.disable($this); $this.toggleClass('PreviewButton').toggleClass('WriteButton'); $.post( gdn.url('messages/preview'), { Body: $this.closest('form').find('textarea[name="Body"]').val(), Format: $this.closest('form').find('input[name="Format"]').val(), TransientKey: gdn.definition('TransientKey') }, (data) => { $preview.html(data).show(); $textbox.hide(); $this .addClass('WriteButton') .removeClass('PreviewButton') .text(gdn.getMeta('conversationsPreview.edit')); $(document).trigger('PreviewLoaded'); }, 'html' ).always(() => { gdn.enable($this); }); }); $(document).on('MessageAdded', () => { $('.WriteButton').click(); }); });
/** * Copyright 2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public * License as published by the Free Software Foundation; either version * 2 of the License (GPLv2) or (at your option) any later version. * There is NO WARRANTY for this software, express or implied, * including the implied warranties of MERCHANTABILITY, * NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should * have received a copy of GPLv2 along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. **/ describe('Controller: ContentViewVersionsController', function() { var $scope beforeEach(module('Bastion.content-views', 'Bastion.test-mocks')); beforeEach(inject(function($injector) { var $controller = $injector.get('$controller'), ContentView = $injector.get('MockResource').$new(), translate = function (string) { return string; }; $scope = $injector.get('$rootScope').$new(); $scope.contentView = ContentView.get({id: 1}); $scope.reloadVersions = function () {}; $scope.taskTypes = { promotion: "promotion", publish: "publish" }; spyOn($scope, 'reloadVersions'); $controller('ContentViewVersionsController', { $scope: $scope, translate: translate }); })); it("puts an empty table object on the scope", function() { expect($scope.table).toBeDefined(); }); it("correctly hide a version's progress", function() { var version = {active_history: [], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(false); version = {active_history: [], task: {state: 'stopped', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'stopped', progressbar: {type: 'error'}}}; expect($scope.hideProgress(version)).toBe(false); }); it("determines what history text to display", function() { var version = {active_history: [], last_event: {environment: {name: 'test'}, task: {label: $scope.taskTypes.promotion} }}; expect($scope.historyText(version)).toBe("Promoted to test"); version.last_event.task.label = $scope.taskTypes.publish; expect($scope.historyText(version)).toBe("Published"); }); });
var Class = { create: function() { return function() { //vararg this.initialize.apply(this, arguments); } } }; Color = Class.create(); Color.prototype = { red: 0, green: 0, blue: 0, initialize: function(r,g,b) { this.red = r; this.green = g; this.blue = b; } } function bench(x) { var d = new Date; var colors = new Array(16); for (var i=0;i<1e8;i++) { colors[i&0xf] = (new Color(1,2,3)); } print(new Date - d); return colors; } bench(17); print("Swapping out call"); Function.prototype.call = function() { throw "This should not happen, apply should be called instead"; }; bench(17); print("All done!");
// IT lang variables tinyMCE.addToLang('',{ bold_desc : 'Grassetto (Ctrl+B)', italic_desc : 'Corsivo (Ctrl+I)', underline_desc : 'Sottolineato (Ctrl+U)', striketrough_desc : 'Barrato', justifyleft_desc : 'Allinea a sinistra', justifycenter_desc : 'Allinea al centro', justifyright_desc : 'Allinea a destra', justifyfull_desc : 'Giustifica', bullist_desc : 'Elenco puntato', numlist_desc : 'Elenco numerato', outdent_desc : 'Riduci rientro', indent_desc : 'Aumenta rientro', undo_desc : 'Annulla (Ctrl+Z)', redo_desc : 'Ripeti (Ctrl+Y)', link_desc : 'Inserisci o modifica link', unlink_desc : 'Elimina link', image_desc : 'Inserisci o modifica immagine', cleanup_desc : 'Pulisci il codice HTML', focus_alert : 'Fare clic su un\' istanza dell\'editor prima di eseguire questo comando', edit_confirm : 'Vuoi usare l\'editor visuale in quest\'area di testo?', insert_link_title : 'Inserisci o modifica link', insert : 'Inserisci', update : 'Modifica', cancel : 'Annulla', insert_link_url : 'URL del collegamento', insert_link_target : 'Destinazione', insert_link_target_same : 'Apri il link nella stessa finestra', insert_link_target_blank : 'Apri il link in una nuova finestra', insert_image_title : 'Inserisci o modifica immagine', insert_image_src : 'URL dell\'immagine', insert_image_alt : 'Descrizione', help_desc : 'Aiuto', bold_img : "bold.gif", italic_img : "italic.gif", underline_img : "underline.gif", clipboard_msg : 'Le operazioni di taglia, copia e incolla non sono disponibili in Firefox. Vuoi ricevere ulteriori informazioni al riguardo?', popup_blocked : 'Un blocco popup sta impedendo l\'utilizzo di alcune funzionalit&agrave;. Dovresti disabilitare il blocco per questo sito.', insert_image_delta_width : 50, insert_link_delta_width : 75 });
"use strict"; var assert = require("assert"), Promise = require("promise"), _ = require("underscore"), configController = require('../controllers/configController.js'); describe('configController', function() { it('init should load the config file', function(done) { configController.init(function(err) { assert(!err); assert(configController.initialized); assert(configController.config); assert(_.isString(configController.config.host)); assert(_.isNumber(configController.config.port)); assert(_.isNumber(configController.config.internalPort)); assert(_.isNumber(configController.config.redisPort)); assert(_.isArray(configController.config.admins)); assert(_.isString(configController.config.amaraKey)); assert(_.isString(configController.config.emailService)); assert(_.isString(configController.config.smtpUser)); assert(_.isString(configController.config.smtpPass)); assert(_.isString(configController.config.emailFrom)); }); done(); }); });
/* * jQuery.liveFilter * * Copyright (c) 2009 Mike Merritt * * Forked by Lim Chee Aun (cheeaun.com) * */ (function($){ $.fn.liveFilter = function(inputEl, filterEl, options){ var defaults = { filterChildSelector: null, filter: function(el, val){ return $(el).text().toUpperCase().indexOf(val.toUpperCase()) >= 0; }, before: function(){}, after: function(){} }; var options = $.extend(defaults, options); var el = $(this).find(filterEl); if (options.filterChildSelector) el = el.find(options.filterChildSelector); var filter = options.filter; $(inputEl).keyup(function(){ var val = $(this).val(); var contains = el.filter(function(){ return filter(this, val); }); var containsNot = el.not(contains); if (options.filterChildSelector){ contains = contains.parents(filterEl); containsNot = containsNot.parents(filterEl).hide(); } options.before.call(this, contains, containsNot); contains.show(); containsNot.hide(); if (val === '') { contains.show(); containsNot.show(); } options.after.call(this, contains, containsNot); }); } })(jQuery);
http://jsfiddle.net/fusioncharts/38U6R/ http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Chart/Data-Labels/Configuring-x-axis-data-labels-display---wrap-mode_466/
var path = require('path'); var ndir = require('ndir'); var express = require('express'); var MongoStore = require('connect-mongo')(express); var ejs = require('ejs'); var routes = require('./routes'); var config = require('./config').config; var adminFilter = require('./filter/adminFilter'); var businessFilter = require('./filter/businessFilter'); var home = require('./controllers/open/home'); var maxAge = 3600000 * 24 * 30; var staticDir = path.join(__dirname, 'assets'); // 静态文件存放更目录. config.upload_temp_dir = config.upload_temp_dir || path.join(__dirname, 'assets', 'user_data'); // ensure upload dir exists ndir.mkdir(config.upload_temp_dir, function(err) { // 建立上传文件目录 if (err) { throw err; } }); config.upload_img_dir = config.upload_img_dir || path.join(__dirname, 'assets', 'user_data', 'images'); ndir.mkdir(config.upload_img_dir, function(err) { // 建立上传文件目录 if (err) { throw err; } }); var app = express(); // all environments app.configure(function() { app.set('title', 'Zero App'); app.set('port', 80); app.set('env', 'production'); ejs.open = '{{'; ejs.close = '}}'; app.engine('.html', ejs.__express); app.set('view engine', 'html'); app.set('views', path.join(__dirname, 'views')); // html 文件存放目录 app.use(express.cookieParser()); require('./model'); var mongoose = require('mongoose'); app.use(express.session({ secret: config.session_secret, store: new MongoStore({ mongooseConnection: mongoose.connection }), cookie: { maxAge: 3600000 } })); // --- 设置中间件 --- app.use(express.favicon(path.join(__dirname, 'assets/img/favicon.ico'))); app.use('/assets', express.static(staticDir)); app.use(express.logger('dev')); app.use('/admin', adminFilter.userNeeded); app.use('/business', businessFilter.bserNeeded); app.use('/', home.init); app.use(express.bodyParser({ uploadDir: config.upload_temp_dir })); app.use(express.methodOverride()); // 配置路由 routes(app); }) // development only app.configure('development', function() { app.use(express.errorHandler()); }) // production only app.configure('production', function() { //FIXME: // app.use(function(err, req, res, next) { // console.error(err.stack); // res.redirect('/500'); // }); }); app.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); });
// Catch Flames Custom Scripts jQuery(document).ready(function() { /* Waypoint */ if ( jQuery.isFunction( jQuery.fn.waypoint ) ) { var waypointheader = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'down' ) { jQuery('#header-top').addClass( 'fixed-header' ); } else { jQuery('#header-top').removeClass( 'fixed-header' ); } }, offset: -50 }) var waypointtoup = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'up' ) { jQuery('#scrollup').fadeOut(); } else { jQuery('#scrollup').fadeIn(); } }, offset: -500 }) } jQuery('#scrollup').click(function () { jQuery('body,html').animate({ scrollTop: 1 }, 800); return false; }); /* Social */ jQuery( '#header-social-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-social' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); /* Search */ jQuery( '#header-search-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-search' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); //sidr if ( jQuery.isFunction( jQuery.fn.sidr ) ) { jQuery('#fixed-header-menu').sidr({ name: 'mobile-top-nav', side: 'left' // By default }); jQuery('#header-left-menu').sidr({ name: 'mobile-header-left-nav', side: 'left' // By default }); } });
/** * Express configuration */ 'use strict'; import express from 'express'; import favicon from 'serve-favicon'; import morgan from 'morgan'; import compression from 'compression'; import bodyParser from 'body-parser'; import methodOverride from 'method-override'; import cookieParser from 'cookie-parser'; import errorHandler from 'errorhandler'; import path from 'path'; import lusca from 'lusca'; import config from './environment'; import passport from 'passport'; import session from 'express-session'; import connectMongo from 'connect-mongo'; import mongoose from 'mongoose'; var MongoStore = connectMongo(session); export default function(app) { var env = app.get('env'); if (env === 'development' || env === 'test') { app.use(express.static(path.join(config.root, '.tmp'))); } if (env === 'production') { app.use(favicon(path.join(config.root, 'client', 'favicon.ico'))); } app.set('appPath', path.join(config.root, 'client')); app.use(express.static(app.get('appPath'))); app.use(morgan('dev')); app.set('views', `${config.root}/server/views`); app.set('view engine', 'jade'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); app.use(passport.initialize()); // Persist sessions with MongoStore / sequelizeStore // We need to enable sessions for passport-twitter because it's an // oauth 1.0 strategy, and Lusca depends on sessions app.use(session({ secret: config.secrets.session, saveUninitialized: true, resave: false, store: new MongoStore({ mongooseConnection: mongoose.connection, db: 'eecr' }) })); /** * Lusca - express server security * https://github.com/krakenjs/lusca */ if (env !== 'test' && !process.env.SAUCE_USERNAME) { app.use(lusca({ csrf: { angular: true }, xframe: 'SAMEORIGIN', hsts: { maxAge: 31536000, //1 year, in seconds includeSubDomains: true, preload: true }, xssProtection: true })); } if ('development' === env) { const webpackDevMiddleware = require('webpack-dev-middleware'); const stripAnsi = require('strip-ansi'); const webpack = require('webpack'); const makeWebpackConfig = require('../../webpack.make'); const webpackConfig = makeWebpackConfig({ DEV: true }); const compiler = webpack(webpackConfig); const browserSync = require('browser-sync').create(); /** * Run Browsersync and use middleware for Hot Module Replacement */ browserSync.init({ open: false, logFileChanges: false, proxy: 'localhost:' + config.port, ws: true, middleware: [ webpackDevMiddleware(compiler, { noInfo: false, stats: { colors: true, timings: true, chunks: false } }) ], port: config.browserSyncPort, plugins: ['bs-fullscreen-message'] }); /** * Reload all devices when bundle is complete * or send a fullscreen error message to the browser instead */ compiler.plugin('done', function(stats) { console.log('webpack done hook'); if (stats.hasErrors() || stats.hasWarnings()) { return browserSync.sockets.emit('fullscreen:message', { title: 'Webpack Error:', body: stripAnsi(stats.toString()), timeout: 100000 }); } browserSync.reload(); }); } if (env === 'development' || env === 'test') { app.use(errorHandler()); // Error handler - has to be last } }
// ============================================================================= // Module to configure an ExpressJS web server // ============================================================================= // Requires // { // "express": "4.13.3", // "cookie-parser": "1.4.0", // "morgan": "1.6.1", // "body-parser" : "1.14.1", // "express-session" : "1.12.1", // "method-override" : "2.3.5" // } var express = require('express'); var cookieParser = require('cookie-parser'); var methodOverride = require('method-override'); var http = require('http'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var app = express(); app.use(morgan('dev')); // log every request to the console app.use(cookieParser()); // read cookies (needed for auth) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); module.exports = { app : app }
var gulp = require("gulp"), concat = require("gulp-concat"), karma = require("karma").server, mocha = require("gulp-mocha"), nodemon = require("gulp-nodemon"), notify = require("gulp-notify"), size = require("gulp-filesize"), sourcemaps = require("gulp-sourcemaps"), uglify = require("gulp-uglify"), typescript = require("gulp-tsc"); gulp.task("default", function () { gulp.start("server"); gulp.start("watch"); }); gulp.task("watch", function () { gulp.watch("assets/js/**/*.ts", ["typescript-client"]); gulp.watch("assets/dist/js/*.js", ["test-client", "client"]); }); gulp.task("client", function () { gulp.src([ "bower_components/jquery/dist/jquery.min.js", "bower_components/lodash/lodash.min.js", "bower_components/rxjs/dist/rx.all.min.js", "bower_components/Rx-jQuery/rx.jquery.js", "assets/dist/js/lib.js" ]) .pipe(sourcemaps.init()) .pipe(concat("app.js")) .pipe(sourcemaps.write()) .pipe(gulp.dest("assets/dist/js")) .pipe(notify("app.js successfully compiled")) .pipe(size()); }); gulp.task("server", function () { nodemon({ script: "app/boot.js", ext: "ts html", ignore: ["assets/**/*", "README"], env: {"NODE_ENV": "development"}, tasks: ["typescript", "test"] }).on("restart", function () { //console.log("Server restarted!"); }); }); gulp.task("typescript-client", function () { tsc("assets/js", "assets/dist/js", "client"); tscClientTest("assets/js"); }); gulp.task("typescript", function () { tsc("app", "app", "server"); }); gulp.task("test-client", function (done) { karma.start({ configFile: process.cwd() + "/assets/js/test/karma.conf.js" }, done); }); gulp.task("test", function () { return gulp.src("app/**/*.spec.js", {read: false}) .pipe(mocha({reporter: "list"})); }); function tsc(path, out, type) { var src = gulp.src([ path + "/**/*.ts", // Ignore specs and typings "!" + path + "/**/*.spec.ts", "!" + path + "/typings/**/*" ], {base: path}); var dest; if (type == "client") { dest = src.pipe(typescript({ target: "ES5", sortOutput: true, sourceMap: false, removeComments: true })) .pipe(concat("lib.js")); //.pipe(uglify()); } else { dest = src.pipe(typescript( { target: "ES5", sourcemap: true, declarationFiles: true, removeComments: true } )); } dest .pipe(gulp.dest(out)) .pipe(notify(path + " tsc compiled into JavaScript")) .pipe(size()); } function tscClientTest(path) { var src = gulp.src([ path + "/**/*.spec.ts" ], {base: path}); src.pipe(typescript({ target: "ES5", sortOutput: true, sourceMap: false, removeComments: true })) .pipe(concat("all.js")) .pipe(gulp.dest(path + "/test")) .pipe(notify(path + " tscTest compiled into JavaScript")) .pipe(size()); }
var events = new Hash(); function showEvent( eid, fid, width, height ) { var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; createPopup( url, 'zmEvent', 'event', width, height ); } function createEventHtml( event, frame ) { var eventHtml = new Element( 'div' ); if ( event.Archived > 0 ) eventHtml.addClass( 'archived' ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', monitorNames[event.MonitorId] ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Name+(frame?("("+frame.FrameId+")"):"") ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.StartTime+" - "+event.Length+"s" ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Cause ); if ( event.Notes ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Notes ); if ( event.Archived > 0 ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', archivedString ); return( eventHtml ); } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var event = respObj.event; if ( !event ) { console.log( "Null event" ); return; } events[event.Id] = event; if ( respObj.loopback ) { requestFrameData( event.Id, respObj.loopback ); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log( "Null frame" ); return; } var event = events[frame.EventId]; if ( !event ) { console.error( "No event "+frame.eventId+" found" ); return; } if ( !event['frames'] ) event['frames'] = new Hash(); event['frames'][frame.FrameId] = frame; event['frames'][frame.FrameId]['html'] = createEventHtml( event, frame ); showEventDetail( event['frames'][frame.FrameId]['html'] ); loadEventImage( frame.Image.imagePath, event.Id, frame.FrameId, event.Width, event.Height ); } var eventQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse } ); var frameQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse } ); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent( eventId, frameId ) { if ( events[eventId] ) { if ( events[eventId]['frames'] ) { if ( events[eventId]['frames'][frameId] ) { showEventDetail( events[eventId]['frames'][frameId]['html'] ); loadEventImage( events[eventId].frames[frameId].Image.imagePath, eventId, frameId, events[eventId].Width, events[eventId].Height ); return; } } } requestFrameData( eventId, frameId ); } function loadEventImage( imagePath, eid, fid, width, height ) { var imageSrc = $('imageSrc'); imageSrc.setProperty( 'src', imagePrefix+imagePath ); imageSrc.removeEvent( 'click' ); imageSrc.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); var eventData = $('eventData'); eventData.removeEvent( 'click' ); eventData.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); } function tlZoomBounds( minTime, maxTime ) { console.log( "Zooming" ); window.location = '?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime; } function tlZoomRange( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; } function tlPan( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; }
(function() { /* constructor */ function PhotoFloat() { this.albumCache = []; } /* public member functions */ PhotoFloat.prototype.album = function(subalbum, callback, error) { var cacheKey, ajaxOptions, self; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) { callback(subalbum); return; } if (Object.prototype.toString.call(subalbum).slice(8, -1) === "String") cacheKey = subalbum; else cacheKey = PhotoFloat.cachePath(subalbum.parent.path + "/" + subalbum.path); if (this.albumCache.hasOwnProperty(cacheKey)) { callback(this.albumCache[cacheKey]); return; } self = this; ajaxOptions = { type: "GET", dataType: "json", url: "cache/" + cacheKey + ".json", success: function(album) { var i; for (i = 0; i < album.albums.length; ++i) album.albums[i].parent = album; for (i = 0; i < album.photos.length; ++i) album.photos[i].parent = album; self.albumCache[cacheKey] = album; callback(album); } }; if (typeof error !== "undefined" && error !== null) { ajaxOptions.error = function(jqXHR, textStatus, errorThrown) { error(jqXHR.status); }; } $.ajax(ajaxOptions); }; PhotoFloat.prototype.albumPhoto = function(subalbum, callback, error) { var nextAlbum, self; self = this; nextAlbum = function(album) { //var index = Math.floor(Math.random() * (album.photos.length + album.albums.length)); if (1==1 && album.main != null && album.main != "") { var index = 0; for (index = 0; index < album.photos.length; ++index) { if (PhotoFloat.cachePath(album.photos[index].name) === PhotoFloat.cachePath(album.main)) { break; } } callback(album, album.photos[index]); } else{ var index = 0; if (album.photos.length > 0) { index = album.photos.length - 1; } if (index >= album.photos.length) { index -= album.photos.length; self.album(album.albums[index], nextAlbum, error); } else callback(album, album.photos[index]); } }; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) nextAlbum(subalbum); else this.album(subalbum, nextAlbum, error); }; PhotoFloat.prototype.parseHash = function(hash, callback, error) { var index, album, photo; hash = PhotoFloat.cleanHash(hash); index = hash.lastIndexOf("/"); if (!hash.length) { album = PhotoFloat.cachePath("root"); photo = null; } else if (index !== -1 && index !== hash.length - 1) { photo = hash.substring(index + 1); album = hash.substring(0, index); } else { album = hash; photo = null; } this.album(album, function(theAlbum) { var i = -1; if (photo !== null) { for (i = 0; i < theAlbum.photos.length; ++i) { if (PhotoFloat.cachePath(theAlbum.photos[i].name) === photo) { photo = theAlbum.photos[i]; break; } } if (i >= theAlbum.photos.length) { photo = null; i = -1; } } callback(theAlbum, photo, i); }, error); }; PhotoFloat.prototype.authenticate = function(password, result) { $.ajax({ type: "GET", dataType: "text", url: "auth?username=photos&password=" + password, success: function() { result(true); }, error: function() { result(false); } }); }; /* static functions */ PhotoFloat.cachePath = function(path) { if (path === "") return "root"; if (path.charAt(0) === "/") path = path.substring(1); path = path .replace(/ /g, "_") .replace(/\//g, "-") .replace(/\(/g, "") .replace(/\)/g, "") .replace(/#/g, "") .replace(/&/g, "") .replace(/,/g, "") .replace(/\[/g, "") .replace(/\]/g, "") .replace(/"/g, "") .replace(/'/g, "") .replace(/_-_/g, "-") .toLowerCase(); while (path.indexOf("--") !== -1) path = path.replace(/--/g, "-"); while (path.indexOf("__") !== -1) path = path.replace(/__/g, "_"); return path; }; PhotoFloat.photoHash = function(album, photo) { return PhotoFloat.albumHash(album) + "/" + PhotoFloat.cachePath(photo.name); }; PhotoFloat.albumHash = function(album) { if (typeof album.photos !== "undefined" && album.photos !== null) return PhotoFloat.cachePath(album.path); return PhotoFloat.cachePath(album.parent.path + "/" + album.path); }; PhotoFloat.photoPath = function(album, photo, size, square) { var suffix; if (square) suffix = size.toString() + "s"; else suffix = size.toString(); return "cache/" + PhotoFloat.cachePath(PhotoFloat.photoHash(album, photo) + "_" + suffix + ".jpg"); }; PhotoFloat.originalPhotoPath = function(album, photo) { return "albums/" + album.path + "/" + photo.name; }; PhotoFloat.trimExtension = function(name) { var index = name.lastIndexOf("."); if (index !== -1) return name.substring(0, index); return name; }; PhotoFloat.cleanHash = function(hash) { while (hash.length) { if (hash.charAt(0) === "#") hash = hash.substring(1); else if (hash.charAt(0) === "!") hash = hash.substring(1); else if (hash.charAt(0) === "/") hash = hash.substring(1); else if (hash.substring(0, 3) === "%21") hash = hash.substring(3); else if (hash.charAt(hash.length - 1) === "/") hash = hash.substring(0, hash.length - 1); else break; } return hash; }; /* make static methods callable as member functions */ PhotoFloat.prototype.cachePath = PhotoFloat.cachePath; PhotoFloat.prototype.photoHash = PhotoFloat.photoHash; PhotoFloat.prototype.albumHash = PhotoFloat.albumHash; PhotoFloat.prototype.photoPath = PhotoFloat.photoPath; PhotoFloat.prototype.originalPhotoPath = PhotoFloat.originalPhotoPath; PhotoFloat.prototype.trimExtension = PhotoFloat.trimExtension; PhotoFloat.prototype.cleanHash = PhotoFloat.cleanHash; /* expose class globally */ window.PhotoFloat = PhotoFloat; }());
;(function($){ $(document).ready( function(){ $('.fa_slider_simple').FeaturedArticles({ slide_selector : '.fa_slide', nav_prev : '.go-back', nav_next : '.go-forward', nav_elem : '.main-nav .fa-nav', effect : false, // events load : load, before : before, after : after, resize : resize, stop : stop, start : start }); }); var resizeDuration = 100; var load = function(){ var options = this.settings(), self = this; this.progressBar = $(this).find('.progress-bar'); this.mouseOver; // height resize if( $(this).data('theme_opt_auto_resize') ){ this.sliderHeight = $(this).height(); var h = $( this.slides()[0] ).find(options.content_container).outerHeight() + 100; setHeight = h > this.sliderHeight ? h : this.sliderHeight; slide = this.slides()[0]; $(slide).css({ 'height' : setHeight }); self.center_img( slide ); $(this) .css({ 'max-height':'none', 'height' : this.sliderHeight }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ /* $(this).css({ 'max-height':setHeight }); */ } });// end animate }// end height resize } var before = function(d){ var options = this.settings(), self = this; if( typeof this.progressBar !== 'undefined' ){ this.progressBar.stop().css({'width':0}); } // height resize if( $(this).data('theme_opt_auto_resize') ){ var h = $( d.next ).find(options.content_container).outerHeight() + 100, setHeight = h > this.sliderHeight ? h : this.sliderHeight; $(d.next).css({ height : setHeight }); self.center_img( d.next ); $(this) .css({ 'max-height':'none' }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ $(this).css({'max-height':setHeight}); } });// end animate } // end height resize } var resize = function(){ var self = this, options = this.settings(); // height resize if( $(this).data('theme_opt_auto_resize') ){ var h = $( this.get_current() ).find(options.content_container).outerHeight() + 100; this.sliderHeight = $(this).height();; var setHeight = h > this.sliderHeight ? h : this.sliderHeight; $( this.get_current() ).css({ height: setHeight }); self.center_img( self.get_current() ); $(this) .css({ 'max-height':'none', 'height':this.sliderHeight }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ $(this).css({'max-height':setHeight}); } }); } // end height resize } var after = function(){ var options = this.settings(), self = this, duration = options.slide_duration; //self.center_current_img(); if( this.mouseOver || this.stopped || !options.auto_slide ){ return; } if( typeof this.progressBar !== 'undefined' ){ this.progressBar.css({width:0}).animate( {'width' : '100%'}, {duration: duration, queue:false, complete: function(){ $(this).css({'width':0}); } }); } } var stop = function(){ if( typeof this.progressBar !== 'undefined' ){ this.progressBar.stop().css({'width':0}); } this.mouseOver = true; } var start = function(){ this.mouseOver = false; if( this.animating() ){ return; } var options = this.settings(), duration = options.slide_duration; if( typeof this.progressBar !== 'undefined' ){ this.progressBar.css({width:0}).animate( {'width' : '100%'}, {duration: duration, queue:false, complete: function(){ $(this).css({'width':0}); } }); } } })(jQuery);
/* The main program of test panel */ requirejs.config({ paths : { "dualless" : ".." }, baseUrl : ".." }); require(["debug/view/component", "debug/view/information", "dualless/directives/winbutton" ], function app(component, information, winbutton){ var module = angular.module('main', []); module.config(['$routeProvider', function configRouteProvider($routeProvider) { $routeProvider.when('/info', information); //$routeProvider.when('/component', component); $routeProvider.when('/preparetest', {templateUrl: "view/preparetest.html"}); $routeProvider.otherwise({redirectTo : "/info" }) }]); module.directive('winbutton',winbutton); $(document).ready(function() { angular.bootstrap(document,["main"]); }); });
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ YUI.add('ez-dashboardview', function (Y) { "use strict"; /** * Provides the Dashboard View class * * @module ez-dashboardview */ Y.namespace('eZ'); /** * The dashboard view * * @namespace eZ * @class DashboardView * @constructor * @extends eZ.TemplateBasedView */ Y.eZ.DashboardView = Y.Base.create('dashboardView', Y.eZ.TemplateBasedView, [Y.eZ.HeightFit], { initializer: function () { this.after('activeChange', this._setIFrameSource); }, /** * Renders the dashboard view * * @method render * @return {eZ.DashboardView} the view itself */ render: function () { this.get('container').setHTML(this.template()); this._attachedViewEvents.push(Y.on("windowresize", Y.bind(this._uiSetHeight, this, 0))); return this; }, /** * Sets the source of the iframe to the value of the iframeSource attribute. * * @method _setIFrameSource * @private */ _setIFrameSource: function () { this.get('container').one('.ez-dashboard-content').set('src', this.get('iframeSource')); } }, { ATTRS: { /** * Stores the iframe Source * * @attribute iframeSource * @type String * @default 'http://ez.no/in-product/eZ-Platform' * @readOnly */ iframeSource: { value: '//ez.no/in-product/eZ-Platform', readOnly: true, }, }, }); });
window.addEvent("domready", function() { var carousel = new iCarousel("carousel_content", { idPrevious: "carousel_prev", idNext: "carousel_next", idToggle: "undefined", item: { klass: "carouselitem_right", size: 265 }, animation: { type: "scroll", duration: 700, amount: 1 } }); $$('.carousel_header a').each(function (el,index){ el.addEvent("click", function(event){ new Event(event).stop(); carousel.goTo(index); $$('.carousel_header a').removeClass('active'); $('carousel_link'+index).addClass('active'); }); }); });
// closure to avoid namespace collision (function(){ //------- var html_form = '<div id="text_box-form">\ <p class="popup_submit_wrap"><span class="wpp_helper_box"><a onclick="open_win(\'http://www.youtube.com/watch?v=Y_7snOfYato&list=PLI8Gq0WzVWvJ60avoe8rMyfoV5qZr3Atm&index=10\')">Видео урок</a></span><input type="button" id="text_box_submit" class="button-primary" value="Вставить" name="submit" /></p>\ <div class="ps_text_box_form coach_box">\ <div>\ <label class="ps_text_box wppage_checkbox ps_text_box_1"><input type="radio" name="text_box_style" value="1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_1_1"><input type="radio" name="text_box_style" value="1_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_2"><input type="radio" name="text_box_style" value="2" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_2_1"><input type="radio" name="text_box_style" value="2_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_3"><input type="radio" name="text_box_style" value="3" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_3_1"><input type="radio" name="text_box_style" value="3_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_4"><input type="radio" name="text_box_style" value="4" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_4_1"><input type="radio" name="text_box_style" value="4_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_5"><input type="radio" name="text_box_style" value="5" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_5_1"><input type="radio" name="text_box_style" value="5_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_6"><input type="radio" name="text_box_style" value="6" /></label>\ </div>\ </div></div>'; //------- // creates the plugin tinymce.create('tinymce.plugins.textbox', { // creates control instances based on the control's id. // our button's id is "smartresponder_button" createControl : function(id, controlManager) { if (id == 'text_box_button') { // creates the button var button = controlManager.createButton('text_box_button', { title : 'Боксы', // title of the button image : plugin_url+'/wppage/i/box.png', // path to the button's image onclick : function() { // triggers the thickbox tb_show( 'Боксы', '#TB_inline?inlineId=text_box-form' ); jQuery('#TB_ajaxContent').css({'width': '640', 'height': (jQuery('#TB_window').height()-50)+'px'}); jQuery(window).resize(function(){ jQuery('#TB_ajaxContent').css({'width': '640', 'height': (jQuery('#TB_window').height()-50)+'px'}); }); } }); return button; } return null; } }); // registers the plugin. DON'T MISS THIS STEP!!! tinymce.PluginManager.add('textbox', tinymce.plugins.textbox); // executes this when the DOM is ready jQuery(function(){ // creates a form to be displayed everytime the button is clicked // you should achieve this using AJAX instead of direct html code like this var form = jQuery(html_form); form.appendTo('body').hide(); // handles the click event of the submit button form.find('#text_box_submit').click(function(){ // defines the options and their default values // again, this is not the most elegant way to do this // but well, this gets the job done nonetheless var options = { 'id' : '' }; var text_box_style = jQuery('input[name=text_box_style]:checked').val(); var shortcode = '<p class="aligncenter"><div class="ps_text_box ps_text_box_'+text_box_style+'"><p class="ps_text_box_text">Текст</p></div></p><p>&nbsp;</p>'; // inserts the shortcode into the active editor tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode); // closes Thickbox tb_remove(); }); }); })()
/** * Lists the number of different characters */ /* global document: true, Node: true, window: true */ exports.version = '1.0'; exports.module = function(phantomas) { 'use strict'; //phantomas.setMetric('differentCharacters'); // @desc the number of different characters in the body @offenders phantomas.on('report', function() { phantomas.log("charactersCount: starting to analyze characters on page..."); phantomas.evaluate(function() { (function(phantomas) { phantomas.spyEnabled(false, 'analyzing characters on page'); function getLetterCount(arr){ return arr.reduce(function(prev, next){ prev[next] = 1; return prev; }, {}); } if (document.body && document.body.textContent) { var allText = ''; // Traverse all DOM Tree to read text var runner = new phantomas.nodeRunner(); runner.walk(document.body, function(node, depth) { switch (node.nodeType) { // Grabing text nodes case Node.TEXT_NODE: if (node.parentNode.tagName !== 'SCRIPT' && node.parentNode.tagName !== 'STYLE') { allText += node.nodeValue; } break; // Grabing CSS content properties case Node.ELEMENT_NODE: if (node.tagName !== 'SCRIPT' && node.tagName !== 'STYLE') { allText += window.getComputedStyle(node).getPropertyValue('content'); allText += window.getComputedStyle(node, ':before').getPropertyValue('content'); allText += window.getComputedStyle(node, ':after').getPropertyValue('content'); } break; } }); // Reduce all text found in page into a string of unique chars var charactersList = getLetterCount(allText.split('')); var charsetString = Object.keys(charactersList).sort().join(''); // Remove blank characters charsetString = charsetString.replace(/\s/g, ''); phantomas.setMetric('differentCharacters', charsetString.length); phantomas.addOffender('differentCharacters', charsetString); } phantomas.spyEnabled(true); }(window.__phantomas)); }); phantomas.log("charactersCount: analyzing characters done."); }); };
/* ************************************************************** #Inicia as funções e plugins * ***************************************************************/ (function() { // Ativa o menu mobile app.menu(); // Ativa o slideshow, se presente na página. var slideshow = document.getElementById("slider"); if(slideshow) { window.mySwipe = new Swipe(slideshow, { speed: 400, auto: 4000, continuous: false, callback: function(){ // Ativa os bullets de navegação do slideshow var i = mySwipe.getPos(), el = document.querySelectorAll("#slider > ul > li"); // Remove a classe ".is-active" de todos os bullets for(var x = 0; x < el.length; x++) { if(el[x].classList.contains("is-active")) { el[x].classList.remove("is-active"); } }; // Ativa a bullet correta el[i].classList.add("is-active"); } }); }; })();
'use strict'; function solve(args) { var $number = +args[0]; var $significantBit = $number => (($number >> 3) & 1); console.log($significantBit($number)); } solve(['15']); solve(['1024']);
{ "CMSMAIN.WARNINGSAVEPAGESBEFOREADDING" : "You have to save a page before adding children underneath it", "CMSMAIN.CANTADDCHILDREN" : "You can't add children to the selected node", "CMSMAIN.ERRORADDINGPAGE" : "Error adding page", "CMSMAIN.FILTEREDTREE" : "Filtered tree to only show changed pages", "CMSMAIN.ERRORFILTERPAGES" : "Could not filter tree to only show changed pages<br />%s", "CMSMAIN.ERRORUNFILTER" : "Unfiltered tree", "CMSMAIN.PUBLISHINGPAGES" : "Publishing pages...", "CMSMAIN.SELECTONEPAGE" : "Please select at least 1 page.", "CMSMAIN.ERRORPUBLISHING" : "Error publishing pages", "CMSMAIN.REALLYDELETEPAGES" : "Do you really want to delete the %s marked pages?", "CMSMAIN.DELETINGPAGES" : "Deleting pages...", "CMSMAIN.ERRORDELETINGPAGES": "Error deleting pages", "CMSMAIN.PUBLISHING" : "Publishing...", "CMSMAIN.RESTORING": "Restoring...", "CMSMAIN.ERRORREVERTING": "Error reverting to live content", "CMSMAIN.SAVING" : "saving...", "CMSMAIN.SELECTMOREPAGES" : "You have %s pages selected.\n\nDo you really want to perform this action?", "CMSMAIN.ALERTCLASSNAME": "The page type will be updated after the page is saved", "CMSMAIN.URLSEGMENTVALIDATION": "URLs can only be made up of letters, digits and hyphens.", "AssetAdmin.BATCHACTIONSDELETECONFIRM": "Do you really want to delete %s folders?", "AssetTableField.REALLYDELETE": "Do you really want to delete the marked files?", "AssetTableField.MOVING": "Moving %s file(s)", "CMSMAIN.AddSearchCriteria": "Add Criteria", "WidgetAreaEditor.TOOMANY": "Sorry, you have reached the maximum number of widgets in this area", "AssetAdmin.ConfirmDelete": "Do you really want to delete this folder and all contained files?", "Folder.Name": "Folder name", "Tree.AddSubPage": "Add new page here", "Tree.Duplicate": "Duplicate", "Tree.EditPage": "Edit", "Tree.ThisPageOnly": "This page only", "Tree.ThisPageAndSubpages": "This page and subpages", "Tree.ShowAsList": "Show children as list", "CMSMain.ConfirmRestoreFromLive": "Do you really want to copy the published content to the draft site?", "CMSMain.RollbackToVersion": "Do you really want to roll back to version #%s of this page?", "URLSEGMENT.Edit": "Edit", "URLSEGMENT.OK": "OK", "URLSEGMENT.Cancel": "Cancel", "URLSEGMENT.UpdateURL": "Update URL" }
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; }, isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get classes( ) { if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); } else { return null; } }, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
'use strict'; module.exports = require('./EuCookies');
/** * FitVids 1.1 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ */ !function(t){"use strict" t.fn.fitVids=function(e){var i={customSelector:null,ignore:null} if(!document.getElementById("fit-vids-style")){var r=document.head||document.getElementsByTagName("head")[0],a=".fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}",d=document.createElement("div") d.innerHTML='<p>x</p><style id="fit-vids-style">'+a+"</style>",r.appendChild(d.childNodes[1])}return e&&t.extend(i,e),this.each(function(){var e=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"] i.customSelector&&e.push(i.customSelector) var r=".fitvidsignore" i.ignore&&(r=r+", "+i.ignore) var a=t(this).find(e.join(",")) a=a.not("object object"),a=a.not(r),a.each(function(){var e=t(this) if(!(e.parents(r).length>0||"embed"===this.tagName.toLowerCase()&&e.parent("object").length||e.parent(".fluid-width-video-wrapper").length)){e.css("height")||e.css("width")||!isNaN(e.attr("height"))&&!isNaN(e.attr("width"))||(e.attr("height",9),e.attr("width",16)) var i="object"===this.tagName.toLowerCase()||e.attr("height")&&!isNaN(parseInt(e.attr("height"),10))?parseInt(e.attr("height"),10):e.height(),a=isNaN(parseInt(e.attr("width"),10))?e.width():parseInt(e.attr("width"),10),d=i/a if(!e.attr("id")){var o="fitvid"+Math.floor(999999*Math.random()) e.attr("id",o)}e.wrap('<div class="fluid-width-video-wrapper"></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*d+"%"),e.removeAttr("height").removeAttr("width")}})})}}(window.jQuery||window.Zepto)
import getNotes from './get-notes'; export const noteHasFilteredRead = ( noteState, noteId ) => noteState.filteredNoteReads.includes( noteId ); export default ( state, noteId ) => noteHasFilteredRead( getNotes( state ), noteId );
"use strict" var merge = require('merge'); var HttpError = require('http-errors'); var Path = require('path'); module.exports = BaseController.extend({ view: { file: '', partials: {}, params: {} }, before: function(next) { this.view.file = this.req.route; next(); }, after: function(next) { if(this.res.headersSent) { return true; } var params = this.view.params; params.partials = {}; // Parse route for partials set not by config for(var i in this.view.partials) { params.partials[i] = Path.join(this.req.route, this.view.partials[i]); } // Merge partials with configuration partials params.partials = merge(true, { _content: this.view.file }, this.config.partials, params.partials); // Test if the partials do exist to prevent hard-to-solve issues for(var i in params.partials) { try { require.resolve(Path.join(app.basedir, app.config.path.view, params.partials[i] + '.hjs')); } catch(e) { throw new HttpError(404, 'Partial ' + partials[i] + ' Not Found'); } } // Do the actial rendering this.res.render(this.config.layout, params); next(); }, init: function(req, res) { // Load specific settings for the WebController this.view = merge(true, this.view, {}); this.config = merge(true, this.config, app.config.web); this.parent(req, res); } });
(function( $ ) { 'use strict'; /** * All of the code for your admin-facing JavaScript source * should reside in this file. * * This enables you to define handlers, for when the DOM is ready: * * $(function() { * * }); * * When the window is loaded: * * $( window ).load(function() { * * }); */ $(function() { console.log("Hallo Welt"); }); })( jQuery );
(function($){ "use strict"; // wpb_el_type_position $('.wpb-element-edit-modal .ewf-position-box div').click(function(){ // e.preventDefault(); $(this).closest('.ewf-position-box').find('div').removeClass('active'); $(this).addClass('active'); console.log('execute param position shit!'); var value = 'none'; if ($(this).hasClass('ewf-pb-top')) { value = 'top'; } if ($(this).hasClass('ewf-pb-top-right')) { value = 'top-right'; } if ($(this).hasClass('ewf-pb-top-left')) { value = 'top-left'; } if ($(this).hasClass('ewf-pb-bottom')) { value = 'bottom'; } if ($(this).hasClass('ewf-pb-bottom-right')) { value = 'bottom-right'; } if ($(this).hasClass('ewf-pb-bottom-left')) { value = 'bottom-left'; } if ($(this).hasClass('ewf-pb-left')) { value = 'left'; } if ($(this).hasClass('ewf-pb-right')) { value = 'right'; } $(this).closest('.edit_form_line').find('input.wpb_vc_param_value').val(value); }); })(window.jQuery);
import React, { useContext, useEffect, Fragment } from "react" import { Typography } from "@material-ui/core" import EventsContext from "../context/EventsContext" import TitleContext from "../context/TitleContext" import Box from "@material-ui/core/Box" import Button from "@material-ui/core/Button" import FacebookIcon from '@material-ui/icons/Facebook'; import TwitterIcon from '@material-ui/icons/Twitter'; import FileCopyIcon from '@material-ui/icons/FileCopy'; import makeStyles from "@material-ui/core/styles/makeStyles" import { graphql, useStaticQuery } from "gatsby" const ucfirst = (string) => string[0].toUpperCase() + string.slice(1) const Sentence = () => { const useStyles = makeStyles(theme => ( { sentence: { fontSize: '1.8em', }, sharing: { fontFamily: 'Raleway,sans-serif', display: 'flex', justifyContent: 'space-between', margin: '0 auto', marginTop: '50px', maxWidth: '300px' }, button: { fontFamily: theme.typography.body1.fontFamily, fontWeight: 'bold', textTransform: 'none' } })) const classes = useStyles() const titleContext = useContext(TitleContext) const eventsContext = useContext(EventsContext) const { site } = useStaticQuery( graphql` query { site { siteMetadata { title description author url app_id } } } ` ) let testo = "" let sharingText = "" let url = site.siteMetadata.url if( typeof window !== 'undefined' ) { url = window.location.href } if (eventsContext.events.length === 0) { testo = "" } if (eventsContext.events.length === 1) { testo = eventsContext.events[0].precisediff + " ago: <br/>" + eventsContext.events[0].name sharingText = eventsContext.events[0].precisediff + " ago: " + eventsContext.events[0].name + " #closerintime" } if (eventsContext.events.length === 2) { let evento1 = eventsContext.events[0] let evento2 = eventsContext.events[1] let verb = parseInt(evento2.plural) ? " are " : " is " if (evento1.diff > evento2.diff) { testo = ucfirst(evento2.name) + verb + "closer in time to us than to " + evento1.name + "." sharingText = ucfirst(evento2.name) + verb + "#closerintime to us than to " + evento1.name + "." } else if (evento1.diff < evento2.diff) { testo = ucfirst(evento2.name) + verb + "closer in time to " + evento1.name + " than to us." sharingText = ucfirst(evento2.name) + verb + "#closerintime to " + evento1.name + " than to us." } else { testo = ucfirst(evento2.name) + verb + "exactly halfway between " + evento1.name + " and us." sharingText = ucfirst(evento2.name) + verb + "exactly halfway between " + evento1.name + " and us. #closerintime" } } if (eventsContext.events.length === 3) { let evento1 = eventsContext.events[0] let evento2 = eventsContext.events[1] let evento3 = eventsContext.events[2] if (evento1.diff > evento3.diff) { testo = "More time passed between " + evento1.name + " and " + evento2.name + " than between " + evento3.name + " and us." sharingText = "More time passed between " + evento1.name + " and " + evento2.name + " than between " + evento3.name + " and us. #closerintime" } else if (evento1.diff < evento3.diff) { testo = "More time passed between " + evento3.name + " and us than between " + evento1.name + " and " + evento2.name + "." sharingText = "More time passed between " + evento3.name + " and us than between " + evento1.name + " and " + evento2.name + ". #closerintime" } else { testo = "The same amount time passed between " + evento1.name + " and " + evento2.name + " as it did between " + evento3.name + " and us." sharingText = "The same amount time passed between " + evento1.name + " and " + evento2.name + " as it did between " + evento3.name + " and us. #closerintime" } } useEffect(() => { titleContext.setTitle(testo) }, [testo]) const copyToClipboard = (text, href) => { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text+' '+href; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); } return (<Fragment> <Typography className={classes.sentence} variant={"h1"} align={"center"} dangerouslySetInnerHTML={{ __html: testo }}></Typography> {(sharingText) && <Box className={classes.sharing} > <Button component={"a"} className={classes.button} target={"_blank"} href={"https://twitter.com/intent/tweet?text=" + encodeURIComponent(sharingText) + "&url=" + encodeURIComponent(url)} startIcon={<TwitterIcon/>}> Tweet </Button> <Button component={"a"} className={classes.button} target={"_blank"} href={"https://www.facebook.com/dialog/share?app_id=" + site.siteMetadata.app_id + "&href=" + encodeURIComponent(url) + "&quote=" + encodeURIComponent(sharingText) + "&hashtag=%23closerintime"} startIcon={<FacebookIcon/>}> Share </Button> <Button component={"a"} className={classes.button} onClick={() => copyToClipboard(sharingText,url)} startIcon={<FileCopyIcon/>}> Copy </Button> </Box>} </Fragment>) } export default Sentence
showWord(["n. ","Boutik, magazen, kote yo vann. Nan ri sa a, gen anpil konmès." ])
tinyMCE.addI18n("ru.len-slider",{ title : "Шорткод для вставки LenSlider" });
(function($){ if (typeof UxU.utils !== 'undefined') { $('.uxu-ticket-status-festival-length').html(UxU.utils.durationFromVisitors(info.tickets_sold)); } })(jQuery);
'use strict'; const { expect } = require('chai'); const { getParsedSql } = require('./util'); describe('common table expressions', () => { it('should support single CTE', () => { const sql = ` WITH cte AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.equal('WITH "cte" AS (SELECT 1) SELECT * FROM "cte"'); }); it('should support multiple CTE', () => { const expected = 'WITH "cte1" AS (SELECT 1), "cte2" AS (SELECT 2) ' + 'SELECT * FROM "cte1" UNION SELECT * FROM "cte2"'; const sql = ` WITH cte1 AS (SELECT 1), cte2 AS (SELECT 2) SELECT * FROM cte1 UNION SELECT * FROM cte2 `.trim(); expect(getParsedSql(sql)).to.equal(expected) }); it('should support CTE with column', () => { const sql = ` WITH cte (col1) AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1)'); }); it('should support CTE with multiple columns', () => { const sql = ` WITH cte (col1, col2) AS (SELECT 1, 2) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1, col2)'); }); it('should support recursive CTE', () => { const sql = ` WITH RECURSIVE cte(n) AS ( SELECT 1 UNION SELECT n + 1 FROM cte WHERE n < 5 ) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.match(/^WITH RECURSIVE/); }); });
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const StyledTag = styled.span` color: ${props => props.color}; background: ${props => props.bgcolor}; padding: ${props => props.padding}; margin: ${props => props.margin}; border-radius: 3px; border: ${props => `1px solid ${props.border}`}; max-width: ${props => props.maxWidth}; word-break: break-all; line-height: 20px; `; const Tag = ({ text, size = "medium", color = { bgcolor: "#fafafa", border: "#d9d9d9", color: "rgba(0,0,0,0.65)" }, margin = "", maxWidth = "300px" }) => { const getPaddingBySize = size => { const choices = { small: "0px 5px", medium: "1px 6px", large: "5px 10px" }; return choices[size]; }; return ( <StyledTag bgcolor={color.bgcolor} border={color.border} color={color.color} padding={getPaddingBySize(size)} margin={margin} maxWidth={maxWidth} > {text} </StyledTag> ); }; Tag.propTypes = { color: PropTypes.shape({ bgcolor: PropTypes.string, border: PropTypes.string, color: PropTypes.string }), text: PropTypes.string, size: PropTypes.string, margin: PropTypes.string, maxWidth: PropTypes.string }; export default Tag;
// ** I18N Calendar._DN = new Array ("Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"); Calendar._MN = new Array ("Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"); // tooltips Calendar._TT = {}; Calendar._TT["TOGGLE"] = "Skifta första veckodag"; Calendar._TT["PREV_YEAR"] = "Förra året (tryck för meny)"; Calendar._TT["PREV_MONTH"] = "Förra månaden (tryck för meny)"; Calendar._TT["GO_TODAY"] = "Gå till dagens datum"; Calendar._TT["NEXT_MONTH"] = "Nästa månad (tryck för meny)"; Calendar._TT["NEXT_YEAR"] = "Nästa år (tryck för meny)"; Calendar._TT["SEL_DATE"] = "Välj dag"; Calendar._TT["DRAG_TO_MOVE"] = "Flytta fönstret"; Calendar._TT["PART_TODAY"] = " (idag)"; Calendar._TT["MON_FIRST"] = "Visa Måndag först"; Calendar._TT["SUN_FIRST"] = "Visa Söndag först"; Calendar._TT["CLOSE"] = "Stäng fönstret"; Calendar._TT["TODAY"] = "Idag"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd"; Calendar._TT["TT_DATE_FORMAT"] = "DD, d MM y"; Calendar._TT["WK"] = "wk";
/* Malaysian initialisation for the jQuery UI date picker plugin. */ /* Written by Mohd Nawawi Mohamad Jamili (nawawi@ronggeng.net). */ jQuery(function ($) { $.datepicker.regional['ms'] = { closeText: 'Tutup', prevText: '&#x3c;Sebelum', nextText: 'Selepas&#x3e;', currentText: 'hari ini', monthNames: ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'], monthNamesShort: ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogo', 'Sep', 'Okt', 'Nov', 'Dis'], dayNames: ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'], dayNamesShort: ['Aha', 'Isn', 'Sel', 'Rab', 'kha', 'Jum', 'Sab'], dayNamesMin: ['Ah', 'Is', 'Se', 'Ra', 'Kh', 'Ju', 'Sa'], weekHeader: 'Mg', dateFormat: 'dd/mm/yy', firstDay: 0, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['ms']); });
/* * linksync commander -- Command line interface to LinkSync * Copyright (C) 2016 Andrew Duncan * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const crawler = require('simplecrawler').Crawler, fs = require('node-fs'), path = require('path'), q = require('q'), request = require('request'), url = require('url'), linklib = require('./links'), settings = require('./settings'); var self = module.exports = { crawler: new crawler(), init_crawler: function() { self.crawler.cache = new crawler.cache(settings.get('syncroot')); self.crawler.interval = 250; self.crawler.maxConcurrency = 5; self.crawler.userAgent = "LinkSync version " + settings.get('version'); self.crawler.maxDepth = 1; self.crawler.ignoreInvalidSSL = true; }, download_url: function(id, weburl, callback) { var mask = parseInt('0755', 8); var parsed_url = url.parse(weburl); var root_id = id; self.crawler = new crawler(parsed_url.hostname); self.init_crawler(); self.crawler.queueURL(weburl); self.crawler.on("fetchcomplete", function(queue_item, response_buffer, response) { console.log("Fetched: %s", queue_item.url); var parsed_url = url.parse(queue_item.url); if (parsed_url.pathname === "/") { parsed_url.pathname = "/index.html"; } var output_directory = path.join(settings.get('syncroot') + root_id + '/', parsed_url.hostname); var dirname = output_directory + parsed_url.pathname.replace(/\/[^\/]+$/, ""); var filepath = output_directory + parsed_url.pathname; console.log('%s : %s : %s', output_directory, dirname, filepath); fs.exists(dirname, function(exists) { if (exists) { fs.writeFile(filepath, response_buffer, function() {}); } else { fs.mkdir(dirname, mask, true, function() { fs.writeFile(filepath, response_buffer, function() {}); }); } }); console.log("%s (%d bytes) / %s", queue_item.url, response_buffer.length, response.headers["content-type"]); }); self.crawler.on("fetcherror", function(error) { console.log("Error syncing url (%s): %s", weburl, error); }); self.crawler.on("complete", function() { callback(); }); self.crawler.start(); }, sync: function(id) { linklib.get_link(id).then(function(link) { console.log('Syncing %s ...', link.url); self.download_url(id, link.url, function() { console.log("Finished syncing %s", link.url); }); }); } }
describe('autocomplete', function () { beforeEach(function () { browser.get('/bonita/preview/page/no-app-selected/autocomplete/'); }); describe('simple list', function() { var input, p; beforeEach(function() { input = $('.test-simple input'); p = $('.test-simple p'); }); it('should allow to pick a suggestion dropdownlist and update the value', function() { input.sendKeys('n'); var values = $$('.dropdown-menu a'); expect(values.count()).toBe(2); values.get(0).click(); expect(p.getText()).toContain('London'); }); }); describe('Object list', function() { var input, p; beforeEach(function() { input = $('.test-object input'); p = $('.test-object p'); }); it('should display the correct value', function() { expect(p.getText()).toContain('{ "name": "Paul" }'); expect(input.getAttribute('value')).toContain('Paul'); }); it('should display the correct suggestions', function() { input.clear().sendKeys('a'); var values = $$('.dropdown-menu a'); var labels = values.map(function(item) { return item.getText(); }); expect(values.count()).toBe(3); expect(labels).toEqual(['Paul', 'Hokusai', 'Pablo']); }); it('should update the value when select a suggestion', function() { input.clear().sendKeys('a'); var values = $$('.dropdown-menu a'); values.get(1).click(); expect(p.getText()).toContain('Hokusai'); }); }); const labels = () => { return $$('.dropdown-menu a') .map(function (item) { return item.getText(); }); }; describe('async', () => { // see https://bonitasoft.atlassian.net/browse/BS-16696 it('should display the right suggestions', () => { const input = $('.test-async input'); input.clear().sendKeys('walt'); expect(labels()).toEqual([ 'walter.bates' ]); input.sendKeys(protractor.Key.BACK_SPACE); expect(labels()).toEqual([ 'walter.bates', 'thomas.wallis' ]); }); it('should return the returned key of selection', () => { const input = $('.test-async-with-returnedKey input'); input.clear().sendKeys('walter'); var values = $$('.dropdown-menu a'); values.get(0).click(); var p = $('.test-async-with-returnedKey p'); expect(p.getText()).toContain('4'); }); it('should return the full selected object if there is no returned key', () => { const input = $('.test-async-without-returnedKey input'); input.clear().sendKeys('walter'); var values = $$('.dropdown-menu a'); values.get(0).click(); var p = $('.test-async-without-returnedKey p'); expect(p.getText()).toContain('walter.bates'); expect(p.getText()).toContain('4'); }); }); });
// config/ptv.js module.exports.ptv = { devId: 'xxx', devSecret: 'xxx', };
/** * Created by kliu on 10/10/2015. */ var jsonschema = require("jsonschema"); var utils = {}; utils.validateJSON = function(schema, json){ var result = jsonschema.validate(json, schema); if(result.errors.length == 0){ return json; }else{ throw new Error("message not valid, " + result.errors.join()); } }; utils.validateRawString = function(schema, message){ var self = this; var json = JSON.parse(message); return self.validateJSON(json, schema); }; /** * load and initial an object from specified path, and check the function exists in this object * @param filePath * @param checkFuncs * @constructor */ utils.loadAndCheck = function(filePath, checkFuncs){ var loadCls = require(filePath); var loadObj = new loadCls(); checkFuncs.forEach(function(checkFunc){ if (typeof(loadObj[checkFunc]) != "function") { throw new Error(filePath + " doesn't have " + checkFunc + "()") } }); return loadObj; }; module.exports = utils;
/* global Ext, ViewStateManager, App */ Ext.define( 'App.ux.StatefulTabPanel', { extend: 'Ext.tab.Panel', alias: 'widget.statefultabpanel', initComponent: function() { this.iconCls = this.iconCls || this.itemId; this.on( 'afterrender', this.onAfterRender, this); this.callParent( arguments); }, setActiveTab: function( tab, dontUpdateHistory) { this.callParent( arguments); if (!dontUpdateHistory) { ViewStateManager.change( tab.itemId); } }, addViewState: function( tab, path) { var i, item, newPath; for (i = 0; i < tab.items.length; i++) { item = tab.items.get( i); newPath = Ext.Array.clone( path); newPath.push( item); ViewStateManager.add( item.itemId, newPath); if (item instanceof App.ux.StatefulTabPanel) { this.addViewState( item, newPath); } } tab.viewStateDone = true; }, onAfterRender: function( tab) { if (!tab.viewStateDone) { if (tab.ownerCt instanceof App.ux.StatefulTabPanel) { tab = tab.ownerCt; } this.addViewState( tab, []); } } });
$(function(){ $('.home .bxslider').bxSlider({ auto: true, mode: 'fade' }); /** * QUICK REFERENCE */ // check if the window bindings should be applied (only if the element is present) var $reference = $('.reference-wrap'); if($reference.length > 0){ // toggle the menu $('.reference-wrap h3').click(function() { $('.reference-content').slideToggle(300); }); // scroll to the elements $('.reference-content a').click(function(){ $('.reference-content').slideToggle(300); var id = $(this).html(); $('html, body').animate({ scrollTop: $('#' + id).offset().top - 20 }, 300); return false; }); $(window).bind('scroll resize', positionQuickReference); } // check if .reference-wrap should be sticky function positionQuickReference(){ var windowTop = $(window).scrollTop(); if(windowTop >= 112){ $reference.css({ position: 'fixed', top: 20, right: $(window).width() > 700 ? $(window).width() - ($('#primary h1').offset().left + $('#primary').width()) : 20 }); }else{ $reference.css({ position: 'absolute', top: 0, right: $(window).width() > 1040 ? 0 : 20 }); } } /** * SIDEBAR */ $('.btn-donate').click(function() { $('#frm-paypal').submit(); return false; }); $('.block-signup form').submit(function() { var email = $('#mce-EMAIL').val(); if(!isValidEmailAddress(email)){ $('.block-signup .error').show(); return false; } }); }); function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; // (function(){ // var bsa = document.createElement('script'); // bsa.type = 'text/javascript'; // bsa.async = true; // bsa.src = '//s3.buysellads.com/ac/bsa.js'; // (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa); // })(); /** * Create a cookie */ function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }; /** * Get a cookie */ function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; };
var express = require('express'); var reload = require('reload'); var fs = require('fs'); var wss = new require('ws').Server({port: 3030}); var app = express(); var Chopper = require('./lib/Chopper'); app.set('port', process.env.PORT || 3000); app.set('view engine', 'ejs'); app.use(require('./routes/index')); app.use(require('./routes/visual')); app.use(require('./routes/d3')); app.use(require('./routes/control')); app.use(require('./routes/config')); app.use(require('./routes/api')); app.use('/jquery', express.static('./node_modules/jquery/dist')); app.use(express.static('./public')); // global vars for the EJS (Embedded JavaScript) framework app.locals.siteTitle = 'CS'; // Control Systems title var server = app.listen(app.get('port'), function () { console.log('Example app listening on port: ' + app.get('port') + '!'); }); reload(server, app); wss.on('connection', function (ws) { ws.send('Welcome to cyber chat'); ws.on('message', function (msg) { if (msg == 'exit') { ws.close(); } }) }); var chop = new Chopper(); chop.on('ready', function() { console.log('Chopper ready'); app.set('chopper', chop); }); chop.on('change', function(value) { wss.clients.forEach(function (ws, index, list) { ws.send(JSON.stringify(value)); }) }); chop.on('data', function(type, data) { fs.writeFile(type + Date.now() + '.csv', data, function (err) { console.log(`${type} data saved`); }); });
export { AbilityScoresViewModel } from './ability_scores'; export { ActionsToolbarViewModel } from './actions_toolbar'; export { ArmorViewModel } from './armor'; export { CharacterNameViewModel } from './character_name'; export { CharacterPortraitModel } from './character_portrait'; export { CharacterStatusLineViewModel } from './character_status_line'; export { BackgroundViewModel } from './background'; export { FeatsViewModel } from './feats'; export { FeaturesViewModel } from './features'; export { ItemsViewModel } from './items'; export { MagicItemsViewModel } from './magic_items'; export { ProficienciesViewModel } from './proficiencies'; export { ProfileViewModel } from './profile'; export { CharacterRootViewModel } from './root'; export { SkillsViewModel } from './skills'; export { SpellSlotsViewModel } from './spell_slots'; export { SpellStatsViewModel } from './spell_stats'; export { SpellbookViewModel } from './spells'; export { StatsViewModel } from './stats'; export { TrackerViewModel } from './tracker'; export { TraitsViewModel } from './traits'; export { WealthViewModel } from './wealth'; export { WeaponsViewModel } from './weapons'; export { OtherStatsViewModel } from './other_stats';
var index = require('express').Router(); var Member = require('../models/Member'); var sitemap = require('../middlewares/sitemap'); var utils = require('../middlewares/utils'); index.get('/', function (req, res) { res.redirect('/article'); }); index.get('/lang', function (req, res) { var setLang; if (req.cookies.lang == undefined || req.cookies.lang == 'zh-cn') { setLang = 'en-us'; } else { setLang = 'zh-cn'; } res.cookie('lang', setLang); res.redirect('/'); }); index.get('/lib/contact-us', function (req, res) { res.render('contactUs', { description: '身为工大学子的你,如果对软件开发或是产品设计有兴趣,欢迎向我们投递简历。' }); }); index.get('/lib/sitemap.xml', function (req, res) { sitemap.createXml(function (xml) { res.contentType('text/xml'); res.send(xml); res.end(); }); }); module.exports = index;
'use strict'; const Stack = require('./_Stack'); const baseIsEqual = require('./_baseIsEqual'); /** Used to compose bitmasks for comparison styles. */ const UNORDERED_COMPARE_FLAG = 1; const PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { let index = matchData.length; const length = index; const noCustomizer = !customizer; let data; if ((object === null || object === undefined)) { return !length; } object = Object(object); while (index--) { data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; const key = data[0]; const objValue = object[key]; const srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { const stack = new Stack(); let result; if (customizer) { result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch;
module.exports = publish var url = require('url') var semver = require('semver') var Stream = require('stream').Stream var assert = require('assert') var fixer = require('normalize-package-data').fixer var concat = require('concat-stream') var ssri = require('ssri') function escaped (name) { return name.replace('/', '%2f') } function publish (uri, params, cb) { assert(typeof uri === 'string', 'must pass registry URI to publish') assert(params && typeof params === 'object', 'must pass params to publish') assert(typeof cb === 'function', 'must pass callback to publish') var access = params.access assert( (!access) || ['public', 'restricted'].indexOf(access) !== -1, "if present, access level must be either 'public' or 'restricted'" ) var auth = params.auth assert(auth && typeof auth === 'object', 'must pass auth to publish') if (!(auth.token || (auth.password && auth.username && auth.email))) { var er = new Error('auth required for publishing') er.code = 'ENEEDAUTH' return cb(er) } var metadata = params.metadata assert( metadata && typeof metadata === 'object', 'must pass package metadata to publish' ) try { fixer.fixNameField(metadata, {strict: true, allowLegacyCase: true}) } catch (er) { return cb(er) } var version = semver.clean(metadata.version) if (!version) return cb(new Error('invalid semver: ' + metadata.version)) metadata.version = version var body = params.body assert(body, 'must pass package body to publish') assert(body instanceof Stream, 'package body passed to publish must be a stream') var client = this var sink = concat(function (tarbuffer) { putFirst.call(client, uri, metadata, tarbuffer, access, auth, cb) }) sink.on('error', cb) body.pipe(sink) } function putFirst (registry, data, tarbuffer, access, auth, cb) { // optimistically try to PUT all in one single atomic thing. // If 409, then GET and merge, try again. // If other error, then fail. var root = { _id: data.name, name: data.name, description: data.description, 'dist-tags': {}, versions: {}, readme: data.readme || '' } if (access) root.access = access if (!auth.token) { root.maintainers = [{ name: auth.username, email: auth.email }] data.maintainers = JSON.parse(JSON.stringify(root.maintainers)) } root.versions[ data.version ] = data var tag = data.tag || this.config.defaultTag root['dist-tags'][tag] = data.version var tbName = data.name + '-' + data.version + '.tgz' var tbURI = data.name + '/-/' + tbName var integrity = ssri.fromData(tarbuffer, { algorithms: ['sha1', 'sha512'] }) data._id = data.name + '@' + data.version data.dist = data.dist || {} // Don't bother having sha1 in the actual integrity field data.dist.integrity = integrity['sha512'][0].toString() // Legacy shasum support data.dist.shasum = integrity['sha1'][0].hexDigest() data.dist.tarball = url.resolve(registry, tbURI) .replace(/^https:\/\//, 'http://') root._attachments = {} root._attachments[ tbName ] = { 'content_type': 'application/octet-stream', 'data': tarbuffer.toString('base64'), 'length': tarbuffer.length } var fixed = url.resolve(registry, escaped(data.name)) var client = this var options = { method: 'PUT', body: root, auth: auth } this.request(fixed, options, function (er, parsed, json, res) { var r409 = 'must supply latest _rev to update existing package' var r409b = 'Document update conflict.' var conflict = res && res.statusCode === 409 if (parsed && (parsed.reason === r409 || parsed.reason === r409b)) { conflict = true } // a 409 is typical here. GET the data and merge in. if (er && !conflict) { client.log.error('publish', 'Failed PUT ' + (res && res.statusCode)) return cb(er) } if (!er && !conflict) return cb(er, parsed, json, res) // let's see what versions are already published. client.request(fixed + '?write=true', { auth: auth }, function (er, current) { if (er) return cb(er) putNext.call(client, registry, data.version, root, current, auth, cb) }) }) } function putNext (registry, newVersion, root, current, auth, cb) { // already have the tardata on the root object // just merge in existing stuff var curVers = Object.keys(current.versions || {}).map(function (v) { return semver.clean(v, true) }).concat(Object.keys(current.time || {}).map(function (v) { if (semver.valid(v, true)) return semver.clean(v, true) }).filter(function (v) { return v })) if (curVers.indexOf(newVersion) !== -1) { return cb(conflictError(root.name, newVersion)) } current.versions[newVersion] = root.versions[newVersion] current._attachments = current._attachments || {} for (var i in root) { switch (i) { // objects that copy over the new stuffs case 'dist-tags': case 'versions': case '_attachments': for (var j in root[i]) { current[i][j] = root[i][j] } break // ignore these case 'maintainers': break // copy default: current[i] = root[i] } } var maint = JSON.parse(JSON.stringify(root.maintainers)) root.versions[newVersion].maintainers = maint var uri = url.resolve(registry, escaped(root.name)) var options = { method: 'PUT', body: current, auth: auth } this.request(uri, options, cb) } function conflictError (pkgid, version) { var e = new Error('cannot modify pre-existing version') e.code = 'EPUBLISHCONFLICT' e.pkgid = pkgid e.version = version return e }
pref('devcache.debug', false); pref('devcache.enabled', true); pref('devcache.patterns', '');
/* UTILIZZO DEL MODULO: var mailer = require('percorso/per/questoFile.js'); mailer.inviaEmail(nome, cognome, emailDestinatario, oggetto, corpoInHtml); OPPURE mailer.inviaEmail(opzioniEmail); dove opzioniEmail è un oggetto JSON formato così: { from: '"Nome Visualizzato" <mail@example.com>', // mail del mittente to: 'info@contoso.com', // email destinatario, eventualmente può essere una lista con elementi separati da virgole subject: 'Oggetto', // l'oggetto dell'email text: 'Ciao', // email solo testo html: '<h3>Ciao</h3>' // email HTML } L'indirizzo email usato per l'invio nel primo caso è quello del gruppo dei developer (creato ad hoc per il progetto) , ovvero mail.sitotranquillo@gmail.com Eventualmente basta cambiare i settaggi nel transporter Un futuro lavoro potrebbe essere quello di fare in modo che anche il transporter sia settabile a piacimento dall'applicazione stessa */ 'use strict'; const nodemailer = require('nodemailer'); var jsonfile = require('jsonfile') var file = './server/config/mailSettings.json'; var fs = require('fs'); var transporter; //var passwords = require('../config/passwords'); var scriviFileDummy = function() { var settaggi = { host: 'smtp.example.org', port: 465, secure: 'true', user: 'user@example.org', pass: 'passwordExample' }; // scrivo il file dummy jsonfile.writeFileSync(file, settaggi); return settaggi; }; var impostaTransporter = function() { var settaggi = leggiPrivate(); // svuoto il vecchio transporter e lo ricreo transporter = null; transporter = nodemailer.createTransport({ host: settaggi.host, port: settaggi.port, secure: settaggi.secure, auth: { user: settaggi.user, pass: settaggi.pass } }); console.log('transporter impostato'); } var leggiPrivate = function() { if (fs.existsSync(file)) { console.log('File exists'); return jsonfile.readFileSync(file) } else { // file does not exist return scriviFileDummy(); } } exports.leggiSettaggi = function() { console.log('chiamata dalla api al mailer') if (fs.existsSync(file)) { console.log('File exists'); return jsonfile.readFileSync(file) } else { // file does not exist return scriviFileDummy(); } } exports.scriviSettaggi = function(obj) { // se non ci sono settaggi li creo dummy if (obj === null) scriviFileDummy() else jsonfile.writeFile(file, obj, function(err) { if (err) return console.log('ERRORE NELLA SCRITTURA DEI SETTAGGI EMAIL'); impostaTransporter(); }); } exports.inviaEmail = function(opzioniEmail) { if (transporter === null || transporter === undefined) { // lo popolo al volo impostaTransporter(); } transporter.sendMail(opzioniEmail, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); }) } exports.inviaEmail = function(nome, cognome, emailDestinatario, oggetto, corpoInHtml) { /* FORMA JSON DELLE OPZIONI: { from: '"Fred Foo 👻" <foo@blurdybloop.com>', // indirizzo mittente to: 'bar@blurdybloop.com, baz@blurdybloop.com', // lista riceventi subject: 'Hello ✔', // Intestazione text: 'Hello world ?', // email con testo normale html: '<b>Hello world ?</b>' // email con testo in html } */ if (transporter === null || transporter === undefined) { // lo popolo al volo impostaTransporter(); } var opzioniEmail = { from: '"Sito Tranquillo" <mail.sitotranquillo@gmail.com>', to: emailDestinatario, subject: oggetto, html: corpoInHtml } transporter.sendMail(opzioniEmail, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); }) }
"use strict"; var os = require("os"); var fs = require('fs'); var settings = require("../config.js").settings; exports.module = function() { this.onCommand_help = function(nick, command) { var chan = this.channel; fs.readFile('./package.json', 'utf-8', function(err, data) { if (!err) { chan.say(settings.globalNick + " v" + JSON.parse(data).version + " by Dirbaio, Nina, LifeMushroom, and AlphaTech. Running on Node.js " + process.versions.node + " (" + os.type() + " " + os.release() + " " + os.arch() + ")."); chan.say("For a list of available commands, check http://v.gd/TheBotCommands"); } else { console.err("Error opening ./package.js... Did you delete it?") } }); }; };
/* eslint-env node */ import { JSDOM } from 'jsdom'; const html = `<body> <div id="test_player" data-vimeo-id="2"></div> <div class="multiple"> <iframe class="two" src="https://player.vimeo.com/video/2"></iframe> <iframe class="one" src="https://player.vimeo.com/video/76979871"></iframe> </div> </body>`; global.window = new JSDOM(html).window; global.document = window.document; global.navigator = window.navigator; global.window.jQuery = global.jQuery = require('jquery');
Vue.component('snackbar', require('./components/material/snackbar.vue')); Vue.component('show-snackbar', require('./components/material/show-snackbar.vue'));
function changeQueryStr(name, value) { var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1) { newQuery = ''; } else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); } function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function init_pagination(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); }); } $(document).ready(init_filtering_stories); $(document).ready(init_pagination);
import Route from '@ember/routing/route' import resetScroll from 'radio4000/mixins/reset-scroll' export default Route.extend(resetScroll, {})
/* Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com) This file is part of the Webcampak project. Webcampak is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Webcampak. If not, see http://www.gnu.org/licenses/. */ console.log('Log: Load: Webcampak.view.dashboard.sourcepicturesizes.SourcesList'); //var rowEditing = Ext.create('Ext.grid.plugin.RowEditing'); Ext.define('Webcampak.view.dashboard.sourcepicturesizes.SourcesList' ,{ extend: 'Ext.form.ComboBox', alias : 'widget.statssourceslistpicturesizes', store: 'permissions.sources.Sources', name: 'source', valueField: 'id', displayField: 'name', typeAhead: true, emptyText: i18n.gettext('Select another source...'), style: 'text-align: center;', width: 315 });
global.should = require('should'); global.Breadboard = require('../lib');
function PingPongPaddle(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = { rotation: new THREE.Vector3(0, 0, 0), init: function(scene) { var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geometry = new THREE.CubeGeometry(this.radius, this.radius, .1); var geometry = new THREE.CylinderGeometry(this.radius, this.radius, .1, 16, 1); this.paddle = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ map: tableImage, transparent: true, opacity: .5 })); //this.paddle.doubleSided = true; this.rotate(Math.PI / 2, 0, 0); this.paddle.position.x = this.x; this.paddle.position.y = this.y; this.paddle.position.z = this.z; scene.add(this.paddle); }, update: function() { if (this.paddle.position.y > 20) { direction = -1; } else if (this.paddle.position.y < -20) { direction = 1; } this.paddle.position.y += direction * .1; }, hitPaddle: function(x, y, z, radius) { if (Math.abs(this.paddle.position.x - x) < radius) { return isBetween(y, this.paddle.position.y + this.radius / 2, this.paddle.position.y - this.radius / 2) && isBetween(z, this.paddle.position.z + this.radius / 2, this.paddle.position.z - this.radius / 2); } }, rotate: function(x, y, z) { this.paddle.rotateOnAxis(new THREE.Vector3(1, 0, 0), x); this.rotation.x += x; this.paddle.rotateOnAxis(new THREE.Vector3(0, 1, 0), y); this.rotation.y += y; this.paddle.rotateOnAxis(new THREE.Vector3(0, 0, 1), z); this.rotation.z += z; } } var direction = 1; function isBetween(x, x1, x2) { return (x <= x1 && x >= x2) || (x >= x1 && x <= x2); }
function InstrumentSelector(list) { this.instruments = list; this.currentInstrument; this.updateInstrumentView(); } InstrumentSelector.prototype.addInstrument = function (type, url, colorCode) { var l = this.instruments.push(new Instrument(type, url, colorCode)); this.createInstrumentView(l-1); } InstrumentSelector.prototype.removeInstrument = function (type, url, colorCode) { this.instruments.push(new Instrument(type, url, colorCode)); this.updateInstrumentView(); } InstrumentSelector.prototype.createInstrumentView = function (index) { var bar = document.getElementById("instrumentBar"); var img = document.createElement("span"); img.className = "instrumentContainer"; img.id = this.instruments[index].instrumentName; img.style.backgroundImage = "url(" + this.instruments[index].imgURL + ")"; img.style.backgroundColor = this.instruments[index].color; // img.style.backgroundImage = "url(images/"+this.instruments[index]+".png)"; bar.appendChild(img); } InstrumentSelector.prototype.updateInstrumentView = function () { var bar = document.getElementById("instrumentBar"); // first clear all the children. var len = bar.children.length; for (var a=0; a<len; a++) { bar.removeChild(bar.children[a]); } // then add all for (var i=0; i < this.instruments.length; i++) { this.createInstrumentView(i); } } InstrumentSelector.prototype.setActiveInstrument = function (instrumentName) { this.currentInstrument = this.getInstrument(instrumentName); this.updateSelected(); } InstrumentSelector.prototype.getInstrument = function (instrumentName) { for (var i=0; i<this.instruments.length; i++) { // alert(this.instruments[i].instrumentName + " " + instrumentName); if (this.instruments[i].instrumentName == instrumentName) { return this.instruments[i]; } } return null; } InstrumentSelector.prototype.updateSelected = function () { for (var i=0; i<this.instruments.length; i++) { var sel = document.getElementById(this.instruments[i].instrumentName); sel.className = sel.className.replace(" instrumentSelected",""); } var sel = document.getElementById(this.currentInstrument.instrumentName); sel.className = sel.className + " instrumentSelected"; }
function glitch_frame(frame) { // bail out if we have no motion vectors let mvs = frame["mv"]; if ( !mvs ) return; // bail out if we have no forward motion vectors let fwd_mvs = mvs["forward"]; if ( !fwd_mvs ) return; // clear horizontal element of all motion vectors for ( let i = 0; i < fwd_mvs.length; i++ ) { // loop through all rows let row = fwd_mvs[i]; for ( let j = 0; j < row.length; j++ ) { // loop through all macroblocks let mv = row[j]; // THIS IS WHERE THE MAGIC HAPPENS mv[0] = 0; // this sets the horizontal motion vector to zero // mv[1] = 0; // you could also change the vertical motion vector } } }
'use strict'; const {Application} = require('backbone.marionette'); const Geppetto = require('backbone.geppetto'); const debug = require( 'debug' )( 'dpac:app', '[Context]' ); const eventLog = require( 'debug' )( 'dpac:core.events', '\u2709' ); const app = module.exports = new Application(); const AppContext = Geppetto.Context.extend( { initialize: function( config ){ debug( "#initialize" ); Geppetto.setDebug( true ); this.vent.on( 'all', function( eventName, event ){ eventLog( eventName ); } ); this.wireValue( 'appContext', this ); this.wireValue( 'app', app ); this.wireCommand( "app:startup:requested", require( './controllers/BootstrapModule' ) ); } } ); app.on( 'start', function(){ debug( 'App#start' ); const app = this; app.context = new AppContext(); app.context.dispatch( 'app:startup:requested' ); } );
jQuery(document).ready(function(jQuery){ jQuery('.smile-upload-media').click(function(e) { _wpPluploadSettings['defaults']['multipart_params']['admin_page']= 'customizer'; var button = jQuery(this); var id = 'smile_'+button.attr('id'); var uid = button.data('uid'); var rmv_btn = 'remove_'+button.attr('id'); var img_container = button.attr('id')+'_container'; //Extend wp.media object var uploader = wp.media.frames.file_frame = wp.media({ title: 'Select or Upload Image', button: { text: 'Choose Image' }, library: { type: 'image' }, multiple: false, }); uploader.on('select', function(props, attachment){ attachment = uploader.state().get('selection').first().toJSON(); var data = attachment.id+"|"+attachment.url; var sz = jQuery(".cp-media-"+uid).val(); var alt = attachment.alt;//console.log(id); var val = attachment.id+"|"+sz+"|"+alt; var a = jQuery("#"+id); var name = jQuery("#"+id).attr('name'); a.val(val); a.attr('value',val); jQuery(".cp-media-"+uid).attr('data-id',attachment.id); jQuery(".cp-media-"+uid).attr('data-alt',attachment.alt); jQuery(".cp-media-"+uid).parents(".cp-media-sizes").removeClass("hide-for-default"); jQuery("."+img_container).html('<img src="'+attachment.url+'"/>'); jQuery("#"+rmv_btn).show(); button.text('Change Image'); // Partial Refresh // - Apply background, background-color, color etc. var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var url = attachment.url; partial_refresh_image( css_preview, selector, property, unit, url ); jQuery(document).trigger('cp-image-change', [name,url, val] ); jQuery("#"+id).trigger('change'); }); uploader.open(button); return false; }); jQuery('.smile-remove-media').on('click', function(e){ e.preventDefault(); var button = jQuery(this); var id = button.attr('id').replace("remove_","smile_"); var upload = button.attr('id').replace("remove_",""); var img_container = button.attr('id').replace("remove_","")+'_container'; jQuery("#"+id).attr('value',''); // Partial Refresh // - Apply background, background-color, color etc. var a = jQuery("#"+id); var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var value = ''; // Empty the background image var name = jQuery("#"+id).attr('name'); partial_refresh_image( css_preview, selector, property, unit, value ); var html = '<p class="description">No Image Selected</p>'; jQuery("."+img_container).html(html); button.hide(); jQuery("#"+upload).text('Select Image'); jQuery(document).trigger('cp-image-remove', [name,value] ); jQuery("#"+id).trigger('change'); }); jQuery('.smile-default-media').on('click', function(e){ e.preventDefault(); var button = jQuery(this); var id = button.attr('id').replace("default_","smile_"); var upload = button.attr('id').replace("default_",""); var img_container = button.attr('id').replace("default_","")+'_container'; var container = jQuery(this).parents('.content'); var default_img = jQuery(this).data('default'); jQuery("#"+id).attr('value',default_img); // Partial Refresh // - Apply background, background-color, color etc. var a = jQuery("#"+id); var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var value = default_img; // Empty the background image var name = jQuery("#"+id).attr('name'); partial_refresh_image( css_preview, selector, property, unit, value ); var html = '<p class="description">No Image Selected</p>'; jQuery("."+img_container).html('<img src="'+default_img+'"/>'); jQuery(document).trigger('cp-image-default', [name,value] ); jQuery("#"+id).trigger('change'); container.find(".cp-media-sizes").hide().addClass('hide-for-default'); }); jQuery(".cp-media-size").on("change", function(e){ var img_id = jQuery(this).attr('data-id'); var alt = jQuery(this).attr('data-alt'); var input = 'smile_'+jQuery(this).parents('.cp-media-sizes').data('name'); var val = ""; if( img_id !== '' ) { val = img_id+"|"+jQuery(this).val(); } if( alt !== '' ) { val = val+"|"+alt; } jQuery("#"+input).val(val); jQuery("#"+input).attr('value',val); }); function partial_refresh_image( css_preview, selector, property, unit, value ) { // apply css by - inline if( css_preview != 1 || null == css_preview || 'undefined' == css_preview ) { var frame = jQuery("#smile_design_iframe").contents(); switch( property ) { case 'src': frame.find( selector ).attr( 'src' , value ); break; default: frame.find( selector ).css( property , 'url(' + value + ')' ); break; } } // apply css by - after css generation jQuery(document).trigger('updated', [css_preview, selector, property, value, unit]); } });
// Copyright © 2016 Gary W. Hudson Esq. // Released under GNU GPL 3.0 var lzwh = (function() {var z={ Decode:function(p) {function f(){--h?k>>=1:(k=p.charCodeAt(q++)-32,h=15);return k&1}var h=1,q=0,k=0,e=[""],l=[],g=0,m=0,c="",d,a=0,n,b; do{m&&(e[g-1]=c.charAt(0));m=a;l.push(c);d=0;for(a=g++;d!=a;)f()?d=(d+a>>1)+1:a=d+a>>1;if(d)c=l[d]+e[d],e[g]=c.charAt(0) else{b=1;do for(n=8;n--;b*=2)d+=b*f();while(f());d&&(c=String.fromCharCode(d-1),e[g]="")}}while(d);return l.join("")}, Encode:function(p) {function f(b){b&&(k|=e);16384==e?(q.push(String.fromCharCode(k+32)),e=1,k=0):e<<=1}function h(b,d){for(var a=0,e,c=l++;a!=c;) e=a+c>>1,b>e?(a=e+1,f(1)):(c=e,f(0));if(!a){-1!=b&&(a=d+1);do{for(c=8;c--;a=(a-a%2)/2)f(a%2);f(a)}while(a)}}for(var q=[],k=0, e=1,l=0,g=[],m=[],c=0,d=p.length,a,n,b=0;c<d;)a=p.charCodeAt(c++),g[b]?(n=g[b].indexOf(a),-1==n?(g[b].push(a),m[b].push(l+1), c-=b?1:0,h(b,a),b=0):b=m[b][n]):(g[b]=[a],m[b]=[l+1],c-=b?1:0,h(b,a),b=0);b&&h(b,0);for(h(-1,0);1!=e;)f(0);return q.join("")} };return z})(); if(typeof define==='function'&&define.amd)define(function(){return lzw}) else if(typeof module!=='undefined'&&module!=null)module.exports=lzw;
'use strict'; var winston = require('winston'), loggerUtils = require('alien-node-winston-utils'); module.exports = { port : 3000, // TODO this isnt setup for nginx yet server : { // Ports on which to run node instances. Should be n-1 instances, where n is the number of cores. enabledPorts : [3000] }, mysql : { connectionLimit : 10, host : 'localhost', user : process.env.MYSQL_USER, password : process.env.MYSQL_PASS, database : 'club540' }, // // Email configuration // email : { // smtp : { // host : "smtp.mailgun.org", // port : 465, // sender : "noreply@playlist.com", // username : "postmaster@playlist.com", // password : "Playlist123" // } // }, redis : { host : 'localhost', port : 6379, password : '' }, logging : { winston : { transports : [ { name : 'console', level : 'debug', timestamp : loggerUtils.getDateString, colorize : true, transportType : 'console' } // TODO: allow parallel logging strategies // using this strategy will disable console logging of errors // { // name : 'file', // level : 'debug', // timestamp : loggerUtils.getTimestamp, // colorize : true, // transportType : 'file', // filename : 'logs/activity.log', // json : false, // required for formatter to work // formatter : loggerUtils.getFormatter, // handleExceptions : true, // datePattern : '.yyyy-MM-dd' // dictates how logs are rotated - more specific pattern rotates more often // } ], strategies : { console : winston.transports.Console, file : winston.transports.DailyRotateFile } } }, errors : { db : { NO_RESULTS : { code : 6000, message : 'No results' } } } };
'use strict'; const path = require('path'); const os = require('os'); const fs = require('fs-extra'); const fieHome = require('fie-home'); const debug = require('debug')('core-report'); const fieUser = require('fie-user'); const execSync = require('child_process').execSync; const spawn = require('cross-spawn'); const cache = require('fie-cache'); /** * 环境变量获取 */ const cacheEnvGetter = { fieVersion() { return ( process.env.FIE_VERSION || execSync('npm view fie version') .toString() .replace(/[\nv]/g, '') ); }, email() { return fieUser.getEmail(); }, nodeVersion() { return execSync('node -v') .toString() .replace(/[\nv]/g, ''); }, npmVersion() { try { return execSync('npm -v') .toString() .replace('\n', ''); } catch (e) { return null; } }, tnpmVersion() { try { return execSync('tnpm -v') .toString() .split('\n')[0] .match(/\d+\.\d+\.\d+/)[0]; } catch (ex) { // 外网无tnpm return null; } }, system() { return `${os.platform()} ${os.release()}`; }, }; /** * 获取当前分支版本 * @param cwd * @returns {string} */ exports.getCurBranch = function(cwd) { const headerFile = path.join(cwd, '.git/HEAD'); let version = ''; if (fs.existsSync(headerFile)) { const gitVersion = fs.readFileSync(headerFile, { encoding: 'utf8' }); const arr = gitVersion.split(/refs[\\\/]heads[\\\/]/g); if (arr && arr.length > 1) { version = arr[1]; } } return version.trim(); }; /** * 获取项目URL * @returns {*} */ exports.getProjectUrl = function() { let url; try { url = ( spawn .sync('git', ['config', '--get', 'remote.origin.url'], { silent: true }) .stdout.toString() || '' ).trim(); // 有些git的url是http开头的,需要格式化为git@格式,方便统一处理 const match = url.match(/http:\/\/gitlab.alibaba-inc.com\/(.*)/); if (match && match[1]) { url = `git@gitlab.alibaba-inc.com:${match[1]}`; } } catch (err) { debug('git config 错误:', err.message); } return url; }; /** * 获取项目相关环境 */ exports.getProjectInfo = function(cwd) { const branch = exports.getCurBranch(cwd); const pkgPath = path.join(cwd, 'package.json'); const CONFIG_FILE = process.env.FIE_CONFIG_FILE || 'fie.config.js'; const fiePath = path.join(cwd, CONFIG_FILE); // 这里不能使用fieConfig这个包,会循环引用 let pkg; let fie; let repository = exports.getProjectUrl(); // 判断pkg是否存在 if (fs.existsSync(pkgPath)) { pkg = fs.readJsonSync(pkgPath, { throws: false }); } // 判断fie.config.js是否存在 if (fs.existsSync(fiePath)) { delete require.cache[fiePath]; try { fie = require(fiePath); } catch (e) { fie = null; } } // 如果git中没有则尝试从pkg中获取 if (pkg && pkg.repository && pkg.repository.url) { repository = pkg.repository.url; } return { cwd, branch, pkg, fie, repository, }; }; /** * 获取项目的环境信息 * @param force 为true时 则获取实时信息,否则读取缓存 * 对 tnpm, node 版本等重新获取,一般在报错的时候才传入 true * @returns {*} */ exports.getProjectEnv = function(force) { let cacheEnv = cache.get('reportEnvCache'); if (!cacheEnv || force) { cacheEnv = {}; const cacheEnvKeys = Object.keys(cacheEnvGetter); cacheEnvKeys.forEach(item => { cacheEnv[item] = cacheEnvGetter[item](); }); // 缓存三天 cache.set('reportEnvCache', cacheEnv, { expires: 259200000 }); } return cacheEnv; }; /** * 获取当前执行的命令,移除用户路径 */ exports.getCommand = function(arg) { let argv = arg || process.argv; argv = argv.map(item => { const match = item.match(/\\bin\\(((?!bin).)*)$|\/bin\/(.*)/); // mac if (match && match[3]) { // 一般 node fie -v 这种方式则不需要显示 node return match[3] === 'node' ? '' : match[3]; } else if (match && match[1]) { // 一般 node fie -v 这种方式则不需要显示 node return match[1] === 'node.exe' ? '' : match[1]; } else if (!match && item.indexOf('node.exe') !== -1) { // fix如果C:\\node.exe 这种不带bin的路径 // TODO 当然这里的正则可以再优化兼容一下 return ''; } return item; }); return argv.join(' ').trim(); }; /** * 获取模块的类型和版本 */ exports.getFieModuleVersion = function(mod) { const modPkgPath = path.join(fieHome.getModulesPath(), mod, 'package.json'); let pkg = {}; if (fs.existsSync(modPkgPath)) { pkg = fs.readJsonSync(modPkgPath, { throws: false }) || {}; } return pkg.version; };
module.exports = { 'extends': ['google', 'plugin:react/recommended'], 'parserOptions': { 'ecmaVersion': 6, 'sourceType': 'module', 'ecmaFeatures': { 'jsx': true } }, 'env': { 'browser': true, }, 'plugins': [ 'react' ] };
/** * Client. * @module client */ /** * View configuration. * @class ViewConfig */ function ViewConfig(resources) { this.playAnimations = true; this.resources = resources; } /** * Should we play animations? * @method setPlayAnimations */ ViewConfig.prototype.setPlayAnimations = function(value) { this.playAnimations = value; } /** * Should we play animations? * @method getPlayAnimations */ ViewConfig.prototype.getPlayAnimations = function() { return this.playAnimations; } /** * Scale animation time. * @method scaleAnimationTime */ ViewConfig.prototype.scaleAnimationTime = function(millis) { if (this.playAnimations) return millis; return 1; } /** * Get resources. * @method getResources */ ViewConfig.prototype.getResources = function() { return this.resources; } module.exports = ViewConfig;
var com = com || {}; com.hiyoko = com.hiyoko || {}; com.hiyoko.component = com.hiyoko.component || {}; com.hiyoko.component.UlList = function($html){}; com.hiyoko.util.extend(com.hiyoko.component.ApplicationBase, com.hiyoko.component.UlList); com.hiyoko.component.UlList.prototype.renderDefaultLi = function($li, item) { if(item.type !== 'node') { var $text = $('<span></span>') $text.text(item.text); $text.addClass('com-hiyoko-component-ul-list-li-text'); $li.append($text); } $li.attr('title', item.value); return $li; } com.hiyoko.component.UlList.prototype.buildList = function(list, opt_option) { this.$html.empty(); var $ul = $('<ul></ul>'); var option = opt_option || {renderer: this.renderDefaultLi.bind(this)}; list.forEach(function(item){ var $li = $('<li></li>'); $li = option.renderer($li, item, option); if(item.type !== 'leaf') { var tmpOption = opt_option || {renderer: this.renderDefaultLi.bind(this)}; tmpOption.child = true; $li.append(this.buildList(item.list, tmpOption)); } if(option.child) { $li.addClass('com-hiyoko-component-ul-list-li-child'); } else { $li.addClass('com-hiyoko-component-ul-list-li'); } $ul.append($li); }.bind(this)); this.$html.append($ul); return $ul; }; com.hiyoko.component.UlList.prototype.getValueLi = function($li) { var result = {}; var text = $li.children('.com-hiyoko-component-ul-list-li-text').text(); result.text = text; var $ul = $li.children('ul'); if($ul.length) { result.list = this.getValue($ul); } if(result.text && result.list) { result.type = 'namednode'; } else if(result.list) { result.type = 'node'; } else { result.type = 'leaf'; } return result; }; com.hiyoko.component.UlList.prototype.getValue = function(opt_$html) { if(opt_$html) { var $html = $(opt_$html); var result = []; $.each($html.children('li'), function(i, v){ result.push(this.getValueLi($(v))); }.bind(this)); return result; } else { return this.getValue(this.$html.children('ul')); } };
Fox.define('language', [], function () { var Language = function (cache) { this.cache = cache || null; this.data = {}; }; _.extend(Language.prototype, { data: null, cache: null, url: 'I18n', has: function (name, category, scope) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return true; } } } }, get: function (scope, category, name) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return this.data[scope][category][name]; } } } if (scope == 'Global') { return name; } return false; }, translate: function (name, category, scope) { scope = scope || 'Global'; category = category || 'labels'; var res = this.get(scope, category, name); if (res === false && scope != 'Global') { res = this.get('Global', category, name); } return res; }, translateOption: function (value, field, scope) { var translation = this.translate(field, 'options', scope); if (typeof translation != 'object') { translation = {}; } return translation[value] || value; }, loadFromCache: function () { if (this.cache) { var cached = this.cache.get('app', 'language'); if (cached) { this.data = cached; return true; } } return null; }, clearCache: function () { if (this.cache) { this.cache.clear('app', 'language'); } }, storeToCache: function () { if (this.cache) { this.cache.set('app', 'language', this.data); } }, load: function (callback, disableCache) { this.once('sync', callback); if (!disableCache) { if (this.loadFromCache()) { this.trigger('sync'); return; } } this.fetch(); }, fetch: function (sync) { var self = this; $.ajax({ url: this.url, type: 'GET', dataType: 'JSON', async: !(sync || false), success: function (data) { self.data = data; self.storeToCache(); self.trigger('sync'); } }); }, }, Backbone.Events); return Language; });
/** * Copyright 2014 IBM Corp. * * 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. **/ // If you use this as a template, update the copyright with your own name. // Sample Node-RED node file module.exports = function(RED) { "use strict"; // require any external libraries we may need.... //var foo = require("foo-library"); // The main node definition - most things happen in here function mobileactuatorNode(n) { // Create a RED node RED.nodes.createNode(this,n); // Store local copies of the node configuration (as defined in the .html) this.topic = n.topic; this.mobile_type = n.mobile_type; this.mobile_port = n.mobile_port; // copy "this" object in case we need it in context of callbacks of other functions. var node = this; // Do whatever you need to do in here - declare callbacks etc // Note: this sample doesn't do anything much - it will only send // this message once at startup... // Look at other real nodes for some better ideas of what to do.... var msg = {}; msg.topic = this.topic; msg.payload = "Hello world !" // send out the message to the rest of the workspace. // ... this message will get sent at startup so you may not see it in a debug node. //this.send(msg); // respond to inputs.... this.on('input', function (msg) { //node.warn("I saw a payload: "+msg.payload); // in this example just send it straight on... should process it here really if (msg.payload[0] == this.mobile_type && msg.payload[1] == 0){ msg.payload = msg.payload.substr(2) node.send(msg); } }); this.on("close", function() { // Called when the node is shutdown - eg on redeploy. // Allows ports to be closed, connections dropped etc. // eg: node.client.disconnect(); }); } RED.nodes.registerType("mobile actuator",mobileactuatorNode); }
function parseCategory(aCategory, aFunction) { if(document.location.host == '' || document.location.host == 'localhost' ) var url = 'test.html'; else var url = categoryGetURLPrivate(aCategory); $.ajax({ type: "GET", url: url, dataType:'html', success: function(responseText) { var aData = {}; aData.categories = []; aData.alternative = []; aData.related = []; aData.sitesCooled = []; aData.sites = []; aData.alphabar = []; aData.groups = []; aData.editors = []; aData.moz = ''; var tmp = 0; //subcategories and links $(responseText).find('.dir-1').each(function() { aData.categories[tmp] = []; $(this).find('li').each(function() { aData.categories[tmp][aData.categories[tmp].length] = $(this).html().replace(/href="/, 'href="#/Top'); }) aData.categories[tmp].sort(ODPy.sortLocale); tmp++; }); //alternative languages $(responseText).find('.language').find('li').each(function() { aData.alternative[aData.alternative.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.alternative = aData.alternative.sort(ODPy.sortLocale); //related categories $(responseText).find('fieldset.fieldcap .directory').find('li').each(function() { aData.related[aData.related.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.related.sort(ODPy.sortLocale); //sites cooled $(responseText).find('.directory-url').find('li.star').each(function() { aData.sitesCooled[aData.sitesCooled.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); //alert(aData.sitesCooled.toString()); aData.sitesCooled.sort(ODPy.sortLocale); //sites not cooled $(responseText).find('.directory-url').find('li:not(.star)').each(function() { aData.sites[aData.sites.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); aData.sites.sort(ODPy.sortLocale); //alphabar $(responseText).find('.alphanumeric a').each(function() { aData.alphabar[aData.alphabar.length] = $(this).html(); }); aData.alphabar.sort(ODPy.sortLocale); //groups $(responseText).find('.fieldcapRn .float-l li:first').each(function() { var item = $(this).html(); if(item.indexOf('search') != -1){} else aData.groups[aData.groups.length] = item; return; }); aData.groups.sort(ODPy.sortLocale); //editors $(responseText).find('.volEditN a').each(function() { if(trim(stripTags($(this).html()))) aData.editors[aData.editors.length] = '<a href="http://editors.dmoz.org/public/profile?editor='+$(this).html()+'">'+$(this).html()+'</a>'; }); //mozzie if(responseText.indexOf('img/moz') != -1) { try { aData.moz = responseText.split('/img/moz/')[1].split('"')[0]; } catch(e){} } //aData.editors.sort(ODPy.sortLocale); aFunction(aCategory, aData); }, error :function() { ODPy.statusSet('Error category "'+categoryTitle(aCategory)+'" no exists'); ODPy.statusHide(); } }); }
Ext.define('User', { extend: 'Ext.data.Model', fields: [ {name: 'name', type: 'string', convert: function(value,record) { return record.get('name')+' the barbarian'); } }, {name: 'age', type: 'int'}, {name: 'phone', type: 'string'}, {name: 'alive', type: 'boolean', defaultValue: true} ], });