text
stringlengths 2
6.14k
|
|---|
/// <binding AfterBuild="less" />
var gulp = require("gulp");
var less = require("gulp-less");
var path = require("path");
gulp.task("less", function () {
return gulp.src("./contents/styles/*.less")
.pipe(less({
paths: [ path.join(__dirname, "less", "includes") ]
}))
.pipe(gulp.dest("./contents/styles/"));
});
|
import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
import style from "../../assets/global-style";
import { prefixStyle } from "./../../api/utils";
const ProgressBarWrapper = styled.div`
height: 30px;
.bar-inner {
position: relative;
top: 13px;
height: 4px;
background: rgba(0, 0, 0, 0.3);
.progress {
position: absolute;
height: 100%;
background: ${style["theme-color"]};
}
.progress-btn-wrapper {
position: absolute;
left: -8px;
top: -13px;
width: 30px;
height: 30px;
.progress-btn {
position: relative;
top: 7px;
left: 7px;
box-sizing: border-box;
width: 16px;
height: 16px;
border: 3px solid ${style["border-color"]};
border-radius: 50%;
background: ${style["theme-color"]};
}
}
}
`;
function ProgressBar(props) {
const progressBar = useRef();
const progress = useRef();
const progressBtn = useRef();
const [touch, setTouch] = useState({});
const { percent } = props;
const { percentChange } = props;
const transform = prefixStyle("transform");
const progressBtnWidth = 16;
useEffect(() => {
if (percent >= 0 && percent <= 1 && !touch.initiated) {
const barWidth = progressBar.current.clientWidth - progressBtnWidth;
const offsetWidth = percent * barWidth;
progress.current.style.width = `${offsetWidth}px`;
progressBtn.current.style[
transform
] = `translate3d(${offsetWidth}px, 0, 0)`;
}
}, [percent]);
const _offset = (offsetWidth) => {
progress.current.style.width = `${offsetWidth}px`;
progressBtn.current.style.transform = `translate3d(${offsetWidth}px, 0, 0)`;
};
const _changePercent = () => {
const barWidth = progressBar.current.clientWidth - progressBtnWidth;
const curPercent = progress.current.clientWidth / barWidth;
percentChange(curPercent);
};
const progressClick = (e) => {
const rect = progressBar.current.getBoundingClientRect();
const offsetWidth = e.pageX - rect.left;
_offset(offsetWidth);
_changePercent(percent);
};
const progressTouchStart = (e) => {
const startTouch = {};
startTouch.initiated = true;
startTouch.startX = e.touches[0].pageX;
startTouch.left = progress.current.clientWidth;
setTouch(startTouch);
};
const progressTouchMove = (e) => {
if (!touch.initiated) return;
const deltaX = e.touches[0].pageX - touch.startX;
const barWidth = progressBar.current.clientWidth - progressBtnWidth;
const offsetWidth = Math.min(Math.max(0, touch.left + deltaX), barWidth);
_offset(offsetWidth);
};
const progressTouchEnd = (e) => {
const endTouch = JSON.parse(JSON.stringify(touch));
endTouch.initiated = false;
setTouch(endTouch);
_changePercent();
};
return (
<ProgressBarWrapper>
<div className="bar-inner" ref={progressBar} onClick={progressClick}>
<div className="progress" ref={progress}></div>
<div
className="progress-btn-wrapper"
ref={progressBtn}
onTouchStart={progressTouchStart}
onTouchMove={progressTouchMove}
onTouchEnd={progressTouchEnd}
>
<div className="progress-btn"></div>
</div>
</div>
</ProgressBarWrapper>
);
}
export default React.memo(ProgressBar);
|
import { WebGLRenderer } from 'three';
class WebGLRendererComponent {
constructor() {
let elements = document.querySelectorAll('[renderer-webgl]');
elements.forEach((elm) => {
const renderer = new WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
elm.renderer = renderer;
elm.appendChild(renderer.domElement);
});
}
}
export default WebGLRendererComponent;
|
import expect from 'expect';
import React from 'react';
import { Menu } from './../../../../src/components/core/menu/Menu.jsx';
import { store, shallowWithContext } from './../../../testUtils/index';
const props = {
store,
menu: [
{
text: 'add',
key: 'add'
},
{
text: 'delete',
key: 'delete'
}
]
};
describe('A rendered Menu', () => {
const component = shallowWithContext(<Menu { ...props } />);
it('Should be a UL HTML Node', () => {
expect(component.type()).toEqual('ul');
});
it('Should have children', () => {
expect(component.props().children).toBeTruthy();
});
it('Should have the correct class name', () => {
expect(
component.props().className
).toEqual('react-grid-action-menu-container');
});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import OptionsScreen from './scenes/OptionsScreen';
import VRScene from './scenes/VRScene';
import getFlashcards from './utils/flashcards';
class Application extends React.Component {
constructor(props){
super(props);
this.state = {terms: [], page: 'options'};
}
optionsChanged(options){
console.log(options);
this.setState({index: options.selected_scene_index});
getFlashcards(options.quizlet_set.value)
.then(response => {
console.log("RESPONSE");
console.log(response);
this.setState({terms: response, page: 'vr'});
})
}
render () {
if (this.state.page === 'options'){
return <OptionsScreen optionsChanged={this.optionsChanged.bind(this)} />
}
else if (this.state.page === 'vr'){
return (
<VRScene sceneIndex={this.state.index} />
);
}
}
}
const App = () => (
<MuiThemeProvider>
<Application />
</MuiThemeProvider>
)
ReactDOM.render(<App />, document.querySelector('.scene-container'));
|
$(function() {
$("#cronology").css("height", $(".struct").css("height"));
$(".struct textarea").autosize({
append: "\n",
callback: function(){
$("#cronology").css("height", $(".struct").css("height"));
}
});
var notify = function(callback){
var isActive = $(".menu-top").attr('is-active');
if(!isActive){
callback();
$(".menu-top").attr('is-active', true);
}else{
$(".menu-top").removeAttr('is-active');
$("#naveg").remove();
$(".indq").remove();
}
}
$("#userOptions").click(function(){
var self = this;
notify(function(){
var $image = $(self).find('img').attr('src');
$(self).html(
'<img src="'+ $image +'" />'+
'<div class="indq"></div><ul id="naveg"><li>Voltar</li>'+
'<li><a href="logout">Sair</a></li></ul>'
);
});
});
$("#mail").click(function(){
var self = this;
notify(function(){
var $image = $(self).find('img').attr('src');
$(self).html(
'<img src="'+ $image +'" /><div class="indq"></div><ul id="naveg" style="margin-top: 56px" >'+
$("#alertMess").show().html() +
'</ul>'
);
});
});
$("#notificacoes").click(function(){
var self = this;
notify(function(){
var $image = $(self).find('img').attr('src');
$(self).html(
'<img src="' + $image + '" />'+
'<div class="indq"></div><ul id="naveg" style="margin-top: 56px" >'+
$("#alertNotific").show().html()+
'</ul>'
);
});
});
$("#atividade").click(function(){
$("body").append("<div id='backMess'></div>");
$(".mess").show();
$("#backMess").click(function(){
$("#backMess").remove();
$(".mess").hide();
});
});
$(".turmasIcons").click(function(){
$("body").append("<div id='backMess'></div>");
$(".mess").show();
$("#backMess").click(function(){
$("#backMess").remove();
$(".mess").hide();
});
});
});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("templates","ms",{button:"Templat",emptyListMsg:"(Tiada Templat Disimpan)",insertOption:"Replace actual contents",options:"Template Options",selectPromptMsg:"Sila pilih templat untuk dibuka oleh editor<br>(kandungan sebenar akan hilang):",title:"Templat Kandungan"});
|
function GetVisa() {
function m(text) {
return text.split(":")[1];
}
function x(text) {
return text.replace('\\', '\\\\"').replace('"', '\\"').replace("'", "\\'");
}
function y(text) {
return text.replace('<', '<').replace('>', '>');
}
var submitinfo = '';
$('.hd a').each(function (i, n) {
var $me = $(this);
var type = $.trim($me.text());
if (type.indexOf('用户咨询') != -1 || type.indexOf('常见问题') != -1)
return;
var data = '';
$('#tagContent' + (i + 1) + " tr").each(function () {
var tr = $(this);
var td1 = tr.children('td:eq(0)');
if (td1.length < 1) return;
var td2 = tr.children('td:eq(1)');
data += (',{ "name":"' + x($.trim(td1.text())) + '", "val": "' + x($.trim(td2.text())) + '"}');
});
submitinfo += ',{ "type":"' + x($.trim($me.text())) + '", "data":[' + data.substring(1, data.length) + '] }';
});
var mid = $('.mid');
var visaItem = '<VisaItem>'
+ '<Name>' + y($.trim($('a.f16.b.blue').text())) + '</Name>'
+ '<ImgUrl>' + y($('.pic img').attr('src')) + '</ImgUrl>'
+ '<办理费用>' + y($.trim(mid.find('span:eq(0) i:last').text())) + '</办理费用>'
+ '<最长停留时间>' + y(m($.trim(mid.find('span:eq(1)').text()))) + '</最长停留时间>'
+ '<入境次数>' + y(m($.trim(mid.find('span:eq(2)').text()))) + '</入境次数>'
+ '<办理时长>' + y(m($.trim(mid.find('span:eq(3)').text()))) + '</办理时长>'
+ '<面试>' + y(m($.trim(mid.find('span:eq(4)').text()))) + '</面试>'
+ '<有效期>' + y(m($.trim(mid.find('span:eq(5)').text()))) + '</有效期>'
+ '<友情提示>' + y($.trim($('.visaDesc4.brown2 p').text())) + '</友情提示>'
+ '<所需材料>[' + y(submitinfo.substring(1, submitinfo.length)) + ']</所需材料>'
+ '</VisaItem>';
//console.info(visaItem.replace(/\s/g, ''));
window.external.Handle("Cabbage.Crawler.Plugins.Uzai.JsCallback,GetVisaItem"
, visaItem);
return true;
}
|
const tap = require('tap')
const fs = require('fs')
const parseAgenda = require('../lib/parse-agenda')
const expectedResult = require('./data/get-agenda-data.json')
const data = fs.readFileSync('test/data/get-agenda-page.html', 'utf-8').toString()
const result = parseAgenda(data)
tap.equal(JSON.stringify(result), JSON.stringify(expectedResult), 'It parses agenda page as expected')
|
/**
* Development config for webpack
*
* Use this to add loaders / modules for the development build
*/
const path = require('path');
const webpackMerge = require('webpack-merge');
const webpackBase = require('./webpack.base.js');
const config = require('./config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function() {
return webpackMerge(webpackBase, {
devtool: 'source-map',
devServer: {
contentBase: config.dist,
historyApiFallback: true,
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(config.src, 'index.html'),
hash: true
})
]
});
}
|
import * as Scrivito from 'scrivito'
const TwitterComponentsWidget = Scrivito.provideWidgetClass('TwitterComponentsWidget', {
attributes: {
twitter: 'string'
}
})
export default TwitterComponentsWidget
|
/*
* webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks )
*
* (C) 2011 Marak Squires
* MIT LICENCE
*
*/
var events = require('events'),
http = require('http'),
https = require('https'),
util = require('util'),
cycle = require('cycle'),
common = require('../common'),
Transport = require('./transport').Transport;
//
// ### function WebHook (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Console transport object responsible
// for making arbitrary HTTP requests whenever log messages and metadata
// are received.
//
var Webhook = exports.Webhook = function (options) {
Transport.call(this, options);
this.name = 'webhook';
this.host = options.host || '127.0.0.1';
this.port = options.port || 8080;
this.method = options.method || 'POST';
this.path = options.path || '/winston-log';
if (options.auth) {
this.auth = {};
this.auth.username = options.auth.username || '';
this.auth.password = options.auth.password || '';
}
if (options.ssl) {
this.port = options.port || 443;
this.ssl = {
key: options.ssl.key || null,
cert: options.ssl.cert || null,
ca: options.ssl.ca
};
}
};
//
// Inherit from `winston.Transport`.
//
util.inherits(Webhook, Transport);
//
// Expose the name of this Transport on the prototype
//
Webhook.prototype.name = 'webhook';
//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Webhook.prototype.log = function (level, msg, meta, callback) {
if (this.silent) {
return callback(null, true);
}
var self = this,
meta = cycle.decycle(meta),
message = common.clone(meta),
options,
req;
// Prepare options for outgoing HTTP request
options = {
host: this.host,
port: this.port,
path: this.path,
method: this.method,
headers: { 'Content-Type': 'application/json' }
};
if (this.ssl) {
options.ca = this.ssl.ca;
options.key = this.ssl.key;
options.cert = this.ssl.cert;
// Required for the test fixture SSL certificate to be considered valid.
options.rejectUnauthorized = false;
}
if (this.auth) {
// Encode `Authorization` header used by Basic Auth
options.headers['Authorization'] = 'Basic ' + new Buffer(
this.auth.username + ':' + this.auth.password, 'utf8'
).toString('base64');
}
// Perform HTTP logging request
req = (self.ssl ? https : http).request(options, function (res) {
// TODO: emit 'logged' correctly,
// keep track of pending logs.
res.on('data', function(data) {
// Do nothing. We need to read the response, or we run into maxSockets
// after 5 requests.
});
self.emit('logged');
if (callback) callback(null, true);
callback = null;
});
req.on('error', function (err) {
//
// Propagate the `error` back up to the `Logger` that this
// instance belongs to.
//
self.emit('error', err);
if (callback) callback(err, false);
callback = null;
});
//
// Write logging event to the outgoing request body
//
// jsonMessage is currently conforming to JSON-RPC v1.0,
// but without the unique id since there is no anticipated response
// see: http://en.wikipedia.org/wiki/JSON-RPC
//
var params = common.clone(meta) || {};
params.timestamp = new Date();
params.message = msg;
params.level = level;
req.write(JSON.stringify({
method: 'log',
params: params
}));
req.end();
};
|
// OPTIMIZED
function parseTagsOptimezed(str) {
if (str === undefined) {
return;
}
var regexUp = /(<upcase>)+(.*?)(<\/upcase>)+/,
regexLow = /(<lowcase>)+(.*?)(<\/lowcase>)+/,
regexOriginal = /(<orgcase>)+(.*?)(<\/orgcase>)+/,
match = regexUp.exec(str),
match1 = regexLow.exec(str),
match2 = regexOriginal.exec(str);
while (match !== null) {
str = str.replace(match[0], match[2].toUpperCase());
match = regexUp.exec(str);
}
while (match1 !== null) {
str = str.replace(match1[0], match1[2].toLowerCase());
match1 = regexLow.exec(str);
}
while (match2 !== null) {
str = str.replace(match2[0], match2[2]);
match2 = regexOriginal.exec(str);
}
console.log(str);
}
parseTagsOptimezed('We are <orgcase>liViNg</orgcase> in a <upcase>yellow submarine</upcase>. We <orgcase>doN\'t</orgcase> have <lowcase>anyThing</lowcase> else.');
//1st try
function parseTags(str) {
if (str === undefined) {
return;
}
var len1,
len2,
len3,
i,
j,
k,
finalResult,
resultUp = '',
resultLow = '',
resultOrg = '',
regexUp = /(<upcase>)+(.*?)(<\/upcase>)+/g,
regexUpT = /(<upcase>)+(.*?)(<\/upcase>)+/,
regexLow = /(<lowcase>)+(.*?)(<\/lowcase>)+/g,
regexLowT = /(<lowcase>)+(.*?)(<\/lowcase>)+/,
regexOriginal = /(<orgcase>)+(.*?)(<\/orgcase>)+/g,
regexOriginalT = /(<orgcase>)+(.*?)(<\/orgcase>)+/;
resultUp = str.match(regexUp).map(function(val) {
val = regexUp.exec(str);
return val[2].toUpperCase();
});
resultLow = str.match(regexLow).map(function(val) {
val = regexLow.exec(str);
return val[2].toLowerCase();
});
resultOrg = str.match(regexOriginal).map(function(val) {
val = regexOriginal.exec(str);
return val[2];
});
finalResult = str;
len1 = resultUp.length;
for (i = 0; i < len1; i += 1) {
finalResult = finalResult.replace(regexUpT, resultUp[i]);
}
len2 = resultOrg.length;
for (k = 0; k < len2; k += 1) {
finalResult = finalResult.replace(regexOriginalT, resultOrg[k]);
}
len3 = resultLow.length;
for (j = 0; j < len3; j += 1) {
finalResult = finalResult.replace(regexLowT, resultLow[j]);
}
console.log(finalResult);
}
parseTags('We are <orgcase>liViNg</orgcase> in a <upcase>yellow submarine</upcase>. We <orgcase>doN\'t</orgcase> have <lowcase>anything</lowcase> else.');
|
/*global $*/
function updatePlayer(message) {
"use strict";
var jsonPlayer, name, whitePlayerName, whiteNameHolder, blackNameHolder;
jsonPlayer = $.parseJSON(message).currentPlayer;
name = jsonPlayer.player.name;
whitePlayerName = $("#white-player").find("span.name").text();
whiteNameHolder = $("#white-player").find("span.name");
blackNameHolder = $("#black-player").find("span.name");
if (whitePlayerName === name) {
whiteNameHolder.addClass("player-name-highlight");
blackNameHolder.removeClass("player-name-highlight");
} else {
whiteNameHolder.removeClass("player-name-highlight");
blackNameHolder.addClass("player-name-highlight");
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:3ee01e5dcb589912c7068eb955d2af1579639c1467bd1df706a9594b82b0da34
size 2494
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import '../../../../src/index.js';
describe('toBeDateCloseToNow', () => {
it('should pass', () => {
const now = new Date().getTime();
const offset = 100;
const date = new Date(now + offset);
expect(date).toBeDateCloseToNow();
expect(date).toBeDateCloseToNow(offset * 10);
expect(date).not.toBeDateCloseToNow(offset / 2);
});
});
|
var searchData=
[
['affinelib_2eh',['affinelib.h',['../affinelib_8h.html',1,'']]]
];
|
const Config = require('../config')
const { httpGet } = require('./http')
const Http = require('http')
const solrAgentConfig = Config.get('solr').shortLiveAgent
const solrAgent = new Http.Agent(solrAgentConfig)
async function getSequenceByHash (md5) {
return httpGet({
port: Config.get('http_port'),
headers: {
'Accept': 'application/json'
},
agent: solrAgent,
path: `/feature_sequence/${md5}`
}).then((body) => {
const doc = JSON.parse(body)
return doc.sequence
})
}
async function getSequenceDictByHash (md5Array) {
if (md5Array.length === 0) return
const ids = md5Array.join(',')
return httpGet({
port: Config.get('http_port'),
headers: {
'Accept': 'application/json'
},
agent: solrAgent,
path: `/feature_sequence/${ids}`
})
.then((resp) => {
if (resp === '') {
throw Error(`Unable to lookup sequence: ${ids}`)
}
if (md5Array.length === 1) {
const doc = JSON.parse(resp)
const obj = {}
obj[doc.md5] = doc.sequence
return obj
} else {
const docs = JSON.parse(resp)
return docs.reduce((h, cur) => {
h[cur.md5] = cur.sequence
return h
}, {})
}
}).catch((err) => {
console.error(err)
})
}
module.exports = { getSequenceByHash: getSequenceByHash, getSequenceDictByHash: getSequenceDictByHash }
|
const assert = require('assert');
const promiseTask = require('../../lib/promise-task');
describe('#promise-task', () => {
const delay = (fuc, time) => {
return new Promise(results => {
setTimeout(() => {
results(fuc());
}, time);
});
}
describe('#promise-task.serial', () => {
it('results', () => {
return promiseTask.serial([
0,
(result) => {
assert.deepEqual(0, result)
return 1;
},
(result) => {
assert.deepEqual(1, result)
return 2;
},
(result) => {
assert.deepEqual(2, result)
return 3;
}
]).then((results) => {
assert.deepEqual([0, 1, 2, 3], results)
});
});
it('order', () => {
return promiseTask.serial([
0,
() => {
return delay(() => 1, 30);
},
() => {
return delay(() => 2, 35);
},
() => {
return delay(() => 3, 0);
}
]).then((results) => {
assert.deepEqual([0, 1, 2, 3], results)
});
});
it('Promise reject', () => {
return promiseTask.serial([
() => 0,
() => 1,
() => Promise.reject(2),
() => 3
]).catch(function (error) {
assert.deepEqual(2, error)
});
});
it('Function error', () => {
return promiseTask.serial([
() => 0,
() => 1,
() => {
throw Error('Function error');
},
() => 3
]).catch(function (error) {
assert.deepEqual('Function error', error.message)
});
});
});
describe('#promise-task.parallel', () => {
const limit = 2;
it('results', () => {
return promiseTask.parallel([
() => 0,
() => 1,
() => 2,
() => 3
], limit).then((results) => {
assert.deepEqual([0, 1, 2, 3], results);
});
});
it('order', () => {
return promiseTask.parallel([
() => {
return delay(() => 0, 40);
},
() => {
return delay(() => 1, 30);
},
() => {
return delay(() => 2, 35);
},
() => {
return delay(() => 3, 0);
}
], limit).then((results) => {
assert.deepEqual([0, 1, 2, 3], results)
});
});
it('Promise reject', () => {
return promiseTask.parallel([
() => 0,
() => 1,
() => Promise.reject(2),
() => 3
], limit).then(() => {
throw new Error('error');
}).catch(function (error) {
assert.deepEqual(2, error)
});
});
it('Function error', () => {
return promiseTask.parallel([
() => 0,
() => 1,
() => {
throw Error('Function error');
},
() => 3
], limit).then(() => {
throw new Error('error');
}).catch(function (error) {
assert.deepEqual('Function error', error.message)
});
});
it('Function error', () => {
return promiseTask.parallel([
null,
undefined,
{},
[]
], limit).then(() => {
throw new Error('error');
}).catch(function (errors) {
assert.deepEqual('object', typeof errors)
});
});
});
});
|
export function getDisplayName(Component)
{
return Component.displayName || Component.name || 'Component'
}
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var Class = require('../../utils/Class');
/**
* @classdesc
* Contains information about a specific button on a Gamepad.
* Button objects are created automatically by the Gamepad as they are needed.
*
* @class Button
* @memberOf Phaser.Input.Gamepad
* @constructor
* @since 3.0.0
*
* @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Button belongs to.
* @param {integer} index - The index of this Button.
*/
var Button = new Class({
initialize:
function Button (pad, index)
{
/**
* A reference to the Gamepad that this Button belongs to.
*
* @name Phaser.Input.Gamepad.Button#pad
* @type {Phaser.Input.Gamepad.Gamepad}
* @since 3.0.0
*/
this.pad = pad;
/**
* An event emitter to use to emit the button events.
*
* @name Phaser.Input.Gamepad.Button#events
* @type {Phaser.Events.EventEmitter}
* @since 3.0.0
*/
this.events = pad.manager;
/**
* The index of this Button.
*
* @name Phaser.Input.Gamepad.Button#index
* @type {integer}
* @since 3.0.0
*/
this.index = index;
/**
* Between 0 and 1.
*
* @name Phaser.Input.Gamepad.Button#value
* @type {number}
* @default 0
* @since 3.0.0
*/
this.value = 0;
/**
* Can be set for analogue buttons to enable a 'pressure' threshold,
* before a button is considered as being 'pressed'.
*
* @name Phaser.Input.Gamepad.Button#threshold
* @type {number}
* @default 1
* @since 3.0.0
*/
this.threshold = 1;
/**
* Is the Button being pressed down or not?
*
* @name Phaser.Input.Gamepad.Button#pressed
* @type {boolean}
* @default false
* @since 3.0.0
*/
this.pressed = false;
},
/**
* Internal update handler for this Button.
* Called automatically by the Gamepad as part of its update.
*
* @method Phaser.Input.Gamepad.Button#update
* @private
* @since 3.0.0
*
* @param {number} value - The GamepadButton value.
*/
update: function (value)
{
this.value = value;
var pad = this.pad;
var index = this.index;
if (value >= this.threshold)
{
if (!this.pressed)
{
this.pressed = true;
this.events.emit('down', pad, this, value);
this.pad.emit('down', index, value, this);
}
}
else if (this.pressed)
{
this.pressed = false;
this.events.emit('up', pad, this, value);
this.pad.emit('up', index, value, this);
}
},
/**
* Destroys this Button instance and releases external references it holds.
*
* @method Phaser.Input.Gamepad.Button#destroy
* @since 3.10.0
*/
destroy: function ()
{
this.pad = null;
this.events = null;
}
});
module.exports = Button;
|
'use strict';
/* global TicTacToeGameBoard */
describe('Tic tac toe game',function() {
var game;
beforeEach(function() {
game = TicTacToeGameBoard();
});
it('should set an item to the board', function() {
game.initializeGameboard(new Array(9));
var result = game.play(0,TicTacToeGameBoard.X);
expect(game.valueAt(0)).toBe(TicTacToeGameBoard.X);
expect(result).toBe(true);
});
it('should not set an item on the board if already taken', function() {
game.initializeGameboard([TicTacToeGameBoard.O,'','','','','','','','']);
var result = game.play(0,TicTacToeGameBoard.X);
expect(game.valueAt(0)).toBe(TicTacToeGameBoard.O);
expect(result).toBe(false);
});
});
|
const five = require('johnny-five');
const BeagleBone = require('beaglebone-io');
const express = require('express');
const SocketIO = require('socket.io');
const path = require('path');
const http = require('http');
const os = require('os');
const app = new express();
const server = new http.Server(app);
const socket = new SocketIO(server);
app.use(express.static(path.join(__dirname, '/app')));
const board = new five.Board({
io: new BeagleBone(),
repl: false
});
board.on('ready', () => {
const weatherSensor = new five.Multi({
controller: 'BMP180',
freq: 5000
});
socket.on('connection', client => {
weatherSensor.on('change', () => {
client.emit('weather', {
temperature: weatherSensor.thermometer.F,
pressure: (weatherSensor.barometer.pressure * 10)
});
});
});
server.listen(80, () => {
console.log(`http://${os.networkInterfaces().eth0[0].address}:80`);
});
});
|
var isTracking = true;
var trackertask = null;
function start_tracking(){
// init
console.log("starting tracker...")
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var x_avg = 0, y_avg = 0, count = 0;
var time;
var tracker = new tracking.ObjectTracker('face');
tracker.setInitialScale(2);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.14);
trackertask = tracking.track('#video', tracker, { camera: true });
tracker.on('track', function(event) {
event.data.forEach(function(rect) {
// console.log("rect x: " + rect.x + "; rect y: " + rect.y);
if(count == 0){
x_avg = rect.x;
y_avg = rect.y;
time = new Date().getTime();
}
count++;
if(count >= 5){
count = 0;
x_avg = Math.abs(x_avg - rect.x)/ (new Date().getTime() - time);
y_avg = Math.abs(y_avg - rect.y)/ (new Date().getTime() - time);
audioControl(x_avg,y_avg);
}
});
});
}
function audioControl(x_avg,y_avg){
var threshold = 5.0;
var measure = (x_avg + y_avg) * 150;
console.log("measure: " + measure + ";");
if(!isPlaying){
if( measure > threshold){
play();
}
}
}
|
search_result['3510']=["topic_000000000000086D.html","JobVacancyDetailVm.Salary Property",""];
|
search_result['3088']=["topic_000000000000076C.html","QuestionModel Class",""];
|
const cheerio = require(`cheerio`)
const path = require(`path`)
const fs = require(`fs`)
const _ = require(`lodash`)
module.exports = (htmlPath, pathPrefix) => {
// load index.html to pull scripts/links necessary for proper offline reload
let html
try {
// load index.html to pull scripts/links necessary for proper offline reload
html = fs.readFileSync(path.resolve(htmlPath))
} catch (err) {
// ENOENT means the file doesn't exist, which is to be expected when trying
// to open 404.html if the user hasn't created a custom 404 page -- return
// an empty array.
if (err.code === `ENOENT`) {
return []
} else {
throw err
}
}
// party like it's 2006
const $ = cheerio.load(html)
// holds any paths for scripts and links
const criticalFilePaths = []
$(`
script[src],
link[as=script],
link[as=font],
link[as=fetch],
link[rel=stylesheet],
style[data-href]
`).each((_, elem) => {
const $elem = $(elem)
const url =
$elem.attr(`src`) || $elem.attr(`href`) || $elem.attr(`data-href`)
// Don't cache XML files, or external resources (beginning with // or http)
const blackListRegex = /(\.xml$|^\/\/|^http)/
// check resource URLs from header tags start with the correct prefix
// (these are not page URLs)
if (url && !blackListRegex.test(url) && url.startsWith(`${pathPrefix}/`)) {
criticalFilePaths.push(url.replace(/^\//, ``))
}
})
// Remove the custom prefix (if any) so Workbox can find the files.
// This is added back at runtime (see modifyUrlPrefix in gatsby-node.js) in
// order to serve from the correct location.
return _.uniq(criticalFilePaths).map(url => url.slice(pathPrefix.length))
}
|
angular.module('Aggie')
.filter('strLimit', ['$filter', function($filter) {
return function(input, limit) {
if (input.length <= limit) {
return input;
}
return $filter('limitTo')(input, limit) + '...';
};
}]);
|
angular
.module('starter.app')
.factory('registrationService', registrationService);
registrationService.$inject = ['$http', '$log', 'ENV'];
function registrationService($http, logger, ENV) {
var baseUrl = ENV.apiEndpoint + '/Registrations';
return {
register: register,
getRegistration: getRegistration
};
function register(gameData) {
return $http.post(baseUrl + '/register', gameData)
.then(registerComplete)
.catch(registerFailed);
function registerComplete(response) {
return response.data;
}
function registerFailed(error) {
logger.error('XHR Failed for register.' + error.data);
}
}
function getRegistration(data) {
return $http.post(baseUrl + '/getRegistration', data)
.then(getRegistrationComplete)
.catch(getRegistrationFailed);
function getRegistrationComplete(response) {
return response.data.getRegistration;
}
function getRegistrationFailed(error) {
logger.error('XHR Failed for getRegistration.' + error.data.error.message);
}
}
}
|
var fs = require('fs');
if (fs.existsSync('1.log'))
fs.unlinkSync('1.log');
var stream = fs.createWriteStream('1.log');
var data = createRowData(3000);
function createRowData(rowSize) {
var s1 = '';
for (var s = 0; s < rowSize; s++) {
if (s > 0)
s1 += ',';
s1 += s;
}
s1 += '\n';
return s1;
};
// taken from node.js api docs
function writeBigFile(writer, data, encoding, callback) {
// change to 500000 to see the other exception
var i = 100000;
var last = i;
write();
function write() {
//console.log(i)
var ok = true;
do {
i -= 1;
if (i === 0) {
// last time!
writer.write(data, encoding, callback);
} else {
// see if we should continue, or wait
// don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);
//console.log('rows: %s', last - i);
last = i;
if (i > 0) {
// had to stop early!
// write some more once it drains
writer.once('drain', write);
}
}
}
writeBigFile(stream, data, null, function() {
stream.end(function () {
/************************************************************
this call throws an error and never invokes the callback
*************************************************************/
fs.readFile('1.log', function(err, data) {
console.log(err);
console.log(data ? data.length : 0);
});
});
});
|
/**
* Created by thihdao on 4/30/2016.
*/
angular.module('view2', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view2', {
templateUrl: 'modules/view2/view2.html',
controller: 'View2Ctrl'
});
}])
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'showblocks', 'bg', {
toolbar: 'Показва блокове'
} );
|
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-09-02 using
// generator-karma 0.8.2
module.exports = function(config) {
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-animate/angular-animate.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-touch/angular-touch.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
|
/**
* Created by Alex on 5/30/2015.
*/
var arr = [
2, 1, 2, 3, 4, 8, 6, 7, 4
];
var longestSeq = 0,
currentSeq = 1,
maxSeqNumber = undefined;
for(var index = 0; index < arr.length ; index +=1){
var currentDigit = arr[index];
if(currentDigit == Number(currentDigit)){
if(currentDigit + 1 == arr[index + 1] && arr[index + 1] <= arr.length - 1 && arr[index + 1] == Number(arr[index+1])){
currentSeq += 1;
}
else{
currentSeq = 1;
}
if(currentSeq > longestSeq){
longestSeq = currentSeq;
maxSeqNumber = arr[index] + 1;
}
}
else{
throw new Error("Your arrays does not contain only digits");
}
}
var start = maxSeqNumber - longestSeq + 1;
var result = [];
for(var index = start; index <= maxSeqNumber; index += 1 ){
result.push(index);
}
console.log(result);
|
if(process.env.NODE_ENV === 'production'){
module.exports = require('./prod')
}
else{
module.exports = require('./dev')
}
|
var R = require('../source');
var eq = require('./shared/eq');
describe('into', function() {
var add = R.add;
var isOdd = function(b) { return b % 2 !== 0; };
var addXf = {
'@@transducer/step': add,
'@@transducer/init': R.always(0),
'@@transducer/result': R.identity
};
it('transduces into arrays', function() {
eq(R.into([], R.map(add(1)), [1, 2, 3, 4]), [2, 3, 4, 5]);
eq(R.into([], R.filter(isOdd), [1, 2, 3, 4]), [1, 3]);
eq(R.into([], R.compose(R.map(add(1)), R.take(2)), [1, 2, 3, 4]), [2, 3]);
});
it('transduces into strings', function() {
eq(R.into('', R.map(add(1)), [1, 2, 3, 4]), '2345');
eq(R.into('', R.filter(isOdd), [1, 2, 3, 4]), '13');
eq(R.into('', R.compose(R.map(add(1)), R.take(2)), [1, 2, 3, 4]), '23');
});
it('transduces into objects', function() {
eq(R.into({}, R.identity, [['a', 1], ['b', 2]]), {a: 1, b: 2});
eq(R.into({}, R.identity, [{a: 1}, {b: 2, c: 3}]), {a: 1, b: 2, c: 3});
});
it('dispatches to objects that implement `reduce`', function() {
var obj = {x: [1, 2, 3], reduce: function() { return 'override'; }};
eq(R.into([], R.map(add(1)), obj), 'override');
eq(R.into([], R.filter(isOdd), obj), 'override');
});
it('allows custom transformer', function() {
var intoSum = R.into(addXf);
var add2 = R.map(add(2));
var result = intoSum(add2);
eq(result([1, 2, 3, 4]), 18);
});
});
|
define(["require", "exports"], function (require, exports) {
var Filter = (function () {
function Filter() {
}
Filter.prototype.getBounds = function () {
return null;
};
Filter.prototype.applyFilter = function (ctx, x, y, width, height, targetCtx, targetX, targetY) {
return false;
};
Filter.prototype.toString = function () {
return "[Filter]";
};
Filter.prototype.clone = function () {
return new Filter();
};
return Filter;
})();
return Filter;
});
|
/**
* Keypad directive, display a keypad on the screen. Template for it
* can be include inside the node containing the keypad attribute.
*
* Use of Namespace.js
*
* @author tommy.rochette[followed by the usual sign]universalmind.com
*/
(function () {
"use strict";
/**
* @Class
*/
window.Keypad = function ($scope, $element, $attrs, $rootScope) {
var locked = false,
opened = false,
padId = $attrs.ngKeypad,
body = $('body');
/**
* Initialize Keypad to default settings
* based on attributes.
*/
function init() {
$scope.$on(Key.PRESSED, handleKeyPressed);
$rootScope.$on(Keypad.TOGGLE_LOCKING, handleLockingToggle);
$rootScope.$on(Keypad.TOGGLE_OPENING, handleOpeningToggle);
$rootScope.$on(Keypad.OPEN, handleOpeningToggle);
$rootScope.$on(Keypad.CLOSE, handleOpeningToggle);
$element.addClass("closed");
initScope();
};
/**
* Initialize scope variables
*/
function initScope() {
$scope.close = function () {
close();
}
}
/**
* Triggered when a user press any key on the pad
* check current status then dispatch KEY_PRESSED event.
*
* @param event
* @param key
*/
function handleKeyPressed(event, key) {
if (!locked) {
if (key.indexOf('[') === -1 && key.indexOf(']') === -1) {
$scope.$emit(Keypad.KEY_PRESSED, key, padId);
} else {
$scope.$emit(Keypad.MODIFIER_KEY_PRESSED, key.substring(1, key.length - 1), padId);
}
}
}
/**
* Triggered when a user press any key on the pad
* check current status then dispatch KEY_PRESSED event.
*
* @param event
* @param key
*/
function handleLockingToggle(event, id) {
if (padId === id || !id) {
locked = !locked;
if (locked) {
$element.attr("disabled", "disabled");
} else {
$element.removeAttr("disabled");
}
}
}
/**
* Triggered when a user toggle keypad opening.
*
* @param event
* @param key
*/
function handleOpeningToggle(event, id, params) {
if (padId === id || !id) {
switch (event.name) {
case Keypad.CLOSE:
opened = false;
break;
case Keypad.OPEN:
opened = true;
break;
default:
opened = !opened;
break;
}
if (!opened) {
close();
} else {
open();
applyOptions(params);
}
}
}
function applyOptions(params) {
if (params && params.position) {
$element.css("top", params.position.y);
$element.css("left", params.position.x);
}
}
/**
* Open current pad
*/
function open() {
$element.removeClass("closed");
$scope.$emit(Keypad.OPENED, padId);
autoClose();
applyOptions();
}
/**
* Close current pad
*/
function close() {
opened = false;
$scope.$emit(Keypad.CLOSED, padId);
body.off("click.keypad");
$element.addClass("closed");
}
/**
* Check if the attribute auto-close is set then
* add event for automatic closing.
*
* @param event
* @param key
*/
function autoClose() {
if ($attrs.autoClose) {
//Timeout use to break the event flow.
setTimeout(function () {
body.on("click.keypad", function () {
opened = !opened;
close();
if (!$scope.$$phase) {
$scope.$apply();
}
});
$element.on("click.keypad", cancelEvent);
}, 1);
}
}
/**
* Dummy function to cancel event propagation.
*
* @param event
*/
function cancelEvent(event) {
event.stopPropagation();
}
init();
};
/**
* @Events
*/
Keypad.KEY_PRESSED = "Keypad.KEY_PRESSED";
Keypad.MODIFIER_KEY_PRESSED = "Keypad.MODIFIER_KEY_PRESSED";
Keypad.TOGGLE_LOCKING = "Keypad.TOGGLE_LOCKING";
Keypad.TOGGLE_OPENING = "Keypad.TOGGLE_OPENING";
Keypad.OPENED = "Keypad.OPENED";
Keypad.CLOSED = "Keypad.CLOSED";
Keypad.OPEN = "Keypad.OPEN";
Keypad.CLOSE = "Keypad.CLOSE";
angular.module('ngKeypad')
.directive('ngKeypad', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
new Keypad($scope, $element, $attrs, $rootScope);
}
}
}]);
})();
|
// libs
import React from 'react';
import PropTypes from 'prop-types';
import {reduxForm, Field, submit, reset as formReset} from 'redux-form';
// components
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';
import {
TextField,
} from 'redux-form-material-ui';
class LoginForm extends React.Component {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
pristine: PropTypes.bool.isRequired,
reset: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
};
submit = () => {
this.props.dispatch(submit('loginForm'));
}
render() {
const {handleSubmit, pristine, reset, submitting} = this.props;
return (
<Card>
<CardHeader
title={<h2>Login</h2>}
/>
<CardText>
<form onSubmit={handleSubmit}>
<div>
<Field name="email" component={TextField} hintText="Email" fullWidth />
</div>
<div>
<Field
name="password"
component={TextField}
hintText="Password"
type="password"
fullWidth
/>
</div>
</form>
</CardText>
<CardActions style={{textAlign: 'right'}}>
<RaisedButton label="Reset" disabled={pristine || submitting} onClick={reset} />
<RaisedButton label="Login" primary disabled={submitting} onClick={this.submit} />
</CardActions>
</Card>
);
}
}
const validate = (values) => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
}
if (!values.password) {
errors.password = 'Required';
}
return errors;
};
export default reduxForm({
form: 'loginForm',
validate,
onSubmitSuccess: (result, dispatch) => dispatch(formReset('loginForm')),
})(LoginForm);
|
var utile = require('utile')
, url = require('url')
, debug = require("debug")("graph-store-client")
, Q = require('q')
, jsonld = require('jsonld').promises()
, rest = require('rest')
, Resolver = require('./Resolver')
, StringDecoder = require('string_decoder').StringDecoder
;
var jsonConverter = require("rest/mime/type/application/json");
var textConverter = require("rest/mime/type/text/plain")
var sparqlJsonConverter = {
read: function (str, opts) {
var obj = JSON.parse(str);
return obj.boolean === undefined ? obj.results.bindings : obj.boolean;
},
write: function (obj, opts) {
return JSON.stringify(str);
}
};
var sparqlXmlConverter = {
read: function (str, opts) {
return /(>true<\/)/.test(str);
},
write: function (obj, opts) {
return obj;
}
};
var registry = require("rest/mime/registry");
registry.register("application/ld+json", jsonConverter)
registry.register("application/sparql-results+json", sparqlJsonConverter)
// registry.register("application/sparql-results+xml", sparqlXmlConverter)
registry.register("application/nquads", textConverter)
registry.register("text/x-nquads", textConverter)
registry.register("text/turtle", textConverter)
registry.register("application/sparql-query", textConverter)
registry.register("application/sparql-update", textConverter)
var GraphStoreClient = module.exports = function(endpoint, graphStoreEndpoint){
this.endpoint = endpoint;
this.graphStoreEndpoint = graphStoreEndpoint;
this.ns = new Resolver;
this._request = rest
.wrap(require("rest/interceptor/mime"), {accept: "application/ld+json,application/x-trig,application/sparql-results+json,application/json,*/*", mime: "application/sparql-query"})
.wrap(sparqlInterceptor())
this._del_request = rest
.wrap(sparqlInterceptor())
}
GraphStoreClient.prototype = {
query: function(sparql, bindings){
return this._sparql("application/sparql-query", sparql, bindings)
},
update: function(sparql, bindings){
return this._sparql("application/sparql-update", sparql, bindings)
},
_sparql: function(type, sparql, bindings){
if(bindings && bindings instanceof Object){
for(var i in bindings){
sparql = sparql.replace(new RegExp('(\\?|\\$)('+i+')', 'g'), bindings[i]);
}
}
var prefixes = this.ns.base ? utile.format("BASE <%s>\n", this.ns.base) : "";
for(var i in this.ns.prefixes){
prefixes += utile.format("PREFIX %s <%s>\n", i, this.ns.prefixes[i]);
}
sparql = prefixes + sparql;
debug("Running SPARQL: %s", sparql);
return rest
// .wrap(debugInterceptor())
.wrap(require("rest/interceptor/mime"), {accept: "text/plain,application/ld+json,text/plain,application/sparql-results+json,application/json,*/*", mime: type+";charset=UTF-8"})
.wrap(sparqlInterceptor())
({
path: this.endpoint,
mime: type,
entity: sparql,
headers: {
"Accept-Charset": "utf-8"
}
})
.catch(function(e){
throw new Error("SPARQL Endpoint Error: (" + e.status + ") "+ e.message);
})
},
put: function(iri, graph, type){
var type = type || "text/turtle", self = this;
if(typeof graph == "object"){
var type = "text/x-nquads";
var graph = jsonld.toRDF(graph, {format: 'application/nquads'});
}
return Q.when(graph)
.then(function(graph){
return self._request({
method: "PUT",
path: self.graphStoreEndpoint,
headers: {"Content-Type": type},
params: {graph: url.resolve(self.ns.base, iri)},
entity: graph
});
});
},
post: function(iri, graph, type){
var type = type || "text/turtle", self = this;
if(typeof graph == "object"){
var type = "text/x-nquads";
var graph = jsonld.toRDF(graph, {format: 'application/nquads'});
}
return Q.when(graph)
.then(function(graph){
return self._request({
method: "POST",
path: self.graphStoreEndpoint,
headers: {"Content-Type": type},
params: {graph: url.resolve(self.ns.base, iri)},
entity: graph
});
});
},
delete: function(iri){
return this._del_request({
method: "DELETE",
path: this.graphStoreEndpoint,
params: {graph: url.resolve(this.ns.base, iri)},
});
},
get: function(iri){
return this._request
({
method: "GET",
path: this.graphStoreEndpoint,
params: {graph: url.resolve(this.ns.base, iri)},
});
}
}
function debugInterceptor(){
return require('rest/interceptor')({
response: function (response) {
debug("SPARQL Result Response:", response);
return response;
}
});
}
function sparqlInterceptor(){
return require('rest/interceptor')({
response: function (response) {
if(response.error){
debug("SPARQL response Error", response.error)
return Q.reject(response.error);
}
if (response.status && response.status.code >= 400) {
debug("SPARQL response Code >=400", response.status)
var e = {
message: "SPARQL Endpoint Error:" + response.status.code + " " + response.entity,
stack: "Request:\n" +
JSON.stringify(response.request, null, " ") + "---------\nResponse:" +
response.status.code +"\n" +JSON.stringify(response.headers, null, " ") +
response.entity,
status: response.status.code,
headers: response.headers,
}
return Q.reject(e);
}
var decoder = new StringDecoder('utf8');
var entity = response.entity + ""
entity = unescape(entity.replace(/\\u/g, '%u') );
debug("SPARQL Result Entity:", entity)
return response.headers['Content-Type'].indexOf('text/plain') == 0 ? jsonld.fromRDF(entity, {format: 'application/nquads'}) : response.entity;
}
});
}
String.prototype.iri = function(base, bare){
var v = base ? url.resolve(base, this + "") : this +"";
return bare ? v : "<" + decodeURI(v) + ">";
}
String.prototype.lit = function(){
return '"' + this + '"';
}
|
/*
* TreatJS: Sandbox
* http://proglang.informatik.uni-freiburg.de/treatjs/
*
* Copyright (c) 2014, Proglang, University of Freiburg.
* http://proglang.informatik.uni-freiburg.de/treatjs/
* All rights reserved.
*
* Released under the MIT license
* http://proglang.informatik.uni-freiburg.de/treatjs/license
*
* Author Matthias Keil
* http://www.informatik.uni-freiburg.de/~keilr/
*/
// _ _ _
//| |__ ___| |_ __ ___ _(_)___ _ _
//| '_ \/ -_) ' \/ _` \ V / / _ \ '_|
//|_.__/\___|_||_\__,_|\_/|_\___/_|
// prototype
load("test/behavior/prototype.js");
// decompile
load("test/behavior/decompile.js");
// eval
load("test/behavior/eval.js");
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('../error/errors.controller'),
Article = mongoose.model('Article'),
_ = require('lodash');
/**
* Create a article
*/
exports.create = function(req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Show the current article
*/
exports.read = function(req, res) {
res.json(req.article);
};
/**
* Update a article
*/
exports.update = function(req, res) {
var article = req.article;
article = _.extend(article, req.body);
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Delete an article
*/
exports.delete = function(req, res) {
var article = req.article;
article.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* List of Articles
*/
exports.list = function(req, res) {
Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
/**
* Article middleware
*/
exports.articleByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
if (err) return next(err);
if (!article) {
return res.status(404).send({
message: 'Article not found'
});
}
req.article = article;
next();
});
};
/**
* Article authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.article.user.id !== req.user.id) {
return res.status(403).send({
message: 'User is not authorized'
});
}
next();
};
|
import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
export default function MonthPickerPropsSection() {
return (
<div className="bs-docs-section">
<h3><Anchor id="month-picker-props">属性</Anchor></h3>
<PropTable component="MonthPicker"/>
</div>
);
}
|
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/moderncpp',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
'https://www.youtube.com/iframe_api',
'public/lib/angular-youtube-mb/src/angular-youtube-embed.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
( function( global, $ ){
var $countDownTimeDis = $( "#countDownTimeDis" );
var $plusWorkBtn = $( "#plusWorkBtn" );
var $minusWorkBtn = $( "#minusWorkBtn" );
var kickOutTheJams;
var timeInMilSec;
var paused = true;
var pomodorosFinished = 0;
var startTime;
var differenceTime;
var time;
var arrayOfBGGifs = [
"img/gif1.gif",
"img/gif2.gif",
"img/gif3.gif",
"img/gif4.gif",
"img/gif5.gif",
"img/gif6.gif"
];
//the constructor function
var Timer = function( timeInMilSecW ){
this.timeInMilSecW = timeInMilSecW;
timeInMilSec = timeInMilSecW;
};
Timer.prototype.countItDown = function(){
//used to cache 'this' referring to Timer object, because setInterval executes in global scope thereby changing 'this'
var that = this;
if( !paused ){
startTime = Number( new Date() );
this.tickTock = setInterval( function(){
var nowTime = Number( new Date() );
//calculate then difference between then and now and subtract the DIFFERENCE from time to get a more accurate timer
differenceTime = Math.floor( nowTime - startTime );
time = timeInMilSec - differenceTime;
if( time < 1 ){
that.showMeTheCats();
}
//convert time to min and secs array
var minSecArray = that.convertTime( time );
//pass returned array from minSecArray to be displayed
var timeString = that.createTimeString( minSecArray );
$countDownTimeDis.html( timeString );
nowTime = startTime;
}, 300 );
}
else{
//subtract differenceTime fron timeInMilSec so future calculations make sense
timeInMilSec = timeInMilSec - differenceTime;
clearInterval(this.tickTock);
}
};
Timer.prototype.convertTime = function( time ){
//60000 ms in 1 minute
var minutes = Math.floor( time / 60000 );
//get the remaining seconds which don't make up a minute and convert to secs--1000 ms in 1 sec
var seconds = Math.floor( ( time % 60000 ) / 1000 );
if( minutes < 0 && seconds < 0 ){
minutes = 0;
seconds = 0;
}
return [ minutes, seconds ];
};
Timer.prototype.createTimeString = function( array ){
//add '00' to front and only display the last two digits
return ( ( "00" + array[0] ).slice( -2 ) + ":" + ( "00" + array[1] ).slice( -2 ) );
};
Timer.prototype.showMeTheCats = function(){
//clear old interval
clearInterval(this.tickTock);
timeInMilSec = this.timeInMilSecW;
//reset clock and display kitties
if( !this.kickOutTheJams ){
this.kickOutTheJams = true;
$( "#mainContentArea" ).addClass( "hidden" );
$( "#kPopShowerDiv" ).removeClass( "hidden" );
if( kPopIframeYT ){
kPopIframeYT.playVideo();
}
pomodorosFinished++;
$( "#pomFinCountDis" ).html( pomodorosFinished );
console.log(this);
this.showNotification();
}
};
Timer.prototype.getRandomGif = function(){
var chosenNum = Math.round( Math.random() * ( arrayOfBGGifs.length - 1 ) );
return arrayOfBGGifs[ chosenNum ];
};
Timer.prototype.showNotification = function(){
if( typeof Notification === 'function' ){
if( !this.kickOutTheJams ){
var workNotification = new Notification( "Oppa-modoro Gangnam Style!", {
body: "It's work time! Sugeo hae~!",
icon: "img/psylogo.png"
});
workNotification.onclick = function(){
window.focus();
};
}
else if( this.kickOutTheJams ){
var breakNotification = new Notification( "Oppa-modoro Gangnam Style!", {
body: "You've completed " + pomodorosFinished + " Oppa-modoro(s)! Go saeng haesseo! Time for a quick break!",
icon: "img/psylogo.png"
});
breakNotification.onclick = function(){
window.focus();
};
}
}
};
Timer.prototype.onPauseBtn = function(){
var $pauseBtn = $( "#startPauseBtn" );
var $glyphiconSpan = $( "#startPauseBtn span" );
var that = this;
$pauseBtn.on( "click", function(){
$glyphiconSpan.toggleClass( "glyphicon-play glyphicon-pause" );
if( !paused ){
paused = true;
$plusWorkBtn.prop( "disabled", false );
$minusWorkBtn.prop( "disabled", false );
}
else{
paused = false;
$plusWorkBtn.prop( "disabled", true );
$minusWorkBtn.prop( "disabled", true );
}
that.countItDown();
} );
};
Timer.prototype.onPlusMinusDuration = function(){
var that = this;
$plusWorkBtn.on( "click", function(){
if( that.timeInMilSecW < ( 60000 * 99 ) ){
clearInterval( this.tickTock );
that.timeInMilSecW += 60000;
that.updateDuration();
if( !kickOutTheJams ){
timeInMilSec = that.timeInMilSecW;
var minSecConversion = that.convertTime( timeInMilSec );
minSecConversion = that.createTimeString( minSecConversion );
$countDownTimeDis.html( minSecConversion );
}
}
});
$minusWorkBtn.on( "click", function(){
if( that.timeInMilSecW > 60000 ){
clearInterval( this.tickTock );
that.timeInMilSecW -= 60000;
that.updateDuration();
if( !kickOutTheJams ){
timeInMilSec = that.timeInMilSecW;
var minSecConversion = that.convertTime( timeInMilSec );
minSecConversion = that.createTimeString( minSecConversion );
$countDownTimeDis.html( minSecConversion );
}
}
});
};
Timer.prototype.updateDuration = function(){
var $workTimeCounter = $( "#workTimeCounter" );
var workTimeInMinSec = this.convertTime( this.timeInMilSecW );
workTimeInMinSec = this.createTimeString( workTimeInMinSec );
$workTimeCounter.html( workTimeInMinSec );
};
Timer.prototype.init = function(){
this.onPauseBtn();
this.onPlusMinusDuration();
this.updateDuration();
};
global.Timer = Timer;
})( window, jQuery );
|
const la = require('lazy-ass')
const snapShot = require('snap-shot')
const filter = require('./filter-allowed-updates')
const {clone, equals} = require('ramda')
const {isPrerelease} = require('./utils')
/* global describe, it, afterEach */
describe('filter allowed', () => {
const current = {
q: { name: 'q', version: '1.1.1', type: 'dev' }
}
const available = [ { name: 'q',
versions: [ '1.3.0', '2.0.2', '3.0.0', '3.0.0-alpha', '3.0.0-rc0' ] } ]
const copy = clone(available)
afterEach(() => {
// sanity check to make sure we are not
// mutating the input objects
la(equals(available, copy),
'original available list is unchanged', available, copy)
})
it('detects prerelease', () => {
snapShot(isPrerelease, '3.0.0-alpha', '3.0.0', '0.1.0', '10.0.0-beta.2')
})
it('allows major', () => {
const options = {
allowed: 'major'
}
const allowed = filter(current, available, options)
snapShot({current, options, allowed})
})
it('allows minor', () => {
const options = {
allowed: 'minor'
}
const allowed = filter(current, available, options)
snapShot({current, options, allowed})
})
it('allows patch', () => {
const options = {
allowed: 'patch'
}
const allowed = filter(current, available, options)
snapShot({current, options, allowed})
})
it('allows everything by default', () => {
const options = {}
const allowed = filter(current, available, options)
snapShot({current, options, allowed})
})
it('can custom filter', () => {
const options = {
limit: (name, version) => version === '2.0.2'
}
const allowed = filter(current, available, options)
snapShot({current, options, allowed})
})
})
|
import { fromJS } from 'immutable';
import videosReducer from '../reducer';
describe('videosReducer', () => {
it('returns the initial state', () => {
expect(videosReducer(undefined, {})).toEqual(fromJS({}));
});
});
|
'use strict';
var assert = require('assert');
var ContainerToken = require('../src/containertoken');
var Definition = require('../src/definition');
var Tocken = require('../src/token');
var Container = require('../src/container');
describe('Testing ContainerToken', function() {
var containerToken, token, subtoken;
function getReconizableFn(name) {
return function() {
return name;
};
}
beforeEach(function() {
token = new Tocken(getReconizableFn('token'), 'token');
subtoken = new Tocken(getReconizableFn('subtoken'), 'subtoken');
var subContainerToken = new ContainerToken('sub', new Definition([subtoken]));
containerToken = new ContainerToken(
'Name',
new Definition([
token,
subContainerToken
]),
['dep1', 'dep2']
);
});
it('should include token and subtoken', function() {
assert(containerToken.includes(token.getter));
assert(containerToken.includes(subtoken.getter));
});
it('should have a getter returning a container containing the defined token + the required top dependencies', function() {
var container = containerToken.getter('dep1', 'dep2');
assert(container instanceof Container);
assert.strictEqual(container.get('dep1'), 'dep1');
assert.strictEqual(container.get('dep2'), 'dep2');
assert.strictEqual(container.get('token'), 'token');
assert.strictEqual(container.get('sub').get('subtoken'), 'subtoken');
});
it('should run the container if containing container is running', function() {
var container = containerToken.getter.call({running : true}, 'dep1', 'dep2');
assert(container.running);
});
it('should clone', function() {
var clone = containerToken.clone();
assert.notEqual(clone, containerToken);
assert.equal(containerToken.name, clone.name);
assert.deepEqual(containerToken.require, clone.require);
assert.notEqual(containerToken.definition, clone.definition);
});
});
|
// Download the Node helper library from www.twilio.com/docs/libraries/node#installation
// These identifiers are your accountSid and authToken from
// https://www.twilio.com/console
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.notify
.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.fetch()
.then(credential => console.log(credential.friendlyName))
.done();
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
Ext.define('sisprod.view.OcurrenceProbability.AddOcurrenceProbability', {
extend: 'sisprod.view.base.BaseDataWindow',
alias: 'widget.addOcurrenceProbability',
require: [
'sisprod.view.base.BaseDataWindow'
],
title: 'Add Ocurrence Probability',
messages: {
labels:{
ocurrenceProbabilityName: 'Name',
ocurrenceProbabilityValue: 'Value',
description: 'Description'
}
},
modal: true,
width: 400,
singleAddition: false,
// height: 150,
initComponent: function(){
var me = this;
me.formOptions = {
bodyPadding: 2,
defaults:{
labelWidth: 100,
anchor: '100%'
},
items: [
{
xtype: 'textfield',
grow: true,
name: 'ocurrenceProbabilityName',
maxLength: 255,
fieldLabel: me.messages.labels.ocurrenceProbabilityName,
allowBlank: false,
fieldStyle: {textTransform: 'uppercase'}
},
{
xtype: 'numberfield',
grow: true,
name: 'ocurrenceProbabilityValue',
id: 'ocurrenceProbabilityValue',
fieldLabel: me.messages.labels.ocurrenceProbabilityValue,
anchor: '70%',
allowBlank: false,
minValue: 0,
value: 0
},
{
xtype: 'textareafield',
grow: true,
name: 'description',
id: 'description',
fieldLabel: me.messages.labels.description,
allowBlank: false
}
]
};
me.callParent(arguments);
}
});
|
/*
* Dampen a selection that goes past the beginning or end of a list. This is
* generally used to produce a visual effect of tension as the user tries to
* go further in a direction that has no more items.
*
* Example: suppose `itemCount` is 5, indicating a list of 5 items. The index of
* the last item is 4. If the `selection` parameter is 4.5, the user is trying
* to go past this last item. When a damping function is applied, the resulting
* value will be less than 4.5 (the actual value will be 4.25). When this
* selection state is rendered, the user will see that, each unit distance the
* drag travels has less and less visible effect. This is perceived as tension.
*
* @param {number} selection - A real number indicating a selection position
* @param {number} itemCount - An integer for the number of items in the list
* @returns {number} A real number representing the damped selection value.
*/
export function dampedListSelection(selection, itemCount) {
const bound = itemCount - 1;
let damped;
if (selection < 0) {
// Trying to go past beginning of list. Apply tension from the left edge.
damped = -damping(-selection);
} else if (selection >= bound) {
// Trying to go past end of list. Apply tension from the right edge.
damped = bound + damping(selection - bound);
} else {
// No damping required.
damped = selection;
}
return damped;
}
/*
* Calculate damping as a function of the distance past the minimum/maximum
* values.
*
* We want to asymptotically approach an absolute minimum of 1 unit
* below/above the actual minimum/maximum. This requires calculating a
* hyperbolic function.
*
* See http://www.wolframalpha.com/input/?i=y+%3D+-1%2F%28x%2B1%29+%2B+1
* for the one we use. The only portion of that function we care about is when
* x is zero or greater. An important consideration is that the curve be
* tangent to the diagonal line x=y at (0, 0). This ensures smooth continuity
* with the normal drag behavior, in which the visible sliding is linear with
* the distance the touchpoint has been dragged.
*/
export function damping(x) {
const y = (-1 / (x + 1)) + 1;
return y;
}
|
// @flow
import fs from 'fs';
import childProcess from 'child_process';
import prompt from 'prompt';
export function get(property: Object): Promise<*> {
return new Promise((resolve, reject) =>
prompt.get(property, (err, result) => err ? reject(err) : resolve(result))
);
}
export function exec(command: string): Promise<*> {
return new Promise((resolve, reject) =>
childProcess.exec(command, (err, stdout) => err ? reject(err) : resolve(stdout))
);
}
export function copy(source: string, target: string): Promise<*> {
return new Promise((resolve, reject) => {
const read = fs.createReadStream(source);
const write = fs.createWriteStream(target);
read.on('error', reject);
write.on('error', reject);
write.on('close', resolve);
read.pipe(write);
});
}
|
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/node
// Find your credentials at twilio.com/console
// To set up environmental variables, see http://twil.io/secure
const API_KEY_SID = process.env.TWILIO_API_KEY;
const API_KEY_SECRET = process.env.TWILIO_API_KEY_SECRET;
const ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;
const Twilio = require('twilio');
const client = new Twilio(API_KEY_SID, API_KEY_SECRET, {accountSid: ACCOUNT_SID});
client.video.compositions.
create({
roomSid: 'RMXXXX',
audioSources: 'RTXXXX',
statusCallback: 'http://my.server.org/callbacks',
format: 'mp4'
})
.then(composition =>{
console.log('Created Composition with SID=' + composition.sid);
});
|
exports.register = function (plugin, options, done) {
const server = plugin;
const gatepost = options.gatepost;
const models = {
Forum: require('./models/forum')(gatepost),
Thread: require('./models/thread')(gatepost),
Post: require('./models/post')(gatepost),
Access: require('./models/access')(gatepost),
Change: require('./models/change')(gatepost)
};
plugin.bind(models);
const Forums = require('./controllers/forums')(models);
const Threads = require('./controllers/threads')(models);
const Posts = require('./controllers/posts')(models);
const Access = require('./controllers/access')(models);
const Changes = require('./controllers/changes')(models);
server.auth.strategy('token', 'jwt', {
key: options.jwtKey,
validateFunc: function (decoded, cb) {
var error, credentials = decoded;
if (!credentials) {
return cb(error, false, credentials);
}
return cb(error, true, credentials);
}
})
server.cors = true;
//forum
server.route({ method: 'get', path: '/forums/{forum_id}', config: Forums.get});
server.route({ method: 'get', path: '/forums', config: Forums.list});
server.route({ method: 'get', path: '/forum/tree', config: Forums.getTree});
server.route({ method: 'put', path: '/forums/{forum_id}', config: Forums.update});
server.route({ method: 'post', path: '/forums', config: Forums.create});
server.route({ method: 'delete', path: '/forums/{forum_id}', config: Forums.delete});
server.route({ method: 'get', path: '/forums/{forum_id}/threads', config: Threads.listByForum});
server.route({ method: 'get', path: '/threads', config: Threads.list});
server.route({ method: 'get', path: '/threads/{thread_id}', config: Threads.get});
server.route({ method: 'get', path: '/threads/{thread_id}/posts', config: Posts.listByThread});
server.route({ method: 'post', path: '/threads', config: Threads.create});
server.route({ method: 'put', path: '/threads/{thread_id}', config: Threads.update});
server.route({ method: 'delete', path: '/threads/{thread_id}', config: Threads.delete});
server.route({ method: 'get', path: '/posts', config: Posts.list});
server.route({ method: 'get', path: '/posts/{post_id}', config: Posts.get});
server.route({ method: 'update', path: '/posts/{post_id}', config: Posts.update});
server.route({ method: 'post', path: '/posts', config: Posts.create});
server.route({ method: 'delete', path: '/posts/{post_id}', config: Posts.delete});
server.route({ method: 'post', path: '/access/{user_id}/forum/{forum_id}', config: Access.create});
server.route({ method: 'get', path: '/access/{user_id}/forum/{forum_id}', config: Access.get});
server.route({ method: 'put', path: '/access/{user_id}/forum/{forum_id}', config: Access.update});
server.route({ method: 'get', path: '/changes', config: Changes.listByDateAndUser });
return done();
};
exports.register.attributes = { pkg: require('./package.json') };
|
import _ from 'lodash'
class BindDeploymentId {
constructor(serverless, options) {
this.serverless = serverless
this.hooks = {
'before:aws:package:finalize:mergeCustomProviderResources': this.bindDeploymentId.bind(this)
}
}
bindDeploymentId() {
const template = this.serverless.service.provider.compiledCloudFormationTemplate
// Find the deployment resource
let deploymentId
for (const key of Object.keys(template.Resources)) {
const resource = template.Resources[key]
if (resource.Type === 'AWS::ApiGateway::Deployment') {
deploymentId = key
break
}
}
// Now, replace the reference to the deployment id
const resources = _.get(this.serverless.service, 'resources.Resources', null)
if (resources) {
const variableRegex = new RegExp(_.get(this.serverless.service, 'custom.deploymentId.variableSyntax', '__deployment__'), 'g')
this.serverless.service.resources.Resources = this.replaceDeploymentIdReferences(resources, deploymentId, variableRegex)
const customStages = this.getCustomStages(this.serverless.service)
if (Object.keys(customStages).length > 0) {
// We have custom stages. The deployment will also create a stage, so we'll map
// that to an unused stage instead. The API keys will also need to depend on
// the stage, instead of the deployment
template.Resources = this.fixUpDeploymentStage(template.Resources, deploymentId)
template.Resources = this.fixUpApiKeys(template.Resources, customStages)
}
}
const resourceExtensions = _.get(this.serverless.service, 'resources.extensions', null)
if (resourceExtensions) {
const variableRegex = new RegExp(_.get(this.serverless.service, 'custom.deploymentId.variableSyntax', '__deployment__'), 'g')
this.serverless.service.resources.extensions = this.replaceDeploymentIdReferences(resourceExtensions, deploymentId, variableRegex)
}
}
replaceDeploymentIdReferences(resources, deploymentId, variableRegex) {
return JSON.parse(JSON.stringify(resources).replace(variableRegex, deploymentId))
}
getCustomStages(service) {
const resources = _.get(service, 'resources.Resources', null)
if (!resources) {
return {}
}
return _.pickBy(resources, (resource) => {
return resource.Type === 'AWS::ApiGateway::Stage'
})
}
fixUpDeploymentStage(resources, deploymentId) {
const newResources = _.cloneDeep(resources)
newResources[deploymentId].Properties.StageName = '__unused_stage__'
return newResources
}
fixUpApiKeys(resources, stages) {
const stageKeys = Object.keys(stages)
const stageToDependOn = _.first(stageKeys)
if (stageKeys.length > 1) {
this.serverless.cli.log(`Multiple stages detected. The API keys will depend on ${stageToDependOn}`)
}
return _.mapValues(resources, (resource) => {
if (resource.Type === 'AWS::ApiGateway::ApiKey') {
return { ...resource, DependsOn: stageToDependOn }
}
return resource
})
}
}
exports.default = BindDeploymentId
module.exports = exports.default
|
// From http://stackoverflow.com/questions/22538638/how-to-have-conditional-elements-and-keep-dry-with-facebook-reacts-jsx
export default class If extends React.Component {
constructor(props) {
super(props);
}
render() {
if (this.props.test) {
return this.props.children;
}
else {
return false;
}
}
}
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.8.0 (2021-05-06)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
function Plugin () {
global.add('contextmenu', function () {
console.warn('Context menu plugin is now built in to the core editor, please remove it from your editor configuration');
});
}
Plugin();
}());
|
/**
* Tom Select v2.0.0-rc.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
// https://github.com/andrewrk/node-diacritics/blob/master/index.js
const latin_convert = {
'æ': 'ae',
'ⱥ': 'a',
'ø': 'o'
};
new RegExp(Object.keys(latin_convert).join('|'), 'g');
/**
* Get the index of an element amongst sibling nodes of the same type
*
*/
const nodeIndex = (el, amongst) => {
if (!el) return -1;
amongst = amongst || el.nodeName;
var i = 0;
while (el = el.previousElementSibling) {
if (el.matches(amongst)) {
i++;
}
}
return i;
};
/**
* Plugin: "dropdown_input" (Tom Select)
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*/
function plugin () {
var self = this;
/**
* Moves the caret to the specified index.
*
* The input must be moved by leaving it in place and moving the
* siblings, due to the fact that focus cannot be restored once lost
* on mobile webkit devices
*
*/
self.hook('instead', 'setCaret', new_pos => {
if (self.settings.mode === 'single' || !self.control.contains(self.control_input)) {
new_pos = self.items.length;
} else {
new_pos = Math.max(0, Math.min(self.items.length, new_pos));
if (new_pos != self.caretPos && !self.isPending) {
self.controlChildren().forEach((child, j) => {
if (j < new_pos) {
self.control_input.insertAdjacentElement('beforebegin', child);
} else {
self.control.appendChild(child);
}
});
}
}
self.caretPos = new_pos;
});
self.hook('instead', 'moveCaret', direction => {
if (!self.isFocused) return; // move caret before or after selected items
const last_active = self.getLastActive(direction);
if (last_active) {
const idx = nodeIndex(last_active);
self.setCaret(direction > 0 ? idx + 1 : idx);
self.setActiveItem(); // move caret left or right of current position
} else {
self.setCaret(self.caretPos + direction);
}
});
}
export default plugin;
//# sourceMappingURL=plugin.js.map
|
"use strict";
const api = require('../shared');
module.exports = {
name: 'Iterate N',
description: "Cost to iterate all keys using an iterator of size `n`.",
sizes: [10, 100, 1000, 10000],
benchmarks: {}
};
module.exports.benchmarks['Immutable'] = (keys, order) => {
const h = api.immutableFrom(keys);
return function() {
let done = false
const iterator = h.keys()
while (!done) {
done = iterator.next().done
}
};
};
module.exports.benchmarks['Hachiko'] = (keys, order) => {
const h = api.hachikoFrom(keys);
return function() {
let done = false
const iterator = h.keys()
while (!done) {
done = iterator.next().done
}
};
};
|
import { compact, isEmpty } from 'lodash';
import { LocationType } from '../constants';
export function titleCase(str) {
if (!str) return null;
return str
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
export function buildAddressArray(location, titleCaseText = false) {
if (location && location.type === LocationType.CC_PROVIDER) {
const { address } = location.attributes;
if (!isEmpty(address)) {
return compact([
titleCaseText ? titleCase(address.street) : address.street,
address.appt,
`${titleCaseText ? titleCase(address.city) : address.city}, ${
address.state
} ${address.zip}`,
]);
}
return [];
}
if (location && location.attributes) {
const {
address: { physical: address },
} = location.attributes;
return compact([
titleCaseText ? titleCase(address.address1) : address.address1,
titleCaseText ? titleCase(address.address2) : address.address2,
titleCaseText ? titleCase(address.address3) : address.address3,
`${titleCaseText ? titleCase(address.city) : address.city}, ${
address.state
} ${address.zip}`,
]);
}
return '';
}
const acronyms = ['va', 'cvs'];
export function titleCaseFacilityName(str) {
if (!str) return null;
return str
.toLowerCase()
.split(' ')
.map(
word =>
acronyms.includes(word)
? word.toUpperCase()
: word.charAt(0).toUpperCase() + word.slice(1),
)
.join(' ');
}
|
jsonp({"cep":"39866000","cidade":"Epaminondas Otoni","uf":"MG","estado":"Minas Gerais"});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Configure = exports.Configure = function () {
function Configure() {
_classCallCheck(this, Configure);
this._config = {
keymap: {}
};
}
Configure.prototype.options = function options(obj) {
Object.assign(this._config, obj);
};
Configure.prototype.get = function get(key) {
return this._config[key];
};
Configure.prototype.set = function set(key, val) {
this._config[key] = val;
return this._config[key];
};
return Configure;
}();
|
define(["exports"], function (exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.md5 = md5;
function md5(x, len) {
x[len >> 5] |= 0x80 << len % 32;
x[(len + 64 >>> 9 << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn(b & c | ~b & d, a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn(b & d | c & ~d, a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | ~d), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xFFFF;
}
function bit_rol(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
});
|
var audioContext = new webkitAudioContext()
var ADSR = require('./index')
var attack = addSlider('attack', 0, 0.0001, 0, 10)
var decay = addSlider('decay', 0, 0.0001, 0, 10)
var sustain = addSlider('sustain', 1, 0.0001, 0, 2)
var release = addSlider('release', 0, 0.0001, 0, 10)
var startValue = addSlider('startValue', 0, 0.0001, 0, 2)
var endValue = addSlider('endValue', 0, 0.0001, 0, 2)
function getAdsr(){
var adsr = ADSR(audioContext)
adsr.attack = parseFloat(attack.value)
adsr.decay = parseFloat(decay.value)
adsr.sustain = parseFloat(sustain.value)
adsr.release = parseFloat(release.value)
adsr.startValue = parseFloat(startValue.value)
adsr.endValue = parseFloat(endValue.value)
return adsr
}
addButton('trigger 1s', function(){
var adsr = getAdsr()
var osc = audioContext.createOscillator()
var gain = audioContext.createGain()
osc.connect(gain)
gain.connect(audioContext.destination)
adsr.connect(gain.gain)
osc.start(audioContext.currentTime)
adsr.start(audioContext.currentTime)
var endTime = adsr.stop(audioContext.currentTime+1)
osc.stop(endTime)
})
var releaseHold = null
addButton('trigger hold', function(){
var adsr = getAdsr()
var osc = audioContext.createOscillator()
var gain = audioContext.createGain()
osc.connect(gain)
gain.connect(audioContext.destination)
adsr.connect(gain.gain)
osc.start(audioContext.currentTime)
adsr.start(audioContext.currentTime)
releaseHold = function(){
var endTime = adsr.stop(audioContext.currentTime)
osc.stop(endTime)
}
}, function(){
releaseHold()
})
function addButton(name, down, up){
var button = document.createElement('button')
button.onmousedown = down
button.onmouseup = up
button.textContent = name
document.body.appendChild(button)
}
function addSlider(property, defaultValue, step, min, max){
var container = document.createElement('div')
container.appendChild(document.createTextNode(property))
var label = document.createTextNode(defaultValue)
var slider = document.createElement('input')
slider.type = 'range'
slider.min = min
slider.max = max
slider.value = defaultValue
slider.style.width = '300px'
if (step){
slider.step = step
}
slider.onchange = function(){
label.data = this.value
}
container.appendChild(slider)
container.appendChild(label)
document.body.appendChild(container)
return slider
}
|
Lux.Scene.add = function(obj, ctx)
{
if (_.isUndefined(ctx)) {
ctx = Lux._globals.ctx;
}
var scene = ctx._luxGlobals.scene;
return scene.add(obj);
};
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colorbutton', 'da', {
auto: 'Automatisk',
bgColorTitle: 'Baggrundsfarve',
colors: {
'000': 'Sort',
'800000': 'Mørkerød',
'8B4513': 'Mørk orange',
'2F4F4F': 'Mørk skifer grå',
'008080': 'Turkis',
'000080': 'Marine',
'4B0082': 'Indigo',
'696969': 'Mørkegrå',
B22222: 'Scarlet / Rød',
A52A2A: 'Brun',
DAA520: 'Guld',
'006400': 'Mørkegrøn',
'40E0D0': 'Turkis',
'0000CD': 'Mellemblå',
'800080': 'Lilla',
'808080': 'Grå',
F00: 'Rød',
FF8C00: 'Mørk orange',
FFD700: 'Guld',
'008000': 'Grøn',
'0FF': 'Cyan',
'00F': 'Blå',
EE82EE: 'Violet',
A9A9A9: 'Matgrå',
FFA07A: 'Laksefarve',
FFA500: 'Orange',
FFFF00: 'Gul',
'00FF00': 'Lime',
AFEEEE: 'Mat turkis',
ADD8E6: 'Lyseblå',
DDA0DD: 'Mørkerød',
D3D3D3: 'Lysegrå',
FFF0F5: 'Lavendelrød',
FAEBD7: 'Antikhvid',
FFFFE0: 'Lysegul',
F0FFF0: 'Gul / Beige',
F0FFFF: 'Himmeblå',
F0F8FF: 'Alice blue',
E6E6FA: 'Lavendel',
FFF: 'Hvid',
'1ABC9C': 'Stærk cyan',
'2ECC71': 'Smaragd',
'3498DB': 'Klar blå',
'9B59B6': 'Ametyst',
'4E5F70': 'Glålig blå',
'F1C40F': 'Klar gul',
'16A085': 'Mørk cyan',
'27AE60': 'Mørk smaragd',
'2980B9': 'Stærk blå',
'8E44AD': 'Mørk violet',
'2C3E50': 'Mat blå',
'F39C12': 'Orange',
'E67E22': 'Gulerod',
'E74C3C': 'Bleg rød',
'ECF0F1': 'Klar sølv',
'95A5A6': 'Lys grålig cyan',
'DDD': 'Lys grå',
'D35400': 'Græskar',
'C0392B': 'Stærk rød',
'BDC3C7': 'Sølv',
'7F8C8D': 'Glålig cyan',
'999': 'Mørk grå'
},
more: 'Flere farver...',
panelTitle: 'Farver',
textColorTitle: 'Tekstfarve'
} );
|
(function ($) {
Drupal.behaviors.e_text_styles = {
attach: function(context, settings) {
$(document).ready(function() {
CKEDITOR.stylesSet.add("default", [{name:"Red1 Title", element:"h3", styles:{color:"Red"}}]);
CKEDITOR.stylesSet.add("default", [{name:"Red2 Title", element:"h3", styles:{color:"Red"}}]);
CKEDITOR.stylesSet.add("default", [{name:"Red2 Title", element:"h3", styles:{color:"Red"}}]);
CKEDITOR.stylesSet.add("default", [{name:"Red3 Title", element:"h3", styles:{color:"Red"}}]);
});
}
};
})(jQuery);
|
/**
* @version $Id: validation.js 552 2010-10-28 19:41:51Z stian $
* @category Koowa
* @package Koowa_Media
* @subpackage Javascript
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.koowa.org
*/
/**
* Form validation class
*/
NinjaValidate = new Class({
options: {
toolbar: 'a.toolbar',
filter: 'post',
form: 'adminForm',
isValid: false,
msg: 'Select an item to @{action} first.',
onValidateForm: function(){
var els = $(this.options.form).getElements('input.required', 'select.required', 'textarea.required');
var filtered = els.filter(function(el){
if (el.getValue() == '' || (el.getTag() == 'select' && el.value == '')) {
el.fireEvent('onInvalid');
return false;
} else {
return true;
}
});
this.options.isValid = els.length == filtered.length;
},
onValidateGrid: function(el){
if($(this.options.form).getElements('.id').filterByAttribute('checked').length > 0) this.options.isValid = true;
else alert(this.options.msg.replace('@{action}', el.getText().toLowerCase()));
},
onSuccess: function(el){
$each(Json.evaluate(el.getProperty('rel')), function(val, key){
new Element('input', {type: 'hidden', name: key, value: val}).inject($(this.options.form));
}.bind(this));
$(this.options.form).submit();
},
onFormToolbar: function(event){
//console.log(event);
},
onGridToolbar: function(event){
var ids = $(this.options.form).getElements('input').filterByAttribute('name', '=', 'id[]').filterByAttribute('checked');
if(ids.length === 0) $$(this.options.toolbar).filterByAttribute('href', '=', '#').addClass('invalid');
else $$(this.options.toolbar).filterByAttribute('href', '=', '#').removeClass('invalid');
},
onFailure: Class.empty
},
initialize: function(type, options){
this.setOptions(options);
this.type = type || 'grid';
this.options.form.addEvent('click', function(event){
this.fireEvent('on' + this.type.capitalize() + 'Toolbar', event);
}.bindWithEvent(this));
$$(this.options.toolbar).filterByClass(this.options.filter).each(function(el){
el.addEvent('click', function(event){
if(!el.hasClass('disabled')){
if(el.hasClass('validate')) this.fireEvent('onValidate'+this.type.capitalize(), el);
if(!el.hasClass('validate') || this.options.isValid) this.fireEvent('onSuccess', el);
} else {
(new Event(event)).stop();
}
}.bind(this));
}.bind(this));
if (this.options.initialize) this.options.initialize.call(this);
}
});
NinjaValidate.implement(new Events, new Options);
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
validate: function(type, options){
new NinjaValidate(type, $merge({form: this}, options));
return this;
}
});
|
var cmsDictionary = {
cms_text_sure: 'Вы уверены?',
}
|
require('./XHRProxy');
var callbackList = {};
class AppsAPI {
static addEventListener() {
window.addEventListener('message', (e) => {
var data = JSON.parse(e.data);
var isGoodCallback =
data.__callback && typeof callbackList[data.__callback] == 'function';
if(isGoodCallback) {
callbackList[data.__callback](data.data);
delete callbackList[data.__callback];
}
})
}
static query(params, callback) {
var callbackId = new Date().getTime();
callbackList[callbackId] = callback;
params.__callback = callbackId;
params.__name = window.name;
//params.type = "get";
window.parent.postMessage(JSON.stringify(params), document.location.origin)
}
static get(name, callback) {
var q = {
query: name,
type: 'get'
};
AppsAPI.query(q, callback);
}
static set(name, data, callback) {
var q = {
query: name,
type: 'set',
data: data
};
AppsAPI.query(q, callback);
}
static init() {
AppsAPI.addEventListener()
}
}
AppsAPI.init();
global.AppsAPI = AppsAPI;
|
/**
* adminSalesDateWatcherService.
* @file adminSalesDateWatcherService.js.
* @copyright Copyright © Lunch-Time 2014
*/
define(['underscore'], function(_) {
'use strict';
var adminSalesDateWatcherService = [
'$interval', '$route',
function ($interval, $route) {
var interval = 60 * 1000;
return {
/** Promise for interval. */
intervalPromise: null,
/** Current date. */
date: null,
/** Watch for date change. */
watch: function() {
this.date = new Date();
this.intervalPromise = $interval(_.bind(this._checkDate, this), interval);
},
/** Dispose watcher. */
dispose: function () {
this.date = null;
if (this.intervalPromise) {
$interval.cancel(this.intervalPromise);
this.intervalPromise = null;
}
},
/** Check for date change and reload route if date was changed. */
_checkDate: function() {
var currentDate = new Date();
var isDateChanged = currentDate.getDate() !== this.date.getDate() ||
currentDate.getMonth() !== this.date.getMonth() ||
currentDate.getFullYear() !== this.date.getFullYear();
if (isDateChanged) {
this.date = currentDate;
$route.reload();
}
}
};
}
];
return adminSalesDateWatcherService;
});
|
/* 遊戲記錄 數據 進度 */
//遊戲記錄
dark.e_save._init_record = function(){
var record = {};
//結構定義 角色記錄
record.create_role = function(id,sid,lv){
var instance = {};
if(lv == undefined){
lv = 1;
}
//唯一標識符
instance.id = id;
//資源id
instance.sid = sid;
//角色等級
instance.lv = lv;
//當前 經驗
instance.exp = 0;
return instance;
};
record._roles = [
record.create_role(ROLE_ID_MAIN,5 * 21 + 3),
record.create_role(ROLE_ID_YAN13,5 * 21 + 6),
record.create_role(ROLE_ID_CAOBIN,1 * 21 + 6),
];
record.roles = function(){
return this._roles;
};
//記錄名
record._name = {};
record.name = function(str){
if(str == undefined){
return record._name;
}
record._name = str;
};
//難度
record.DIFFICULTY_GOD = 0;
record.DIFFICULTY_MANKIND = 1;
record.DIFFICULTY_FAIRYTALE = 2;
record._difficulty = record.DIFFICULTY_GOD;
record.difficulty = function(n){
if(n == undefined){
return _difficulty;
}
record._difficulty = n;
};
//記錄狀態
record.STATUS_DRAMA = 0; //執行劇本
record.STATUS_WAR = 1; //戰前準備
record.STATUS_MAP = 2; //戰鬥中
record._status = record.STATUS_DRAMA;
//保存當前關卡信息
//record._info
//設置 執行劇本
record.set_drama = function(name){
if(name == undefined){
name = record._info.name;
}
var obj = {};
obj.name = name;
record._info = obj;
record._status = this.STATUS_DRAMA;
};
//設置 戰前準備
record.set_war = function(name){
if(name == undefined){
name = record._info.name;
}
var obj = {};
obj.name = name;
record._info = obj;
record._status = this.STATUS_WAR;
};
//設置 地圖
record.set_map = function(name){
if(name == undefined){
name = record._info.name;
}
var obj = {};
obj.name = name;
record._info = obj;
record._status = this.STATUS_MAP;
};
//返回 當前 關卡 信息
record.get_info = function(){
return record._info;
};
this._record = record;
};
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Sebastian Werner (wpbasti)
* Andreas Ecker (ecker)
************************************************************************ */
qx.Class.define("qx.legacy.theme.manager.Border",
{
type : "singleton",
extend : qx.legacy.util.ValueManager,
/*
*****************************************************************************
PROPERTIES
*****************************************************************************
*/
properties :
{
/** the currently selected border theme */
borderTheme :
{
check : "Theme",
nullable : true,
apply : "_applyBorderTheme",
event : "changeBorderTheme"
}
},
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :
{
/**
* Returns the dynamically interpreted result for the incoming value
*
* @param value {String} dynamically interpreted idenfier
* @return {var} return the (translated) result of the incoming value
*/
resolveDynamic : function(value) {
return value instanceof qx.legacy.ui.core.Border ? value : this._dynamic[value];
},
/**
* Whether a value is interpreted dynamically
*
* @param value {String} dynamically interpreted idenfier
* @return {Boolean} returns true if the value is interpreted dynamically
*/
isDynamic : function(value) {
return value && (value instanceof qx.legacy.ui.core.Border || this._dynamic[value] !== undefined);
},
/**
* Sync dependend objects with internal database
*
* @return {void}
*/
syncBorderTheme : function() {
this.updateAll();
},
_applyBorderTheme : function(value)
{
var dest = this._dynamic;
for (var key in dest)
{
if (dest[key].themed)
{
dest[key].dispose();
delete dest[key];
}
}
if (value)
{
var source = value.borders;
var border = qx.legacy.ui.core.Border;
for (var key in source)
{
dest[key] = (new border).set(source[key]);
dest[key].themed = true;
}
}
if (qx.legacy.theme.manager.Meta.getInstance().getAutoSync()) {
this.syncBorderTheme();
}
}
}
});
|
var searchData=
[
['main',['main',['../df/d0a/main_8cpp.html#a0ddf1224851353fc92bfbff6f499fa97',1,'main.cpp']]],
['mkdir',['mkdir',['../de/d0a/namespace_survival.html#a8e83b61c7e186a1a6d5702bcdab6675e',1,'Survival']]]
];
|
/*
* Copyright (C) 2009-2015 Pivotal Software, Inc
*
* This program is is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
({"buttonSet":"تحديد","insertTableTitle":"ادراج جدول","insertTableRowAfterLabel":"اضافة صف بعد","center":"توسيط","deleteTableColumnLabel":"حذف عمود","right":"لليمين","insertTableColumnBeforeLabel":"اضافة عمود قبل","tableWidth":"عرض الجدول:","buttonInsert":"ادراج","default":"المفترض","align":"محاذاة:","insertTableRowBeforeLabel":"اضافة صف قبل","cellSpacing":"تباعد الخانة:","pixels":"عنصر صورة","selectTableLabel":"تحديد جدول","rows":"الصفوف:","modifyTableTitle":"تعديل جدول","cellPadding":"ملء الخانة:","deleteTableRowLabel":"حذف صف","backgroundColor":"لون الخلفية:","insertTableColumnAfterLabel":"اضافة عمود بعد","left":"لليسار","borderThickness":"سمك الحدود","columns":"الأعمدة:","percent":"نسبة مئوية","borderColor":"لون الحدود:"})
|
navHover = function() {
var lis1 = document.getElementById("menu-nav").getElementsByTagName("LI");
for (var i=0; i<lis1.length; i++) {
lis1[i].onmouseover=function() {
this.className+=" sfhover";
}
lis1[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", navHover);
|
/**
* Internal dependencies
*/
import {
DONE_CREATE,
DONE_CREATE_FAILURE,
DONE_DELETE,
DONE_UPDATE,
DONES_REQUEST,
REQUEST,
} from 'state/action-types';
import { translate } from 'lib/i18n';
import { displayErrorNotice } from 'state/notices/actions';
import { receiveDones, updateDone } from 'state/dones/actions';
export default {
[ DONES_REQUEST ]( action ) {
const { query } = action;
return {
type: REQUEST,
path: '/dones/v1/dones',
query,
success: ( { body, headers } ) =>
receiveDones(
body,
query,
Number( headers[ 'x-wp-totalpages' ] ) || null
),
};
},
[ DONE_CREATE ]( action ) {
const { date, text, done, transientId } = action;
return {
type: REQUEST,
path: '/dones/v1/dones',
params: {
method: 'POST',
body: { date, text, done },
},
success( { body } ) {
return updateDone( body.id, text, done, transientId );
},
failure() {
return {
type: DONE_CREATE_FAILURE,
transientId,
};
},
};
},
[ DONE_CREATE_FAILURE ]() {
return displayErrorNotice(
translate( 'An error occurred while saving' )
);
},
[ DONE_DELETE ]( action ) {
const { id } = action;
return {
type: REQUEST,
path: `/dones/v1/dones/${ id }`,
params: {
method: 'DELETE',
},
};
},
[ DONE_UPDATE ]( action ) {
const { id, text, done, replaceId } = action;
// Network request only when not replacing an existing done (i.e. in
// case that creation completes)
if ( replaceId ) {
return;
}
return {
type: REQUEST,
path: `/dones/v1/dones/${ id }`,
params: {
method: 'PUT',
body: { text, done },
},
};
},
};
|
/*
+-----------------------------------------------------------------------+
| RoundCube editor js library |
| |
| This file is part of the RoundCube web development suite |
| Copyright (C) 2006, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Eric Stadtherr <estadtherr@gmail.com> |
+-----------------------------------------------------------------------+
$Id: editor.js 000 2006-05-18 19:12:28Z roundcube $
*/
// Initialize HTML editor
function rcmail_editor_init(skin_path, editor_lang, spellcheck, mode)
{
if (mode == 'identity')
tinyMCE.init({
mode : 'textareas',
editor_selector : 'mce_editor',
apply_source_formatting : true,
theme : 'advanced',
language : editor_lang,
content_css : skin_path + '/editor_content.css',
theme_advanced_toolbar_location : 'top',
theme_advanced_toolbar_align : 'left',
theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,separator,outdent,indent,charmap,hr,link,unlink,code,forecolor',
theme_advanced_buttons2 : ',fontselect,fontsizeselect',
theme_advanced_buttons3 : '',
relative_urls : false,
remove_script_host : false,
gecko_spellcheck : true
});
else // mail compose
tinyMCE.init({
mode : 'textareas',
editor_selector : 'mce_editor',
accessibility_focus : false,
apply_source_formatting : true,
theme : 'advanced',
language : editor_lang,
plugins : 'emotions,media,nonbreaking,table,searchreplace,visualchars,directionality' + (spellcheck ? ',spellchecker' : ''),
theme_advanced_buttons1 : 'bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,outdent,indent,separator,link,unlink,emotions,charmap,code,forecolor,backcolor,fontselect,fontsizeselect, separator' + (spellcheck ? ',spellchecker' : '') + ',undo,redo,image,media,ltr,rtl',
theme_advanced_buttons2 : '',
theme_advanced_buttons3 : '',
theme_advanced_toolbar_location : 'top',
theme_advanced_toolbar_align : 'left',
extended_valid_elements : 'font[face|size|color|style],span[id|class|align|style]',
content_css : skin_path + '/editor_content.css',
external_image_list_url : 'program/js/editor_images.js',
spellchecker_languages : (rcmail.env.spellcheck_langs ? rcmail.env.spellcheck_langs : 'Dansk=da,Deutsch=de,+English=en,Espanol=es,Francais=fr,Italiano=it,Nederlands=nl,Polski=pl,Portugues=pt,Suomi=fi,Svenska=sv'),
gecko_spellcheck : true,
relative_urls : false,
remove_script_host : false,
rc_client: rcmail,
oninit : 'rcmail_editor_callback'
});
}
// react to real individual tinyMCE editor init
function rcmail_editor_callback(editor)
{
var input_from = rcube_find_object('_from');
if (input_from && input_from.type=='select-one')
rcmail.change_identity(input_from);
// set tabIndex
rcmail_editor_tabindex()
}
// set tabIndex on tinyMCE editor
function rcmail_editor_tabindex()
{
if (rcmail.env.task == 'mail') {
var editor = tinyMCE.get(rcmail.env.composebody);
var textarea = editor.getElement();
var node = editor.getContentAreaContainer().childNodes[0];
if (textarea && node)
node.tabIndex = textarea.tabIndex;
}
}
// switch html/plain mode
function rcmail_toggle_editor(ishtml, textAreaId, flagElement)
{
var composeElement = document.getElementById(textAreaId);
var flag;
if (ishtml)
{
rcmail.display_spellcheck_controls(false);
rcmail.plain2html(composeElement.value, textAreaId);
tinyMCE.execCommand('mceAddControl', true, textAreaId);
rcmail_editor_tabindex();
if (flagElement && (flag = rcube_find_object(flagElement)))
flag.value = '1';
}
else
{
if (!confirm(rcmail.get_label('editorwarning')))
return false;
var thisMCE = tinyMCE.get(textAreaId);
var existingHtml = thisMCE.getContent();
rcmail.html2plain(existingHtml, textAreaId);
tinyMCE.execCommand('mceRemoveControl', true, textAreaId);
rcmail.display_spellcheck_controls(true);
if (flagElement && (flag = rcube_find_object(flagElement)))
flag.value = '0';
}
};
|
/**
* node-compress-commons
*
* Copyright (c) 2014 Chris Talkington, contributors.
* Licensed under the MIT license.
* https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT
*/
var zipUtil = require( './util' );
var DATA_DESCRIPTOR_FLAG = 1 << 3;
var ENCRYPTION_FLAG = 1 << 0;
var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;
var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;
var STRONG_ENCRYPTION_FLAG = 1 << 6;
var UFT8_NAMES_FLAG = 1 << 11;
var GeneralPurposeBit = module.exports = function() {
if( !(this instanceof GeneralPurposeBit) ) {
return new GeneralPurposeBit();
}
this.descriptor = false;
this.encryption = false;
this.utf8 = false;
this.numberOfShannonFanoTrees = 0;
this.strongEncryption = false;
this.slidingDictionarySize = 0;
return this;
};
GeneralPurposeBit.prototype.encode = function() {
return zipUtil.getShortBytes(
(this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) |
(this.utf8 ? UFT8_NAMES_FLAG : 0) |
(this.encryption ? ENCRYPTION_FLAG : 0) |
(this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0)
);
};
GeneralPurposeBit.prototype.parse = function( buf, offset ) {
var flag = zipUtil.getShortBytesValue( buf, offset );
var gbp = new GeneralPurposeBit();
gbp.useDataDescriptor( (flag & DATA_DESCRIPTOR_FLAG) !== 0 );
gbp.useUTF8ForNames( (flag & UFT8_NAMES_FLAG) !== 0 );
gbp.useStrongEncryption( (flag & STRONG_ENCRYPTION_FLAG) !== 0 );
gbp.useEncryption( (flag & ENCRYPTION_FLAG) !== 0 );
gbp.setSlidingDictionarySize( (flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096 );
gbp.setNumberOfShannonFanoTrees( (flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2 );
return gbp;
};
GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function( n ) {
this.numberOfShannonFanoTrees = n;
};
GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() {
return this.numberOfShannonFanoTrees;
};
GeneralPurposeBit.prototype.setSlidingDictionarySize = function( n ) {
this.slidingDictionarySize = n;
};
GeneralPurposeBit.prototype.getSlidingDictionarySize = function() {
return this.slidingDictionarySize;
};
GeneralPurposeBit.prototype.useDataDescriptor = function( b ) {
this.descriptor = b;
};
GeneralPurposeBit.prototype.usesDataDescriptor = function() {
return this.descriptor;
};
GeneralPurposeBit.prototype.useEncryption = function( b ) {
this.encryption = b;
};
GeneralPurposeBit.prototype.usesEncryption = function() {
return this.encryption;
};
GeneralPurposeBit.prototype.useStrongEncryption = function( b ) {
this.strongEncryption = b;
};
GeneralPurposeBit.prototype.usesStrongEncryption = function() {
return this.strongEncryption;
};
GeneralPurposeBit.prototype.useUTF8ForNames = function( b ) {
this.utf8 = b;
};
GeneralPurposeBit.prototype.usesUTF8ForNames = function() {
return this.utf8;
};
|
// -*- mode: js2; indent-tabs-mode: nil; js2-basic-offset: 8 -*-
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const Gettext = imports.gettext.domain('gnome-shell-extension-pidgin');
const _ = Gettext.gettext;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;
function init() {
Convenience.initTranslations();
}
const PidginPrefsWidget = new GObject.Class({
Name: 'Pidgin.Prefs.Widget',
GTypeName: 'PidginPrefsWidget',
Extends: Gtk.Grid,
_init: function(params) {
this.parent(params);
this.row_spacing = 10;
this._settings = Convenience.getSettings();
this.margin = 24;
this.spacing = 30;
let msg_label = new Gtk.Label({
label: _('Message tray integration'),
hexpand: true,
halign: Gtk.Align.START});
let msg_checkbox = new Gtk.Switch({
halign: Gtk.Align.END});
msg_checkbox.set_active(this._settings.get_boolean('enable-message-tray'));
msg_checkbox.connect(
'notify::active',
Lang.bind(this, function(check) {
this._settings.set_boolean('enable-message-tray', check.get_active());
})
);
this.attach(msg_label, 0, 1, 1, 1);
this.attach(msg_checkbox, 1, 1, 1, 1);
let buddy_label = new Gtk.Label({
label: _('Buddies search provider'),
hexpand: true,
halign: Gtk.Align.START});
let buddy_checkbox = new Gtk.Switch({
halign: Gtk.Align.END});
buddy_checkbox.set_active(this._settings.get_boolean('enable-search-provider'));
buddy_checkbox.connect(
'notify::active',
Lang.bind(this, function(check) {
this._settings.set_boolean('enable-search-provider', check.get_active());
})
);
this.attach(buddy_label, 0, 2, 1, 1);
this.attach(buddy_checkbox, 1, 2, 1, 1);
let chat_hl_label = new Gtk.Label({
label: _('Track only highlighted messages for chats'),
hexpand: true,
halign: Gtk.Align.START});
let chat_hl_checkbox = new Gtk.Switch({
halign: Gtk.Align.END});
chat_hl_checkbox.set_active(this._settings.get_boolean('chat-highlight-only'));
chat_hl_checkbox.connect(
'notify::active',
Lang.bind(this, function(check) {
this._settings.set_boolean('chat-highlight-only', check.get_active());
})
);
this.attach(chat_hl_label, 0, 3, 1, 1);
this.attach(chat_hl_checkbox, 1, 3, 1, 1);
},
});
function buildPrefsWidget() {
let widget = new PidginPrefsWidget();
widget.show_all();
return widget;
}
|
import React from 'react';
import ActionStore from 'material-ui/svg-icons/action/store';
import Email from 'material-ui/svg-icons/communication/email';
import Info from 'material-ui/svg-icons/action/info';
import Loyalty from 'material-ui/svg-icons/action/loyalty';
import Person from 'material-ui/svg-icons/social/person';
import Phone from 'material-ui/svg-icons/communication/phone';
import IconTextFieldRow from '../lib/formTable/IconTextFieldRow';
import { TiposID } from 'facturacion_common/src/Models.js';
const tiposIDSource = Object.keys(TiposID).map(key => ({
text: TiposID[key],
value: key
}));
export default class NuevoClienteForm extends React.Component {
render() {
const { editar, errors, inputs, updateData } = this.props;
const tipoInput = {
hintText: 'Tipo de identificación',
icon: Info,
value: inputs.tipoText || '',
errorText: errors.tipo,
dataSource: tiposIDSource,
disabled: editar,
onChange: newText => {
updateData('tipo', newText);
}
};
const idInput = {
hintText: '#ID',
icon: Info,
value: inputs.id || '',
errorText: errors.id,
disabled: editar,
onChange: event => {
updateData('id', event.target.value);
}
};
const telf1Input = {
hintText: 'Teléfono 1',
icon: Phone,
value: inputs.telefono1 || '',
errorText: errors.telefono1,
onChange: event => {
updateData('telefono1', event.target.value);
}
};
const clienteInput = {
hintText: 'Cliente',
icon: Person,
value: inputs.nombre || '',
errorText: errors.nombre,
onChange: event => {
updateData('nombre', event.target.value);
}
};
const telf2Input = {
hintText: 'Teléfono 2',
icon: Phone,
value: inputs.telefono2 || '',
errorText: errors.telefono2,
onChange: event => {
updateData('telefono2', event.target.value);
}
};
const direccionInput = {
hintText: 'Dirección',
icon: ActionStore,
value: inputs.direccion || '',
errorText: errors.direccion,
onChange: event => {
updateData('direccion', event.target.value);
}
};
const emailInput = {
hintText: 'E-mail',
icon: Email,
value: inputs.email || '',
errorText: errors.email,
onChange: event => {
updateData('email', event.target.value);
}
};
const descDefaultInput = {
hintText: 'Descuento recomendado (%)',
icon: Loyalty,
value: inputs.descDefault || '',
errorText: errors.descDefault,
onChange: event => {
updateData('descDefault', event.target.value);
}
};
return (
<table>
<tbody>
<IconTextFieldRow leftInput={tipoInput} rightInput={idInput} />
<IconTextFieldRow leftInput={clienteInput} rightInput={emailInput} />
<IconTextFieldRow leftInput={telf1Input} rightInput={telf2Input} />
<IconTextFieldRow
leftInput={direccionInput}
rightInput={descDefaultInput}
/>
{/* An additional empty row prevents jittering in the dialog */}
<IconTextFieldRow empty={true} />
</tbody>
</table>
);
}
}
NuevoClienteForm.propTypes = {
editar: React.PropTypes.bool.isRequired,
errors: React.PropTypes.object.isRequired,
inputs: React.PropTypes.object.isRequired,
updateData: React.PropTypes.func.isRequired
};
|
'use strict';
// Use local.env.js for environment variables that grunt will set when the server starts locally.
// Use for your api keys, secrets, etc. This file should not be tracked by git.
//
// You will need to set these on the server you deploy to.
module.exports = {
DOMAIN: 'http://localhost:9000',
SESSION_SECRET: "aml-secret",
// Control debug level for modules using visionmedia/debug
DEBUG: ''
};
|
function closeDestroyer() {
if (div = document.getElementById('explorerdestroyer')) {
div.style.display = "none";
}
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 259200000);
setCookie('destroyer','hide',expire)
}
function loadPage() {
var destroyer = getCookie('destroyer');
if (destroyer == 'hide') {
if (div = document.getElementById('explorerdestroyer')) {
div.style.display = "none";
}
}
}
function addComment(parent) {
if (div = document.getElementById('postform')) {
if (div.style.display == "block") {
div.style.display = "none";
} else {
div.style.display = "block";
if (cmt = document.getElementById('gocode')) {
cmt.focus();
}
}
}
if (prt = document.getElementById('parentid')) {
prt.value = parent;
}
}
function sizer(size) {
document.body.style.fontSize = size;
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 259200000);
setCookie('sizer',size,expire);
}
function focuser(inputz) {
inputz.style.backgroundColor = "lightyellow";
}
function blurer(inputz) {
inputz.style.backgroundColor = "#efefef";
}
function comments(c) {
window.open(c, 'n0comments', 'toolbar=yes, directories=no,'
+'status=no, resizable=yes, scrollbars=yes, location=no'
+', dependent, width=400, height=350');
}
function commentsp(c) {
if (window.event && window.event.keyCode == 13) {
return comments(c);
}
}
function emoticon(code) {
x = document.postform.comment;
x.value = x.value + code;
document.postform.comment.focus();
}
function emoticonp(code) {
if (window.event && window.event.keyCode == 13) {
return emoticon(code);
}
}
function closep() {
if (window.event && window.event.keyCode == 13) {
return window.close();
}
}
window.name='n0main';
|
Ext.define('Ext.form.SubmitFix', {
override: 'Ext.ZIndexManager',
register : function(comp) {
var me = this,
compAfterHide = comp.afterHide;
if (comp.zIndexManager) {
comp.zIndexManager.unregister(comp);
}
comp.zIndexManager = me;
me.list[comp.id] = comp;
me.zIndexStack.push(comp);
// Hook into Component's afterHide processing
comp.afterHide = function() {
compAfterHide.apply(comp, arguments);
me.onComponentHide(comp);
};
},
/**
* Unregisters a {@link Ext.Component} from this ZIndexManager. This should not
* need to be called. Components are automatically unregistered upon destruction.
* See {@link #register}.
* @param {Ext.Component} comp The Component to unregister.
*/
unregister : function(comp) {
var me = this,
list = me.list;
delete comp.zIndexManager;
if (list && list[comp.id]) {
delete list[comp.id];
// Relinquish control of Component's afterHide processing
delete comp.afterHide;
Ext.Array.remove(me.zIndexStack, comp);
// Destruction requires that the topmost visible floater be activated. Same as hiding.
me._activateLast();
}
}
});
|
mailer = {
sendMailTemplated: function(email, template) {
this.message = 'success';
}
}
module.exports = mailer;
|
scnShortcodeMeta={
attributes:[
{
label:"Slides",
id:"content",
controlType:"tab-control"
}
],
disablePreview:true,
customMakeShortcode: function(b){
var a=b.data;
var tabTitles = new Array();
if(!a)return"";
var c=a.content;
var r= ' '+b.rotation;
var g = ''; // The shortcode.
for ( var i = 0; i < a.numTabs; i++ ) {
var currentField = 'tle_' + ( i + 1 );
if ( b[currentField] == '' ) {
tabTitles.push( 'Slide ' + ( i + 1 ) );
} else {
var currentTitle = b[currentField];
currentTitle = currentTitle.replace( /"/gi, "'" );
tabTitles.push( currentTitle );
} // End IF Statement
} // End FOR Loop
g += '[text_slider'+r+']<br/><br/>';
for ( var t in tabTitles ) {
g += '[text_slide title="' + tabTitles[t] + '"]' + tabTitles[t] + ' content goes here.[/text_slide] <br/><br/>';
} // End FOR Loop
g += '[/text_slider]';
return g
}
};
|
var searchData=
[
['debuglevelstr',['DebugLevelStr',['../class_logger.html#a30344984f1f6d2a5896a52a4788e8b72',1,'Logger']]]
];
|
function hideAddressBar() {
window.scrollTo(0, 1);
}
function w(what) {
document.write(what)
}
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function g(where) {
var newQS = window.location.search.replace(/t=./, '');
newQS += '&t=' + where;
document.location = newQS;
}
|
$ = jQuery;
$(document).ready( function(){
// If there are many articles on the page, make them images
if( $('.hentry').size() > 1 ){
// Change <article> css by adding a class
// the class makes them shrink and in a grid
$('.hentry').addClass('thumb-hentry');
}
});
|
jQuery(document).ready(function($) {
if (jQuery('.wp-list-table').length > 0)
{
$('.edit a').addClass('button-primary').addClass('button');
$('.trash a').addClass('button-primary').addClass('button');
$('.clone a').addClass('button');
// Script for leads list page
jQuery('.row-actions').each(function() {
var jQuerylist = jQuery(this);
var jQueryfirstChecked = jQuerylist.parent().parent().find('.column-first-name');
if ( !jQueryfirstChecked.html() )
return;
jQuerylist.appendTo(jQueryfirstChecked);
});
jQuery("body").on('click', '.lead-grav-img', function () {
var checked = jQuery(this).parent().parent().find(".check-column input").is(':checked');
if (checked === false) {
jQuery(this).parent().parent().find(".check-column input").attr("checked", "checked");
} else {
jQuery(this).parent().parent().find(".check-column input").removeAttr('checked');
}
});
jQuery('.column-status').each(
function(){
// hide empty fields
if( jQuery(this).text() == "" ) {
jQuery(this).text('New Lead');
jQuery(this).parent().css("background-color", "#e2ffc9").addClass('new-lead-row');
}
if( jQuery(this).text() == "New Lead" ) {
jQuery(this).parent().css("background-color", "#e2ffc9");
}
if( jQuery(this).text() == "Lost" ) {
jQuery(this).parent().css("background-color", "#ffe2e2");
}
if( jQuery(this).text() == "Read" ) {
jQuery(this).parent().css("background-color", "#f2f2f2");
}
if( jQuery(this).text() == "Contacted" ) {
jQuery(this).parent().css("background-color", "#fcf7d1");
}
}
);
jQuery(".submitdelete").text("Delete");
var textchange = jQuery("li.publish").html().replace("Published", "Live");
jQuery('li.publish').html(textchange);
jQuery('.date.column-date').each(function() {
var textchange2 = jQuery(this).html().replace("Published", "");
jQuery(this).html(textchange2);
});
var mark_as_read = '<span class="mark-viewed button" title="Mark lead as viewed">Mark as read</span><span class="mark-viewed-undo button">Undo</span>';
//jQuery(mark_as_read).appendTo(".row-actions");
jQuery(mark_as_read).appendTo(".edit");
jQuery('.mark-viewed, .mark-viewed-undo').each(function() {
var this_lead = jQuery(this).parent().parent().parent().parent().attr("id");
var lead_id = this_lead.replace("post-","");
jQuery(this).attr("id", lead_id);
});
jQuery("body").on('change', '.bulkactions select', function () {
var selected = jQuery(this).val();
console.log(selected);
if (selected != -1) {
jQuery(".alignleft.actions").not('.bulkactions').hide();
jQuery("#wordpress_list_select").hide();
} else {
jQuery(".alignleft.actions").show();
jQuery(".alignleft.actions").show();
jQuery("#doaction").val('Apply');
}
if(selected === "add-to-list") {
jQuery("#wordpress_list_select").show();
jQuery("#doaction").val('Add Selected Leads to List');
setTimeout(function() {
var test = "<span id='add-to-this'>Select List:</span>";
jQuery("#wordpress_list_select").before(test);
}, 100);
} else {
jQuery("#doaction").val('Apply');
jQuery("#add-to-this").remove();
}
});
jQuery('.type-wp-lead').each(function() {
var current_status = jQuery(this).find(".status").text();
if( current_status === "Read" ) {
jQuery(this).find(".mark-viewed").hide();
jQuery(this).find(".mark-viewed-undo").text("Mark as new").css('display', 'inline-block');
}
});
//var move_box = jQuery(".alignleft.actions").first();
//jQuery(".subsubsub").before(move_box);
//var filter_box = "<span class='left-float-filter'>Filter</span>";
//jQuery(".alignleft.actions").eq(1).before(filter_box);
var meta_filter = jQuery('#lead-meta-filter').val();
if(meta_filter != "") {
jQuery(".lead_meta_val").show();
}
jQuery("body").on('change', '#lead-meta-filter', function () {
var meta = jQuery('#lead-meta-filter').val();
if(meta === "") {
jQuery(".lead_meta_val").hide();
} else {
jQuery(".lead_meta_val").show();
}
});
$( '.mark-viewed' ).on( 'click', function() {
// define the bulk edit row
var post_id = jQuery(this).attr("id");
var status = "Read";
jQuery.ajax({
type: 'POST',
url: ajaxurl,
context: this,
data: {
action: 'wp_leads_mark_as_read_save',
j_rules: status,
page_id: post_id
},
success: function(data){
var self = this;
//alert(data);
// jQuery('.lp-form').unbind('submit').submit();
jQuery(self).hide();
jQuery(self).parent().find(".mark-viewed-undo").css('display', 'inline-block');
jQuery(self).parent().parent().parent().parent().css("background-color", "#f2f2f2");
jQuery(self).parent().parent().parent().parent().find(".status").text("Read");
//alert("Changes Saved! Refresh the page to see your changes");
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("Ajax not enabled");
}
});
return false;
});
$( '.mark-viewed-undo' ).on( 'click', function() {
// define the bulk edit row
var post_id = jQuery(this).attr("id");
var status = "Read";
jQuery.ajax({
type: 'POST',
url: ajaxurl,
context: this,
data: {
action: 'wp_leads_mark_as_read_undo',
j_rules: status,
page_id: post_id
},
success: function(data){
var self = this;
//alert(data);
// jQuery('.lp-form').unbind('submit').submit();
jQuery(self).hide();
jQuery(self).parent().find(".mark-viewed").show();
jQuery(self).parent().parent().parent().parent().css("background-color", "#e2ffc9");
jQuery(self).parent().parent().parent().parent().find(".status").text("New Lead");
//alert("Changes Saved! Refresh the page to see your changes");
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("Ajax not enabled");
}
});
return false;
});
}
});
|
$(function()
{
if($("html").width() < 480)
{
windowResize();
setTimeout(function(){$("body,html").animate({ scrollLeft: 3000}, 500);},1500);
}
else
setTimeout(function(){$("body, html").animate({ scrollTop: 3000}, 500);},1500);
setTimeout(function(){$(".abertura").hide();$("#middle-button").animate({opacity: 1},2000)},2000);
$(window).resize(windowResize);
$("button, .dir").click(function(){
pengine.send('http://www.rodrigop.com.br/firestick/server.php',{'send':this.id, 'id': 1});
$(this).blur();
});
$("#middle-button").click(function()
{
trocaTela("joystick", "config");
});
$(".config .btn-layout").click(function()
{
trocaTela("config", "layout");
});
$(".config .btn-voltar").click(function()
{
trocaTela("config", "joystick");
});
$(".config .btn-sobre").click(function()
{
trocaTela("config", "sobre");
});
$(".sobre .btn-voltar").click(function()
{
trocaTela("sobre", "config");
});
$(".layout .btn-voltar").click(function()
{
trocaTela("layout", "config");
});
$(".joystick").css("background-color", "#191919");
$("button, .dir .square").css("background-color", "#0AF");
$(".dir .triangle").css("border-bottom-color", "#0AF");
});
function trocaTela(de,para)
{
$("."+de).fadeOut(200);
$("."+para).fadeIn(500);
}
function windowResize()
{
if($("html").width() < 400)
$("html").css("transform","rotate(-90deg)").height(window.innerWidth).width(window.innerHeight).css("top","15%").css("left","-20%");
else
$("html").css("transform","rotate(0deg)").height("100%").width("100%").css("top",0).css("left",0);
}
function setLayout()
{
}
|
/*=============================================================
Authour URL: www.designbootstrap.com
http://www.designbootstrap.com/
License: MIT
http://opensource.org/licenses/MIT
100% Free To use For Personal And Commercial Use.
IN EXCHANGE JUST TELL PEOPLE ABOUT THIS WEBSITE
======================================================== */
$(document).ready(function () {
/*====================================
SCROLLING SCRIPTS
======================================*/
$('.scroll-me a').bind('click', function (event) { //just pass scroll-me in design and start scrolling
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1200, 'easeInOutExpo');
event.preventDefault();
});
/*====================================
SLIDER SCRIPTS
======================================*/
$('#carousel-slider').carousel({
interval: 2000 //TIME IN MILLI SECONDS
});
/*====================================
VAGAS SLIDESHOW SCRIPTS
======================================*/
$.vegas('slideshow', {
backgrounds: [
{ src: '/static/img/root.png', fade: 1000, delay: 9000 }
]
})('overlay', {
/** SLIDESHOW OVERLAY IMAGE **/
src: '/static/js/vegas/overlays/06.png' // THERE ARE TOTAL 01 TO 15 .png IMAGES AT THE PATH GIVEN, WHICH YOU CAN USE HERE
});
/*====================================
POPUP IMAGE SCRIPTS
======================================*/
$('.fancybox-media').fancybox({
openEffect: 'elastic',
closeEffect: 'elastic',
helpers: {
title: {
type: 'inside'
}
}
});
/*====================================
FILTER FUNCTIONALITY SCRIPTS
======================================*/
$(window).load(function () {
var $container = $('#work-div');
$container.isotope({
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false
}
});
$('.caegories a').click(function () {
$('.caegories .active').removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
$container.isotope({
filter: selector,
animationOptions: {
duration: 750,
easing: 'linear',
queue: false
}
});
return false;
});
});
/*====================================
WRITE YOUR CUSTOM SCRIPTS BELOW
======================================*/
});
|
var bootState = {
preload: function() {
},
create: function() {
game.stage.backgroundColor = '#f7f7f7';
game.physics.startSystem(Phaser.Physics.ARCADE);
game.state.start('load');
}
}
|
jQuery(document).ready(function () {
//clone main menu from header and prepend to footer
/*jQuery('#block-system-main-menu').clone().prependTo( '#footer .region-footer .region-inner' );*/
//header menu
jQuery('#header').wrapInner( '<div id="header-inner"></div>' );
jQuery('.region-header #block-system-main-menu .menu-item-1154, .region-header #block-system-main-menu .menu-item-541, .region-header #block-system-main-menu .menu-item-589, .region-header #block-system-main-menu .menu-item-1155, .region-header #block-system-main-menu .menu-item-514').wrapInner( '<div class="menu-center"></div>' );
jQuery('.region-header #block-system-main-menu .menu-depth-2').wrapInner('<div class="menu-inner-wrap"></div>');
//add - remove class "active" from SERVICE header menu when click
jQuery('.region-header .menu-item-529 span').click(function(){//en
jQuery('.region-header .menu-item-529, .region-header .menu-item-541').toggleClass('active');
jQuery('.region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-514, .region-header .menu-item-588, .region-header .menu-item-1156, .region-header .menu-item-542').removeClass('active');
});
jQuery('.region-header .menu-item-1153 span').click(function(){//ja
jQuery('.region-header .menu-item-1153, .region-header .menu-item-1154').toggleClass('active');
jQuery('.region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-514, .region-header .menu-item-588, .region-header .menu-item-1156, .region-header .menu-item-542').removeClass('active');
});
//remove class "active" from SERVICE header menu when click
jQuery('.region-header .menu-item-541 a').click(function(){//en
jQuery('.region-header .menu-item-541').toggleClass('active');
});
jQuery('.region-header .menu-item-1154 a').click(function(){//ja
jQuery('.region-header .menu-item-1154').toggleClass('active');
});
//add - remove class "active" from COMPANY header menu when click
jQuery('.region-header .menu-item-588 span, .region-header .menu-item-1156 span').click(function(){
jQuery('.region-header .menu-item-588, .region-header .menu-item-1156, .region-header .menu-item-589, .region-header .menu-item-1155').toggleClass('active');
jQuery('.region-header .menu-item-1153, .region-header .menu-item-542, .region-header .menu-item-529, .region-header .menu-item-514, .region-header .menu-item-1154, .region-header .menu-item-541').removeClass('active');
});
//add - remove class "active" from CONTACT header menu when click
jQuery('.region-header .menu-item-542 span').click(function(){//en
jQuery('.region-header .menu-item-542, .region-header .menu-item-514').toggleClass('active');
jQuery('.region-header .menu-item-1154, .region-header .menu-item-541, .region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-1153, .region-header .menu-item-588, .region-header .menu-item-1156').removeClass('active');
});
//remove class "active" from all upper menu when click out side heder area
jQuery('#columns, #footer').click(function(){
jQuery('.region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-514, .region-header .menu-item-588, .region-header .menu-item-1156, .region-header .menu-item-542, .region-header .menu-item-1153, .region-header .menu-item-542, .region-header .menu-item-1154, .region-header .menu-item-541, .region-header .menu-item-514, .region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-1153, .region-header .menu-item-588, .region-header .menu-item-1156').removeClass('active');
});
//burger
jQuery('.region-header #burger-menu').click(function(){
jQuery('.region-header #block-system-main-menu, #burger-menu').toggleClass('burger-active');
jQuery('.region-header .menu-item-1154, .region-header .menu-item-541, .region-header .menu-item-589, .region-header .menu-item-1155, .region-header .menu-item-514, .region-header .menu-item-1153, .region-header .menu-item-588, .region-header .menu-item-1156, .region-header .menu-item-542').removeClass('active');
});
//page header for non service page - in relation to block12, "header for non service pages"
jQuery('#main-content #main-content-header, .section-contact #main-content-header, .section-contact-us #main-content-header').appendTo('#jq-page-title');
//contact page
jQuery('<div id="addon-arrow">').appendTo('body.section-contact .webform-client-form');
//add script here
});
|
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* @deprecated since version 2.2.0
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
/**
* This widget is used to tag a DOM element as deletable. By default, it will use the click event on the item with a
* data role of delete to trigger the deletion.
*/
$.widget('mage.deletableItem', {
options: {
deleteEvent: 'click',
deleteSelector: '[data-role="delete"]',
hiddenClass: 'no-display'
},
/**
* This method binds elements found in this widget.
*/
_bind: function () {
var handlers = {};
// since the first handler is dynamic, generate the object using array notation
handlers[this.options.deleteEvent + ' ' + this.options.deleteSelector] = '_onDeleteClicked';
handlers.hideDelete = '_onHideDelete';
handlers.showDelete = '_onShowDelete';
this._on(handlers);
},
/**
* This method constructs a new widget.
*/
_create: function () {
this._bind();
},
/**
* This method is to initialize the control
* @private
*/
_init: function () {
this._onHideDelete(); // by default, hide the control
},
/**
* This method removes the entity from the DOM.
* @private
*/
_onDeleteClicked: function (e) {
e.stopPropagation();
this.element.trigger('deleteItem');
},
/**
* This method hides the delete capability of this item (i.e. making it not deletable)
* @private
*/
_onHideDelete: function () {
this.element.find(this.options.deleteSelector).addClass(this.options.hiddenClass);
},
/**
* This method shows the delete capability of this item (i.e. making it deletable)
* @private
*/
_onShowDelete: function () {
this.element.find(this.options.deleteSelector).removeClass(this.options.hiddenClass);
}
});
return $.mage.deletableItem;
});
|
/*
* Title : Booking System PRO (WordPress Plugin)
* Version : 2.0
* File : assets/js/coupons/backend-coupons.js
* File Version : 1.0.2
* Created / Last Modified : 23 September 2014
* Author : Dot on Paper
* Copyright : © 2012 Dot on Paper
* Website : http://www.dotonpaper.net
* Description : Booking System PRO back end coupons JavaScript class.
*/
var DOPBSPCoupons = new function(){
'use strict';
/*
* Private variables.
*/
var $ = jQuery.noConflict();
/*
* Display coupons list.
*/
this.DOPBSPCoupons = function(){
};
/*
* Display coupons list.
*/
this.display = function(){
DOPBSP.clearColumns(1);
DOPBSP.toggleMessages('active', DOPBSP.text('MESSAGES_LOADING'));
$.post(ajaxurl, {action: 'dopbsp_coupons_display'}, function(data){
$('#DOPBSP-column1 .dopbsp-column-content').html(data);
$('.DOPBSP-admin .dopbsp-main').css('display', 'block');
DOPBSP.toggleMessages('success', DOPBSP.text('COUPONS_LOAD_SUCCESS'));
}).fail(function(data){
DOPBSP.toggleMessages('error', data.status+': '+data.statusText);
});
};
return this.DOPBSPCoupons();
};
|
/** out city */
var outcitys = {'SH','BJ'}
|
/**
A data model representing an Invite
@class Invite
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
Discourse.Invite = Discourse.Model.extend({
rescind: function() {
$.ajax('/invites', {
type: 'DELETE',
data: { email: this.get('email') }
});
this.set('rescinded', true);
}
});
Discourse.Invite.reopenClass({
create: function(invite) {
var result;
result = this._super(invite);
if (result.user) {
result.user = Discourse.User.create(result.user);
}
return result;
}
});
|
/*
* Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["gu-IN"] = {
name: "gu-IN",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "%"
},
currency: {
pattern: ["$ -n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "₹"
}
},
calendars: {
standard: {
days: {
names: ["રવિવાર","સોમવાર","મંગળવાર","બુધવાર","ગુરુવાર","શુક્રવાર","શનિવાર"],
namesAbbr: ["રવિ","સોમ","મંગળ","બુધ","ગુરુ","શુક્ર","શનિ"],
namesShort: ["ર","સો","મં","બુ","ગુ","શુ","શ"]
},
months: {
names: ["જાન્યુઆરી","ફેબ્રુઆરી","માર્ચ","એપ્રિલ","મે","જૂન","જુલાઈ","ઑગસ્ટ","સપ્ટેમ્બર","ઑક્ટોબર","નવેમ્બર","ડિસેમ્બર"],
namesAbbr: ["જાન્યુ","ફેબ્રુ","માર્ચ","એપ્રિલ","મે","જૂન","જુલાઈ","ઑગ","સપ્ટે","ઑક્ટો","નવે","ડિસે"]
},
AM: ["પૂર્વ મધ્યાહ્ન","પૂર્વ મધ્યાહ્ન","પૂર્વ મધ્યાહ્ન"],
PM: ["ઉત્તર મધ્યાહ્ન","ઉત્તર મધ્યાહ્ન","ઉત્તર મધ્યાહ્ન"],
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy HH:mm:ss",
g: "dd-MM-yy HH:mm",
G: "dd-MM-yy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
console.log('Fantazy Sidebar is loaded');
fs = {};
if (typeof console === 'undefined') {
console = {
log: function() {},
dir: function() {}
};
}
(function() {
fs.start = function(opts) {
jQuery(function() {
opts = jQuery.extend({}, {
contentID: '#content',
sidebarID: '#sidebar',
contentClass:'.content',
sidebarClass:'.sidebar',
waitingTime: 3000,
debounce: 500,
animate: 3000,
offsetTop: 0,
offsetBottom: 0,
minHDiff: 0
}, opts);
(function ($) {
$(document);
$(jQuery(opts.contentClass)).attr("id", "content");
$(jQuery(opts.sidebarClass)).attr("id", "sidebar");
}(jQuery));
setTimeout(function() {
var $w = jQuery(window),
$c = jQuery(opts.contentID),
$ss = jQuery(opts.sidebarID),
$b = jQuery('body');
console.dir(opts);
if ($c.length && $ss.length) {
$ss.each(function() {
(function($s) {
// console.log($c.height() - $s.height());
if ($c.height() - $s.height() > opts.minHDiff || opts.dynamicTop) {
$s.parent().css('position', 'relative');
var initialSPos = $s.position(),
initialSOff = $s.offset();
setTimeout(function() {
$s.css({
position: 'absolute',
left: initialSPos.left + 'px',
top: initialSPos.top + 'px'
}).find('.widget').css('position', 'relative');
var lastScrollY = -1,
sidebarIDTop = initialSPos.top,
offsetTop = initialSOff.top - sidebarIDTop,
maxTop = sidebarIDTop + $c.height() - $s.outerHeight(),
onScroll = function(e) {
var scrollY = $w.scrollTop(),
t, scrollingDown = scrollY > lastScrollY;
if ((scrollingDown && scrollY > sidebarIDTop + offsetTop && scrollY + $w.height() > $s.position().top + $s.height() + offsetTop - sidebarIDTop) || (!scrollingDown && scrollY < $s.position().top + offsetTop)) {
if (e.type === 'scroll' && ($w.height() > $s.height() || !scrollingDown)) {
t = Math.max(sidebarIDTop, scrollY - (offsetTop) + (~~opts.offsetTop));
} else {
t = Math.max(sidebarIDTop, scrollY + $w.height() - $s.outerHeight() - offsetTop - (~~opts.offsetBottom));
}
t = Math.min(t, opts.dynamicTop ? (sidebarIDTop + $c.height() - $s.outerHeight()) : maxTop);
$s.stop().animate({
top: t + 'px'
}, ~~opts.animate);
}
lastScrollY = scrollY;
};
if (opts.debounce && Function.prototype.debounce) {
onScroll = onScroll.debounce(opts.debounce);
}
$w.scroll(onScroll).resize(onScroll);
onScroll({
type: 'scroll'
});
$w.scroll(function() {
$s.stop();
});
}, 0);
}
})(jQuery(this));
});
} else {
if ($c.length === 0) {
console.log(opts.contentID + ' not found');
}
if ($ss.length === 0) {
console.log(opts.sidebarID + ' not found');
}
}
}, opts.waitingTime);
});
};
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.