text
stringlengths
2
6.14k
var baseIteratee = require('./_baseIteratee'), baseSortedIndexBy = require('./_baseSortedIndexBy'); /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @specs * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, baseIteratee(iteratee), true); } module.exports = sortedLastIndexBy;
ThinMint.Mixin.Paginate = function() { var _super = {}; _super.init = ThinMint.Util.callback( this.init ); _super.getPage = ThinMint.Util.callback( this.getPage ); _super.setPage = ThinMint.Util.callback( this.setPage ); _super.getPages = ThinMint.Util.callback( this.getPages ); _super.setPages = ThinMint.Util.callback( this.setPages ); _super.pageNext = ThinMint.Util.callback( this.pageNext ); _super.pagePrevious = ThinMint.Util.callback( this.pagePrevious ); _super.pageTo = ThinMint.Util.callback( this.pageTo ); _super.onPage = ThinMint.Util.callback( this.onPage ); // The first page, cannot paginate before this page. this.pageFirst = 1; // The current page. this.page = 1; // How many pages are available. this.pages = 1; this.getPage = function() { return this.page; }; this.setPage = function(page) { this.page = Number(page); return this; }; this.getPages = function() { return this.pages; }; this.setPages = function(pages) { this.pages = Number(pages); return this; }; this.pageNext = function() { if(this.page >= this.pages) { this.console.warn('ThinMint.Mixin.Paginate', 'Already at the max page.'); return; } ++this.page; return this.onPage(); }; this.pagePrevious = function() { if(this.page <= this.pageFirst) { this.console.warn('ThinMint.Mixin.Paginate', 'Already at the first page.'); return; } --this.page; return this.onPage(); }; this.pageTo = function(page) { page = parseInt(page); if(page >= this.pages || page <= this.pageFirst) { this.console.warn('ThinMint.Mixin.Paginate', 'Cannot go outside of the allowed pages.'); return; } this.page = page; return this.onPage(); }; this.onPage = function() { // Each panel will imlement onPage, this is how it // will handle a page change. _super.onPage.apply(this, arguments); }; return this; };
const expect = require('chai').expect; const PragmaThanksSpreadsheet = require('../src/PragmaThanksSpreadsheet'); describe('PragmaThanksSpreadsheet', () => { describe('#isEmpty', () => { it('returns true when spreadsheet is empty', () => { const spreadsheetContent = []; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); expect(sheet.isEmpty()).to.eql(true); }); it('returns true when spreadsheet is undefined', () => { const sheet = new PragmaThanksSpreadsheet(undefined); expect(sheet.isEmpty()).to.eql(true); }); it('returns false when spreadsheet is not empty', () => { const spreadsheetContent = [[1], [2]]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); expect(sheet.isEmpty()).to.eql(false); }); }); describe('#getPointsToUse', () => { const spreadsheetContent = [ [], ['foo', 'bar', 'biz'], [], [20, 42, 32], [0, 0], ]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); it('returns user balance when it has at least one pragma points', () => { expect(sheet.getPointsToUse('foo')).to.eql(20); }); it('returns the balance for different users', () => { expect(sheet.getPointsToUse('bar')).to.eql(42); }); it('returns zero balance when user is not found', () => { expect(sheet.getPointsToUse('unknown')).to.eql(0); }); }); describe('#getPointsToGive', () => { const spreadsheetContent = [ [], ['foo', 'bar'], [], [0, 0], [30, 44], ]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); it('returns the points to give when user has at least one pragma points to give', () => { expect(sheet.getPointsToGive('foo')).to.eql(30); }); it('returns the points to give for different users', () => { expect(sheet.getPointsToGive('bar')).to.eql(44); }); it('returns zero points to give when user is not found', () => { expect(sheet.getPointsToGive('unknown')).to.eql(0); }); }); });
import React, { PropTypes } from 'react'; import styled from 'styled-components'; import TextInfo from '../TextInfo'; import CardImage from '../CardImage'; import { Row, Col, Card, Avatar } from 'antd'; import { Panel } from 'react-bootstrap'; /* const CardImage = styled.div` img { display: block; height:200px; } `;*/ class CardRaces extends React.Component { constructor(props) { super(props); } onClick = (id) => { if (this.props.onClick) { this.props.onClick(id); } } render() { const { data } = this.props; return ( <Row gutter={8}> {data.map((race, key) => <Col key={key} md={12} style={{ marginBottom: 5, marginTop: 5 }}> <CardImage imageUrl={race.cardImageUrl} onClick={() => this.onClick(race.id)}> <div > <h3>{race.title}</h3> <TextInfo>{race.description}</TextInfo> </div> </CardImage> </Col> )} </Row> ) } } /* CardRaces.defaultProps = { data: [ { id:'spartan-challenge', title: 'Spartan Challenge', date: '2017-Aug-12', description: 'Spartan Challenge', url:'http://lorempixel.com/400/200/sports/1' }, { id:'takbo-marawi', title: 'Takbo Marawi', date: '2017-Aug-12', description: 'Spartan Challenge', url:'http://lorempixel.com/400/200/sports/2' }, ] }; */ CardRaces.propTypes = { data: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string, date: PropTypes.date, description: PropTypes.string, url: PropTypes.string })) }; export default CardRaces;
var names = [ 'Whiskers', 'Athena', 'Sir Theodore Tibblesworth', 'Rex' ]; function keyOf (name) { return name.toLowerCase().replace(/\W+/g, '-') } module.exports = function (db) { setInterval(function () { var lives = Math.floor(Math.random() * 9 + 1); var name = names[Math.floor(Math.random() * names.length)]; db.put('cat!' + keyOf(name), { name: name, lives: lives }); }, 1000); };
'use strict'; var CanvasRenderer = require('./main'); CanvasRenderer.prototype._prepareImages = function () { // Creating the list of images var imagesToPrepare = []; var symbolList = this._extractor._symbolList; var symbols = this._extractor._symbols; for (var s = 0; s < symbolList.length; s += 1) { var symbolId = symbolList[s]; var symbol = symbols[symbolId]; if (symbol.isImage) { imagesToPrepare.push(symbol.swfObject); } var images = symbol.images; if (images) { for (var i = 0; i < images.length; i += 1) { var imageData = images[i]; imagesToPrepare.push(imageData.image); } } } var nImagesToPrepare = imagesToPrepare.length; if (nImagesToPrepare === 0) { this._renderImages(); return; } var nImagesReady = 0; var self = this; var onWrittenCallBack = function (imageData, imageCanvas) { if (imageCanvas.width > 0 && imageCanvas.height > 0) { self._images[imageData.id] = imageCanvas; } else { console.warn('[CanvasRenderer.prepareImages] Image is empty', imageCanvas.width, imageCanvas.height, imageData.id); } nImagesReady += 1; if (nImagesReady === nImagesToPrepare) { self._renderImages(); } }; for (var i = 0; i < imagesToPrepare.length; i += 1) { this._renderImageToCanvas(imagesToPrepare[i], onWrittenCallBack); } };
module.exports = { '1.train.spikes': { display: '01', indicator: 'OGB-1', area: 'V1', source: 'Theis et al., 2016' }, '2.train.spikes': { display: '02', indicator: 'OGB-1', area: 'V1', source: 'Theis et al., 2016' }, '3.train.spikes': { display: '03', indicator: 'GCaMP6s', area: 'V1', source: 'Theis et al., 2016' }, '4.train.spikes': { display: '04', indicator: 'OGB-1', area: 'Retina', source: 'Theis et al., 2016' }, '5.train.spikes': { display: '05', indicator: 'GCaMP6s', area: 'V1', source: 'Theis et al., 2016' }, '6.train.spikes': { display: '06', indicator: 'GCaMP5k', area: 'V1', source: 'Akerboom et al., 2012' }, '7.train.spikes': { display: '07', indicator: 'GCaMP6f', area: 'V1', source: 'Chen et al., 2013' }, '8.train.spikes': { display: '08', indicator: 'GCaMP6s', area: 'V1', source: 'Chen et al., 2013' }, '9.train.spikes': { display: '09', indicator: 'jRCAMP1a', area: 'V1', source: 'Dana et al., 2016' }, '10.train.spikes': { display: '10', indicator: 'jRGECO1a', area: 'V1', source: 'Dana et al., 2016' } }
var etc=require("./etc.js"), msgtype=require("./msgtype.js"); function constructMessage(type,args){ var len=6+args.map(function(a){return 4+a.length;}).reduce(function(a,b){return a+b;},0); var buf=new Buffer(len); //console.log("constructing message with len",len) buf.writeUInt32BE(len,0); buf.writeUInt8(type,4); buf.writeUInt8(args.length,5); var cursor=6; for(var i=0;i<args.length;i++){ if(!(args[i] instanceof Buffer))args[i]=new Buffer(""+args[i]); buf.writeUInt32BE(args[i].length,cursor); cursor+=4; args[i].copy(buf,cursor); cursor+=args[i].length; } //console.log("constructing message with len",len,"result:",buf); return buf; } function parseMessage(buf){ var buflen=buf.length; if(buflen<4)return false; var len=buf.readUInt32BE(0); if(buflen<len)return false; console.log(buf.slice(0,len)); var type=buf.readUInt8(4); var numargs=buf.readUInt8(5); var cursor=6; var args=new Array(numargs),arglen; for(var i=0;i<numargs;i++){ //console.log("pM: i="+i); if(cursor+4>len)return {type:null,args:null,len:len}; arglen=buf.readUInt32BE(cursor); cursor+=4; //console.log("pM: cursor="+cursor); if(cursor+arglen>len)return {type:null,args:null,len:len}; args[i]=new Buffer(arglen); buf.copy(args[i],0,cursor,cursor+arglen); cursor+=arglen; } return {type:type,args:args,len:len}; } function makeBufferedProtocolHandler(onmessage,obj){ var buffer=new Buffer(0); return function(data){ if(typeof data=="string")data=new Buffer(data); //console.log("received",data); //first append new data to buffer var tmp=new Buffer(buffer.length+data.length); if(buffer.length)buffer.copy(tmp); data.copy(tmp,buffer.length); buffer=tmp; //console.log("buffer+data",buffer); //then while there's a message in there do { //try to parse it var messageBuffer=new Buffer(buffer.length); buffer.copy(messageBuffer); var msg=parseMessage(messageBuffer); if(msg==false)return; //more data needed //console.log("messageBuffer",messageBuffer); //console.log("msg.len",msg.len); //replace buffer with the data that's left if(buffer.length-msg.len>0){ tmp=new Buffer(buffer.length-msg.len); buffer.copy(tmp,0,msg.len); buffer=tmp; } else { buffer=new Buffer(0); } //console.log("buffer",buffer); //now all administration is done, we've got ourselves a message if(msg.type==null)throw new Error("Invalid message received!"); onmessage(msg,obj,messageBuffer); } while(buffer.length); }; } module.exports.constructMessage=constructMessage; module.exports.parseMessage=parseMessage; module.exports.makeBufferedProtocolHandler=makeBufferedProtocolHandler;
cssx( @media screen and (min-width: `minWidthForMediaQuery`px) { `a().reduce(b)` { `getProperty();`: `a + b / c`%; } } )
import React from "react"; import { shallow } from "enzyme"; import TableRow from "./TableRow"; describe("TableRow", () => { it("matches snapshot", () => { const aTableRow = shallow(<TableRow />); expect(aTableRow).toMatchSnapshot(); }); });
//Get /question exports.question = function (req, res, next) { var answer = req.query.answer || ''; res.render('quizzes/question', {question: "Capital de Italia", answer: answer}); }; //GET /check exports.check = function(req,res, next) { var answer = req.query.answer || ''; var result = ((answer === 'Roma') ? 'Correcta' : 'Incorrecta'); res.render('quizzes/result', {result: result, answer: answer}); }; //GET /author exports.author = function(req, res, next) { res.render('author'); };
import * as util from "./util"; const path = require("path"); /** * Creates a toc object * @param {Array} items All items of the toc * @param {Array} root Only the root items * @return {Object} Toc object */ const createToc = function (items, root) { if (items == null) items = []; if (root == null) root = []; return { items, root, }; }; const findByPath = util.findBy("path"); export const createTocFromFolderP = function (pathParam, toc, rootPath) { if (toc == null) toc = createToc(); if (rootPath == null) rootPath = pathParam; return util.readdirP(pathParam).then((files) => { var localItemIds = []; var prom = Promise.resolve(); files.forEach((f) => { var fullPath = path.join(pathParam, f); prom = prom .then(() => { return util.lstatP(fullPath); }) .then((stats) => { var id = toc.items.push({ ext: path.extname(f), isDir: stats.isDirectory(), absolutePath: fullPath, path: fullPath.replace(rootPath + path.sep, ""), name: f, }) - 1; localItemIds.push(id); if (toc.items[id].isDir) { return createTocFromFolderP(fullPath, toc, rootPath).then( (newToc) => { toc = newToc; toc.items[id].children = toc.root; toc.root = []; } ); } }); }); prom = prom.then(() => { toc.root = localItemIds; return toc; }); return prom; }); }; export const mergeTocConfigWithToc = function (toc, tocConfig) { var newToc = createToc(); var addChildren = function (children) { var ids = []; children.forEach(function (childId) { var childItem = toc.items[childId]; var id = newToc.items.push(childItem) - 1; ids.push(id); if (childItem.children != null) { childItem.children = addChildren(childItem.children); } }); return ids; }; var mergeItems = function (items, basePath) { if (basePath == null) basePath = ""; var localItemIds = []; items.forEach((tocItem) => { var item = {}; if (tocItem.path != null) { tocItem.path = path.join(basePath, tocItem.path); var origId = findByPath(toc.items, tocItem.path); if (origId !== false) { item = toc.items[origId]; } } item.href = tocItem.href; if (tocItem.title != null) { item.title = tocItem.title; } var id = newToc.items.push(item) - 1; if (tocItem.children != null) { newToc.items[id].children = mergeItems(tocItem.children, tocItem.path); newToc.items[id].isDir = true; } else if (item.children != null) { newToc.items[id].children = addChildren(item.children); } localItemIds.push(id); }); return localItemIds; }; newToc.root = mergeItems(tocConfig); return newToc; }; export const calculateItemLevels = function (toc, items, level) { if (level == null) level = 0; if (items == null) items = toc.root; items.forEach(function (itemId) { let item = toc.items[itemId]; item.level = level; if (item.children != null) { calculateItemLevels(toc, item.children, level + 1); } }); return toc; }; export const getHtmlChapters = function (html) { const chapters = { root: [], items: [], }; const headingRegexStr = '<h(\\d*)(?: id="(.*?)")?.*?>([\\s\\S]*?)<\\/h\\1(?: .*?)?>'; const headingGlobalRegex = new RegExp(headingRegexStr, "g"); const headingRegex = new RegExp(headingRegexStr); const htmlTagsRegex = /<(?:.|\n)*?>/gm; let matches = html.match(headingGlobalRegex); if (matches != null && matches.length > 0) { matches = matches.map(function (match) { const subMatches = match.match(headingRegex); const hash = subMatches[2]; const heading = subMatches[3].replace(htmlTagsRegex, ""); return { level: subMatches[1], heading: heading, hash }; }); const pushHeadingsRecursive = function (matches) { var head = matches[0]; var tail = matches.slice(1); var rest = []; var broken = false; var children = []; tail.forEach(function (item) { if (item.level === head.level) { rest.push(item); broken = true; } else if (broken === false && head.level < item.level) { children.push(item); } else { rest.push(item); } }); if (children.length > 0) { children = pushHeadingsRecursive(children); } head.children = children; if (rest.length > 0) { rest = pushHeadingsRecursive(rest); } return [head, ...rest]; }; const recursiveHeadings = pushHeadingsRecursive(matches); const normalizeRecursive = function (items) { return items.map(function (chapter) { const idx = chapters.items.push(chapter) - 1; chapter.id = idx; chapter.children = normalizeRecursive(chapter.children); return idx; }); }; chapters.root = normalizeRecursive(recursiveHeadings); } return chapters; };
/* eslint no-console:0 */ var Hapi = require('hapi'), Path = require('path'), Swig = require('swig'), Routes = require('./routes'); Swig.setDefaults({ cache: false }); var server = new Hapi.Server(); server.connection({ port: 3000 }); server.views({ engines: { swig: Swig }, path: Path.join(__dirname, 'views') }); server.route({ method: 'GET', path: '/', handler: Routes.index }); server.route({ method: 'GET', path: '/action', handler: Routes.action }); server.route({ method: 'GET', path: '/responsive', handler: Routes.responsive}); server.route({ method: 'GET', path: '/form', handler: Routes.form }); server.route({ method: 'GET', path: '/keys', handler: Routes.keys }); server.route({ method: 'GET', path: '/angular', handler: Routes.angular }); server.route({ method: 'GET', path: '/pace', handler: Routes.pace }); server.route({ method: 'GET', path: '/pace-theme-center-simple.css', handler: function (request, reply) { reply.file(Path.join(__dirname, 'pace-theme-center-simple.css')); } }); server.route({ method: 'GET', path: '/pace.js', handler: function (request, reply) { reply.file(Path.join(__dirname, 'pace.js')); } }); server.route({ method: 'GET', path: '/angular/data', handler: Routes.angularData}); server.route({ method: 'POST', path: '/result', handler: Routes.result }); server.route({ method: 'GET', path: '/post/{id}', handler: Routes.post }); server.route({ method: 'GET', path: '/generate/{number}', handler: Routes.generate }); server.route({ method: 'GET', path: '/delay/{number}', handler: Routes.delay }); server.start(function () { console.log('Server running at:', server.info.uri); });
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Jesse Ruderman * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //----------------------------------------------------------------------------- var BUGNUMBER = 452476; var summary = 'Do not assert with JIT: !cx->runningJittedCode'; var actual = 'No Crash'; var expect = 'No Crash'; printBugNumber(BUGNUMBER); printStatus (summary); jit(true); for (var j = 0; j < 10; j++) { for (var i = 0; i < j; ++i) this["n" + i] = 1; __defineGetter__('w', (function(){})); [1 for each (g in this) for each (t in /x/g)]; } jit(false); reportCompare(expect, actual, summary);
import pt from './pt/pt' const messages = { pt } export default messages
import { validate, URL_REX, TITLE_REX } from '../validator'; import db from '../connection'; import getUserById from '../loaders/get-user-by-id'; import sanitizeHtml from 'sanitize-html'; export default async (userId, rawTitle, rawLink, rawBody) => { const body = sanitizeHtml(rawBody, { allowedTags: ['b', 'i', 'em', 'strong', 'a', 'p', 'br', 'div', 'h2', 'h3'], allowedAttributes: { a: ['href'], }, }); const link = (validate(URL_REX, rawLink)) ? rawLink : null; const title = (validate(TITLE_REX, rawTitle)) ? rawTitle.trim() : null; const urlStringRoot = title.toLowerCase().replace(/ /g, '-').replace(/[^a-z-1234567890]/g, ''); if (userId && body && body !== '') { const urlStringLike = `${urlStringRoot}%`; const countResult = await db.one( 'select count(*) as count from t_post where urlstring like $(urlStringLike)', { urlStringLike } ); const urlString = (Number(countResult.count) === 0) ? urlStringRoot : `${urlStringRoot}-${countResult.count}`; const user = await getUserById(userId); if (user && user.status > 0) { const insertResult = await db.one( `insert into t_post (user_id, title, urlstring, body, url) values ($(userId), $(title), $(urlString), $(body), $(link)) returning id`, { userId, title, urlString, body, link } ); if (insertResult) { return { success: true, post: { urlstring: urlString } }; } return { success: false, message: 'Insert failed' }; } return { success: false, message: 'No permissions' }; } return { success: false, message: 'Didn\'t validate' }; };
'use strict'; //NOTE:Methods used to do HTTP requests. To use an HTTP request listed here just call the method angular.module('announcements').factory('Announcements', ['$http', function($http) { var methods = { getAllAnnouncements: function(announcements) { return $http.get('/api/announcements', announcements); }, getOneAnnouncement: function(id) { return $http.get('/api/announcements/' + id); }, createAnnouncement: function(announcement) { $http.post('/api/announcements', announcement); }, deleteAnnouncement: function(id) { return $http.delete('/api/announcements/' + id); }, updateAnnouncement: function(id, announcement) { return $http.put('/api/announcements/' + id, announcement); }, }; return methods; }]);
//document.write("It works."); document.write(require("./content.js"));
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'find', 'ro', { find: 'Găseşte', findOptions: 'Find Options', findWhat: 'Găseşte:', matchCase: 'Deosebeşte majuscule de minuscule (Match case)', matchCyclic: 'Potrivește ciclic', matchWord: 'Doar cuvintele întregi', notFoundMsg: 'Textul specificat nu a fost găsit.', replace: 'Înlocuieşte', replaceAll: 'Înlocuieşte tot', replaceSuccessMsg: '%1 căutări înlocuite.', replaceWith: 'Înlocuieşte cu:', title: 'Găseşte şi înlocuieşte' } );
/** * @copyright * The MIT License (MIT) * * Copyright (c) 2014 Cosmic Dynamo LLC * * 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. * @module jazzHands.query.function.boolean */ define([ "./_boolean" ], function (_boolean) { /** * Returns true if var is bound to a value. Returns false otherwise. Variables with the value NaN or INF are considered bound. * @see http://www.w3.org/TR/sparql11-query/#func-bound * @param {Object} execData * @param {jazzHands.query.DataRow} dataRow * @param {jazzHands.query.Variable} variable * @return {RdfJs.node.Literal<Boolean>} * @throws err:FORG0006, Invalid argument type */ function bound(execData, dataRow, variable) { return _boolean(variable.resolve(execData, dataRow) !== null); } return bound; });
import React from 'react'; import { Link } from 'react-router-dom'; export default class Combatant extends React.Component { render() { return ( <div key={ this.props.id } className={this.props.index === 0 ? 'col-xs-6 col-sm-6 col-md-5 col-md-offset-1' : 'col-xs-6 col-sm-6 col-md-5'}> <div className='thumbnail fadeInUp animated'> <div className="image-container"> <div className="inner-container"> <img onClick={ this.props.upVote.bind(null, this.props.id) } src={ this.props.imageUrl } alt="cats"/> </div> </div> <div className='caption text-center'> <p>{ this.props.description }</p> <h4> <Link to={ `/characters/${ this.props.id }` }> <strong>{this.props.name}</strong> </Link> </h4> {this.props.isReported? null : <span onClick={ this.props.report.bind(null, this.props.id) } className="pull-right report">Report</span> } </div> </div> </div> ) } }
/* * This file is part of the React Redux starter repo. * * (c) Magnus Bergman <hello@magnus.sexy> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React, { PropTypes } from 'react' import { Provider } from 'react-redux' import { Router } from 'react-router' import routes from 'routes/routes' import DevTools from '../DevTools' /** * This is the Root component. * * @author Magnus Bergman <hello@magnus.sexy> */ const Root = ({ store, history }) => <Provider store={store}> <div> <Router history={history} routes={routes} /> <DevTools /> </div> </Provider> Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired } export default Root
var assert = require('chai').assert; var ss = require('../../../script_sanitize'); var describe = require('mocha/lib/mocha.js').describe; var it = require('mocha/lib/mocha.js').it; var script_sanitize = ss.sanitize; module.exports = function () { describe("attributes", function () { it('should replace the attribute specified', function() { var a = script_sanitize("<h1 onload=''></h1>", { attributes: ["onload"], tags: [] }); assert.isOk(!a.includes("onload")); }); it('should support multiple attributes', function() { var a = script_sanitize("<h1 onload='' onmouseover=''></h1>", { attributes: ["onload", "onmouseover"], tags: [] }); assert.isOk(!a.includes("onload")); assert.isOk(!a.includes("onmouseover")); }); it('should remove nested attributes', function () { var a = script_sanitize("<h1 onload='onload='''></h1>", { attributes: ["onload", "onmouseover"], tags: [] }); assert.isOk(!a.includes("onload")); }); }); };
import resource from 'resource-router-middleware'; import model from '../models/users'; export default ({ config, db }) => resource({ /** Property name to store preloaded entity on `request`. */ id : 'user', mergeParams: true, /** For requests with an `id`, you can auto-load the entity. * Errors terminate the request, success sets `req[id] = data`. */ load(req, id, callback) { let query = { select: '-_id -__v' }; model.findOne({id: id}, query.select, function(err, record) { let error = record ? null : 'Not found'; callback(error, record); }); }, /** GET / - List all entities */ index(params, res) { let urlQuery = {}; let searchable = ['fullName', 'email', 'workPhone', 'personalPhone']; params.query.select = { '_id': 0, 'id': 1, 'fullName': 1, 'email': 1, 'workPhone': 1, 'personalPhone': 1 }; if(!params.query.active || params.query.active === 'false') { urlQuery.active = false; } else { urlQuery.active = true; } if(!params.query.limit) { params.query.limit = config.pagination; } if(!params.query.sort) { params.query.sort = 'id'; } if(params.query.sort) { params.query.sort = params.query.sort; } for(var key in params.query) { if(!isNaN(parseFloat((params.query[key])))) { params.query[key] = parseInt(params.query[key]); } } if(params.query.find) { let parsed = JSON.parse(params.query.find); let queryArray = []; for ( let property in parsed ) { if( (searchable.indexOf(property) > -1) ) { let userSearch = new RegExp(parsed[property], 'i'); let tempObj = {}; tempObj[property] = userSearch; queryArray.push(tempObj); } } //we ensure we only search for proper active/inactive records let activeQuery = { 'active': urlQuery.active } queryArray.push(activeQuery); urlQuery = { $and: queryArray, }; } model.paginate( urlQuery ,params.query, function(err, result) { if(err) { console.log(err); res.sendStatus(500); } res.json(result); }); }, /** POST / - Create a new entity */ create(req, res) { console.log(req.body); let newModel = new model(req.body); newModel.save((err, user) => { if(err) { console.error(err); if (err.name === 'MongoError' && err.code === 11000) { // Duplicate username return res.status(400).send({ success: false, message: 'Email is not unique' }); } return res.status(400).send({ success: false, message: err }); } else { return res.status(200).send({success: true}); } }); }, /** GET /:id - Return a given entity */ read( record , res) { res.status(200).json(record['user']); }, /** PUT /:id - Update a given entity */ update({ facet, body }, res) { for (let key in body) { if (key!=='id') { facet[key] = body[key]; } } res.sendStatus(204); }, /** DELETE /:id - Delete a given entity */ delete({ facet }, res) { facets.splice(facets.indexOf(facet), 1); res.sendStatus(204); }, });
;(function(dragula){ 'use strict'; angular.module('angular-dragula', []) .factory('ngDragulaFactory', ['$timeout', function($timeout){ function get(name){ return $timeout(function(){ if(name === 'get'){ throw new Error('RESERVE_WORD'); } if(this[name]){ return this[name] }else{ throw new Error('NOT_FOUND'); } }.bind(this), 500) }; return { get: get }; }]) .directive('ngDragula', ['ngDragulaFactory', function(ngDragulaFactory){ return { restrict: 'A', scope: { config: '=' }, link: function(scope, element, attrs){ var drag = scope.config; ngDragulaFactory[drag.name] = dragula(drag.elements, drag); }; } }]); }(dragula));
/*! * * Super simple WYSIWYG editor v0.8.19 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-13T19:41Z * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(self, function() { return /******/ (() => { // webpackBootstrap var __webpack_exports__ = {}; (function ($) { $.extend($.summernote.lang, { 'cs-CZ': { font: { bold: 'Tučné', italic: 'Kurzíva', underline: 'Podtržené', clear: 'Odstranit styl písma', height: 'Výška řádku', strikethrough: 'Přeškrtnuté', size: 'Velikost písma' }, image: { image: 'Obrázek', insert: 'Vložit obrázek', resizeFull: 'Původní velikost', resizeHalf: 'Poloviční velikost', resizeQuarter: 'Čtvrteční velikost', floatLeft: 'Umístit doleva', floatRight: 'Umístit doprava', floatNone: 'Neobtékat textem', shapeRounded: 'Tvar: zaoblený', shapeCircle: 'Tvar: kruh', shapeThumbnail: 'Tvar: náhled', shapeNone: 'Tvar: žádný', dragImageHere: 'Přetáhnout sem obrázek', dropImage: 'Přetáhnout obrázek nebo text', selectFromFiles: 'Vybrat soubor', url: 'URL obrázku', remove: 'Odebrat obrázek', original: 'Originál' }, video: { video: 'Video', videoLink: 'Odkaz videa', insert: 'Vložit video', url: 'URL videa?', providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion nebo Youku)' }, link: { link: 'Odkaz', insert: 'Vytvořit odkaz', unlink: 'Zrušit odkaz', edit: 'Upravit', textToDisplay: 'Zobrazovaný text', url: 'Na jaké URL má tento odkaz vést?', openInNewWindow: 'Otevřít v novém okně' }, table: { table: 'Tabulka', addRowAbove: 'Přidat řádek nad', addRowBelow: 'Přidat řádek pod', addColLeft: 'Přidat sloupec vlevo', addColRight: 'Přidat sloupec vpravo', delRow: 'Smazat řádek', delCol: 'Smazat sloupec', delTable: 'Smazat tabulku' }, hr: { insert: 'Vložit vodorovnou čáru' }, style: { style: 'Styl', p: 'Normální', blockquote: 'Citace', pre: 'Kód', h1: 'Nadpis 1', h2: 'Nadpis 2', h3: 'Nadpis 3', h4: 'Nadpis 4', h5: 'Nadpis 5', h6: 'Nadpis 6' }, lists: { unordered: 'Odrážkový seznam', ordered: 'Číselný seznam' }, options: { help: 'Nápověda', fullscreen: 'Celá obrazovka', codeview: 'HTML kód' }, paragraph: { paragraph: 'Odstavec', outdent: 'Zvětšit odsazení', indent: 'Zmenšit odsazení', left: 'Zarovnat doleva', center: 'Zarovnat na střed', right: 'Zarovnat doprava', justify: 'Zarovnat oboustranně' }, color: { recent: 'Aktuální barva', more: 'Další barvy', background: 'Barva pozadí', foreground: 'Barva písma', transparent: 'Průhlednost', setTransparent: 'Nastavit průhlednost', reset: 'Obnovit', resetToDefault: 'Obnovit výchozí', cpSelect: 'Vybrat' }, shortcut: { shortcuts: 'Klávesové zkratky', close: 'Zavřít', textFormatting: 'Formátování textu', action: 'Akce', paragraphFormatting: 'Formátování odstavce', documentStyle: 'Styl dokumentu' }, help: { 'insertParagraph': 'Vložit odstavec', 'undo': 'Vrátit poslední příkaz', 'redo': 'Opakovat poslední příkaz', 'tab': 'Tab', 'untab': 'Untab', 'bold': 'Nastavit tučně', 'italic': 'Nastavit kurzívu', 'underline': 'Nastavit podtrhnutí', 'strikethrough': 'Nastavit přeškrtnutí', 'removeFormat': 'Ostranit nastavený styl', 'justifyLeft': 'Nastavit zarovnání vlevo', 'justifyCenter': 'Nastavit zarovnání na střed', 'justifyRight': 'Nastavit zarovnání vpravo', 'justifyFull': 'Nastavit zarovnání do bloku', 'insertUnorderedList': 'Aplikovat odrážkový seznam', 'insertOrderedList': 'Aplikovat číselný seznam', 'outdent': 'Zmenšit odsazení aktuálního odstavec', 'indent': 'Odsadit aktuální odstavec', 'formatPara': 'Změnit formátování aktuálního bloku na odstavec (P tag)', 'formatH1': 'Změnit formátování aktuálního bloku na Nadpis 1', 'formatH2': 'Změnit formátování aktuálního bloku na Nadpis 2', 'formatH3': 'Změnit formátování aktuálního bloku na Nadpis 3', 'formatH4': 'Změnit formátování aktuálního bloku na Nadpis 4', 'formatH5': 'Změnit formátování aktuálního bloku na Nadpis 5', 'formatH6': 'Změnit formátování aktuálního bloku na Nadpis 6', 'insertHorizontalRule': 'Vložit horizontální čáru', 'linkDialog.show': 'Zobrazit dialog pro odkaz' }, history: { undo: 'Krok vzad', redo: 'Krok vpřed' }, specialChar: { specialChar: 'SPECIÁLNÍ ZNAKY', select: 'Vyberte speciální znaky' } } }); })(jQuery); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=summernote-cs-CZ.js.map
angular.module('contatooh').factory('Contato',function($resource){ return $resource('/contatos/:id'); });
import { MJMLElement } from 'mjml-core' import React, { Component } from 'react' const tagName = 'mj-table' const parentTag = ['mj-column', 'mj-hero-content'] const endingTag = true const defaultMJMLDefinition = { content: '', attributes: { 'align': 'left', 'cellpadding': '0', 'cellspacing': '0', 'color': '#000', 'container-background-color': null, 'font-family': 'Ubuntu, Helvetica, Arial, sans-serif', 'font-size': '13px', 'line-height': '22px', 'padding-bottom': null, 'padding-left': null, 'padding-right': null, 'padding-top': null, 'padding': '10px 25px', 'table-layout': 'auto', 'vertical-align': null, 'width': '100%' } } @MJMLElement class Table extends Component { styles = this.getStyles() getStyles () { const { mjAttribute, defaultUnit } = this.props return { table: { cellpadding: mjAttribute('cellspadding'), cellspacing: mjAttribute('cellspacing'), color: mjAttribute('color'), fontFamily: mjAttribute('font-family'), fontSize: defaultUnit(mjAttribute('font-size')), lineHeight: mjAttribute('line-height'), tableLayout: mjAttribute('table-layout') } } } render () { const { mjAttribute, mjContent } = this.props return ( <table cellPadding={mjAttribute('cellpadding')} cellSpacing={mjAttribute('cellspacing')} dangerouslySetInnerHTML={{__html: mjContent() }} data-legacy-border="0" style={this.styles.table} width={mjAttribute('width')} /> ) } } Table.tagName = tagName Table.parentTag = parentTag Table.endingTag = endingTag Table.defaultMJMLDefinition = defaultMJMLDefinition export default Table
/* * Guerilla * Copyright 2015, Yahoo Inc. * Copyrights licensed under the MIT License. * * Retrieves the Logcat from an Android device. */ var path = require('path'); var fs = require('fs-extra'); function Logcat (context, exec) { this.context = context; this.exec = exec; this.file = path.join(context.output_dir, 'logcat.txt'); } Logcat.prototype.start = function (callback) { var self = this; var cmd = 'adb'; var args = []; args.push('-s'); args.push(self.context.device.identifier); args.push('logcat'); args.push('-v'); args.push('time'); var options = { log: [true, false, false, false], file: this.file }; self.process = self.exec(cmd, args, options, function () {}); if (callback) callback(); }; Logcat.prototype.stop = function (callback) { if (this.process) this.process.kill(); if (callback) callback(); }; module.exports = Logcat;
(function () { define(["jquery", "datatables", "datatables-tabletools", "datatables-colvis"], function ($) { var achilles_heel = {}; achilles_heel.render = function (datasource) { $('#reportAchillesHeel svg').remove(); $.ajax({ type: "GET", url: getUrlFromData(datasource, "achillesheel"), contentType: "application/json; charset=utf-8", success: function (data) { table_data = []; for (i = 0; i < data.MESSAGES.ATTRIBUTEVALUE.length; i++) { temp = data.MESSAGES.ATTRIBUTEVALUE[i]; message_type = temp.substring(0, temp.indexOf(':')); message_content = temp.substring(temp.indexOf(':') + 1); // RSD - A quick hack to put commas into large numbers. // Found the regexp at: // https://stackoverflow.com/questions/23104663/knockoutjs-format-numbers-with-commas message_content = message_content.replace(/\B(?=(\d{3})+(?!\d))/g, ','); table_data[i] = { 'type': message_type, 'content': message_content }; } datatable = $('#achillesheel_table').DataTable({ dom: 'lfrt<"row"<"col-sm-4" i ><"col-sm-4" T ><"col-sm-4" p >>', tableTools: { "sSwfPath": "js/swf/copy_csv_xls_pdf.swf" }, data: table_data, columns: [ { data: 'type', visible: true, width:200 }, { data: 'content', visible: true } ], pageLength: 15, lengthChange: false, deferRender: true, destroy: true }); $('#reportAchillesHeel').show(); } }); } return achilles_heel; }); })();
scouts = new Meteor.Collection('scouts', { schema: new SimpleSchema({ userId: { type: String, index: 1, unique: true }, scoutId: { type: String, optional: true }, scoutStatusCode: { type: String, optional: true }, scoutLand: { type: String, optional: true }, scoutName: { type: String, optional: true }, scoutBudget: { type: Number, optional: true }, scoutSpent: { type: Number, optional: true } }) }); // Collection2 already does schema checking // Add custom permission rules if needed scouts.allow({ insert : function () { return true; }, update : function () { return true; }, remove : function () { return true; } });
/* global angular: false */ /** * WinchJS Factory - Maintain state of winch * * Written by Sean Cady */ angular.module('winch') .factory('winchFactory', [function() { //Basic API structure var API = { _img: {} }; /** * Register an image * @param URL * @param load * @param validate * @returns {boolean} */ API.registerImg = function(URL, load, validate) { if (typeof load !== 'function') { return false; } if (typeof validate !== 'function') { return false; } if (typeof URL !== 'string' || URL.length < 1) { return false; } if (API._img.hasOwnProperty(URL)) { //If already loaded once (cached) trigger load immediately if (API._img[URL].loaded) { load(); } else { API._img[URL].fnLoad.push(load); API._img[URL].fnValidate.push(validate); } } else { API._img[URL] = { fnLoad: [load], fnValidate: [validate], loaded: false }; } return true; }; /** * Load all images with the same URL * @param URL */ API.loadImage = function(URL) { var index = 0, length; if (API._img.hasOwnProperty(URL)) { length = API._img[URL].fnLoad.length; for (index = 0; index < length; index += 1) { API._img[URL].fnLoad[index](); } API._img[URL] = { loaded: true, fnValidate: [], fnLoad: [] }; } }; /** * Trigger validation of images * @param URL - optional */ API.triggerValidation = function(URL) { var imageIndex, imageKeys, validationIndex, validationLength; if (URL && API._img[URL]) { for (validationIndex = 0; validationIndex < API._img[URL].fnValidate.length; validationIndex += 1) { if (API._img[URL].fnValidate[validationIndex]()) { API.loadImage(URL); } } } else if (!URL) { imageKeys = Object.keys(API._img); for (imageIndex = 0; imageIndex < imageKeys.length; imageIndex += 1) { validationLength = API._img[imageKeys[imageIndex]].fnValidate.length; for (validationIndex = 0; validationIndex < validationLength; validationIndex += 1) { if (API._img[imageKeys[imageIndex]].fnValidate[validationIndex] && API._img[imageKeys[imageIndex]].fnValidate[validationIndex]()) { API.loadImage(imageKeys[imageIndex]); } } } } }; /** * Store the current window Height and Width * @param height * @param width */ API.setWindowView = function(height, width) { API.windowWidth = width; API.windowHeight = height; }; /** * Return window width * @returns number */ API.getWindowWidth = function() { return API.windowWidth; }; /** * Return window height * @returns number */ API.getWindowHeight = function() { return API.windowHeight; }; /** * Returns an object of window bounding * @returns {{top: number, bottom: number, left: number, right: number, vOffset: number, hOffset: number}} */ API.getMasterBox = function() { return { top: 0, bottom: API.windowHeight, left: 0, right: API.windowWidth, vOffset: 100, hOffset: 100 }; }; return API; }]);
exports.up = (knex, Promise) => { return knex.schema.createTable('users', (table) => { table.increments('id') table.string('user_id') // table.string('username') table.string('server_id') table.integer('quest_xp') table.integer('message_xp') table.dateTime('last_msg') }) } exports.down = (knex, Promise) => { return knex.schema.dropTable('users') }
'use strict'; /** * Module dependencies. */ var coursesPolicy = require('../policies/courses.server.policy'), courses = require('../controllers/courses.server.controller'); module.exports = function (app) { // Articles collection routes app.route('/api/courses').all(coursesPolicy.isAllowed) .get(courses.list) .post(courses.create); // Single article routes app.route('/api/courses/:articleId').all(coursesPolicy.isAllowed) .get(courses.read) .put(courses.update) .delete(courses.delete); // Finish by binding the article middleware app.param('articleId', courses.articleByID); };
/* global Flash */ export default class BlobViewer { constructor() { this.switcher = document.querySelector('.js-blob-viewer-switcher'); this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn'); this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn'); this.simpleViewer = document.querySelector('.blob-viewer[data-type="simple"]'); this.richViewer = document.querySelector('.blob-viewer[data-type="rich"]'); this.$fileHolder = $('.file-holder'); let initialViewerName = document.querySelector('.blob-viewer:not(.hidden)').getAttribute('data-type'); this.initBindings(); if (this.switcher && location.hash.indexOf('#L') === 0) { initialViewerName = 'simple'; } this.switchToViewer(initialViewerName); } initBindings() { if (this.switcherBtns.length) { Array.from(this.switcherBtns) .forEach((el) => { el.addEventListener('click', this.switchViewHandler.bind(this)); }); } if (this.copySourceBtn) { this.copySourceBtn.addEventListener('click', () => { if (this.copySourceBtn.classList.contains('disabled')) return this.copySourceBtn.blur(); return this.switchToViewer('simple'); }); } } switchViewHandler(e) { const target = e.currentTarget; e.preventDefault(); this.switchToViewer(target.getAttribute('data-viewer')); } toggleCopyButtonState() { if (!this.copySourceBtn) return; if (this.simpleViewer.getAttribute('data-loaded')) { this.copySourceBtn.setAttribute('title', 'Copy source to clipboard'); this.copySourceBtn.classList.remove('disabled'); } else if (this.activeViewer === this.simpleViewer) { this.copySourceBtn.setAttribute('title', 'Wait for the source to load to copy it to the clipboard'); this.copySourceBtn.classList.add('disabled'); } else { this.copySourceBtn.setAttribute('title', 'Switch to the source to copy it to the clipboard'); this.copySourceBtn.classList.add('disabled'); } $(this.copySourceBtn).tooltip('fixTitle'); } loadViewer(viewerParam) { const viewer = viewerParam; const url = viewer.getAttribute('data-url'); if (!url || viewer.getAttribute('data-loaded') || viewer.getAttribute('data-loading')) { return; } viewer.setAttribute('data-loading', 'true'); $.ajax({ url, dataType: 'JSON', }) .fail(() => new Flash('Error loading source view')) .done((data) => { viewer.innerHTML = data.html; $(viewer).syntaxHighlight(); viewer.setAttribute('data-loaded', 'true'); this.$fileHolder.trigger('highlight:line'); gl.utils.handleLocationHash(); this.toggleCopyButtonState(); }); } switchToViewer(name) { const newViewer = document.querySelector(`.blob-viewer[data-type='${name}']`); if (this.activeViewer === newViewer) return; const oldButton = document.querySelector('.js-blob-viewer-switch-btn.active'); const newButton = document.querySelector(`.js-blob-viewer-switch-btn[data-viewer='${name}']`); const oldViewer = document.querySelector(`.blob-viewer:not([data-type='${name}'])`); if (oldButton) { oldButton.classList.remove('active'); } if (newButton) { newButton.classList.add('active'); newButton.blur(); } if (oldViewer) { oldViewer.classList.add('hidden'); } newViewer.classList.remove('hidden'); this.activeViewer = newViewer; this.toggleCopyButtonState(); this.loadViewer(newViewer); } }
/** * Created by khuongdt on 12/07/2015. * Author : khuongdt * Copyright @ 2015 by OneSoft.,JSC */ goog.provide('com.onesoft.livetube.entity.SCLogout'); goog.require('bigfox.Global'); goog.require('bigfox.core.base.BaseMessage'); goog.require('com.onesoft.livetube.base.LiveTag'); com.onesoft.livetube.entity.SCLogout = function(tag,name,isCore){ goog.base(this,'constructor',tag || com.onesoft.livetube.base.LiveTag.SC_LOGOUT,name || 'SC_LOGOUT', isCore || false); } goog.inherits(com.onesoft.livetube.entity.SCLogout, bigfox.core.base.BaseMessage);
/* jslint node: true */ 'use strict'; var cfg = require('../../../config.json'); exports.validNick = function(nickname) { var regex = /^\w*$/; return regex.exec(nickname) !== null; }; // determine mass from radius of circle exports.massToRadius = function (mass) { return 4 + Math.sqrt(mass) * 6; }; // overwrite Math.log function exports.log = (function () { var log = Math.log; return function (n, base) { return log(n) / (base ? log(base) : 1); }; })(); // get the Euclidean distance between the edges of two shapes exports.getDistance = function (p1, p2) { return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)) - p1.radius - p2.radius; }; exports.randomInRange = function (from, to) { return Math.floor(Math.random() * (to - from)) + from; }; // generate a random position within the field of play exports.randomPosition = function (radius) { return { x: exports.randomInRange(radius, cfg.gameWidth - radius), y: exports.randomInRange(radius, cfg.gameHeight - radius) }; }; exports.uniformPosition = function(points, radius) { var bestCandidate, maxDistance = 0; var numberOfCandidates = 10; if (points.length === 0) { return exports.randomPosition(radius); } // Generate the cadidates for (var ci = 0; ci < numberOfCandidates; ci++) { var minDistance = Infinity; var candidate = exports.randomPosition(radius); candidate.radius = radius; for (var pi = 0; pi < points.length; pi++) { var distance = exports.getDistance(candidate, points[pi]); if (distance < minDistance) { minDistance = distance; } } if (minDistance > maxDistance) { bestCandidate = candidate; maxDistance = minDistance; } else { return exports.randomPosition(radius); } } return bestCandidate; }; exports.findIndex = function(arr, id) { var len = arr.length; while (len--) { if (arr[len].id === id) { return len; } } return -1; }; exports.randomColor = function() { var color = '#' + ('00000' + (Math.random() * (1 << 24) | 0).toString(16)).slice(-6); var c = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color); var r = (parseInt(c[1], 16) - 32) > 0 ? (parseInt(c[1], 16) - 32) : 0; var g = (parseInt(c[2], 16) - 32) > 0 ? (parseInt(c[2], 16) - 32) : 0; var b = (parseInt(c[3], 16) - 32) > 0 ? (parseInt(c[3], 16) - 32) : 0; return { fill: color, border: '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) }; };
export const CODE_LENGTH = 12 export const ALL_DIGITS = /^\d+$/ export const normalizedValue = (value) => { const { length } = value const systemDigitMissing = !value.startsWith('0') return length == CODE_LENGTH - 1 && systemDigitMissing ? '0' + value : value } export const passesCheckDigitVerification = (value) => { const digits = value.split('') const targetCheckDigit = parseInt(digits[CODE_LENGTH - 1], 10) const targetDigits = digits.slice(0, CODE_LENGTH - 1) const sum = targetDigits.reduce(function(total, digit, index) { const isOneBasedOddPositionedNumber = index % 2 === 0 const parsedDigit = parseInt(digit, 10) return total + (isOneBasedOddPositionedNumber ? parsedDigit * 3 : parsedDigit) }, 0) const sumModTen = sum % 10 const checkDigit = sumModTen === 0 ? sumModTen : 10 - sumModTen return checkDigit === targetCheckDigit }
import styled from 'styled-components' const RulesContainer = styled.div` text-align: justify; h3 { margin-bottom: 10px; margin-left: 0; } .summary { margin-left: 10px; font-size: 10pt; line-height: 13pt; font-style: italic; } ` export default RulesContainer
/* eslint-disable */ 'use strict'; const chai = require('chai'); global.chaiAsPromised = require('chai-as-promised'); chai.should(); chai.use(chaiAsPromised); global.expect = chai.expect; global.AssertionError = chai.AssertionError; global.Assertion = chai.Assertion; global.assert = chai.assert;
'use strict'; const stateModule = angular.module('hkRouter', ['ui.router']); stateModule .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { ///////////////////////////// // Redirects and Otherwise // ///////////////////////////// $urlRouterProvider.otherwise("/attractions"); // state provider $stateProvider .state('attractions', { url: '/attractions', templateUrl: 'partials/attraction.html', resolve: { locationResult : [ 'Accessible', function(Accessible) { return Accessible.get('facilities/attractions.json', 'attractions'); }], translateHeader: ['$translate', function($translate) { return $translate('ATTRACTION'); }] }, controller: 'AccessibleCtrl', controllerAs: 'vm' }) .state('shopping_dining', { url: '/shopping_dining', templateUrl: 'partials/attraction.html', resolve: { locationResult : [ 'Accessible', function(Accessible) { return Accessible.get('facilities/shoppings.json', 'shopping-dining'); }], translateHeader: ['$translate', function($translate) { return $translate('SHOPPING'); }] }, controller: 'AccessibleCtrl', controllerAs: 'vm' }) .state('hotels', { url: '/hotels', templateUrl: 'partials/attraction.html', resolve: { locationResult : [ 'Accessible', function(Accessible) { return Accessible.get('facilities/hotels.json', 'hotels'); }], translateHeader: ['$translate', function($translate) { return $translate('HOTEL'); }] }, controller: 'AccessibleCtrl', controllerAs: 'vm' }) .state('other_venues', { url: '/other_venues', templateUrl: 'partials/attraction.html', resolve: { locationResult : [ 'Accessible', function(Accessible) { return Accessible.get('facilities/other_venues.json', 'other-venues'); }], translateHeader: ['$translate', function($translate) { return $translate('OTHERVENUE'); }] }, controller: 'AccessibleCtrl', controllerAs: 'vm' }) // .state('geolocation', // { // url: '/geolocation', // templateUrl: 'partials/geolocation.html', // resolve: { // locationResult : [ 'Accessible', function(Accessible) { // return Accessible.get("facilities/shoppings.json","shopping-dining"); // }] // }, // controller: 'MapCtrl', // controllerAs: 'vm' // }) .state('related_links', { url : '/links', templateUrl : 'partials/link.html', controller : 'LinkCtrl', controllerAs: 'vm' }); }]);
$(function() { setInterval( function() { var seconds = new Date().getSeconds(); var sdegree = seconds * 6; var srotate = "rotate(" + sdegree + "deg)"; $('.dynamic-time').html(moment(new Date()).format("hh:mm:ss A")); $("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate}); }, 1000 ); setInterval( function() { var hours = new Date().getHours(); var mins = new Date().getMinutes(); var hdegree = hours * 30 + (mins / 2); var hrotate = "rotate(" + hdegree + "deg)"; $("#hour").css({"-moz-transform" : hrotate, "-webkit-transform" : hrotate}); }, 1000 ); setInterval( function() { var mins = new Date().getMinutes(); var mdegree = mins * 6; var mrotate = "rotate(" + mdegree + "deg)"; $("#min").css({"-moz-transform" : mrotate, "-webkit-transform" : mrotate}); }, 1000 ); });
angular .module('AngularCommunicator', []) .provider('angularCommunicatorService', function() { var registeredListeners = {}; function buildHierarchicalStructure(reg, splitName, callback) { (!reg[splitName[0]]) && (reg[splitName[0]] = {listeners: []}); if(splitName.length === 1) { reg[splitName[0]].listeners.push(callback); return; } var registered = reg[splitName[0]]; splitName.splice(0, 1); buildHierarchicalStructure(registered, splitName, callback); } function unRegisterListener(reg, splitName) { if(splitName.length === 1) { reg[splitName[0]] = {listeners: []}; return; } var registered = reg[splitName[0]]; splitName.splice(0, 1); unRegisterListener(registered, splitName); } function findNodeListenersToExecute(reg, splitName, params, $exceptionHandler) { if(splitName.length === 1) { execNodeListeners(reg[splitName[0]], params, $exceptionHandler); return; } var registered = reg[splitName[0]]; splitName.splice(0, 1); findNodeListenersToExecute(registered, splitName, params); } function execNodeListeners(reg, params, $exceptionHandler) { for(var i = 0; i < reg.listeners.length; i++) { try { reg.listeners[i](params); } catch(e) { $exceptionHandler(e); } } var children = Object.keys(reg).filter(function(elem) { return elem !== 'listeners'; }); for(var child = 0; child < children.length; child++) { execNodeListeners(reg[children[child]], params, $exceptionHandler); } } function isEmptyObject(obj) { return Object.keys(obj).length === 0 && JSON.stringify(obj) === JSON.stringify({}); } function isInvalidKey(key) { return typeof key !== 'string'; } this.$get = ['$exceptionHandler', function($exceptionHandler) { var registerHierarchicalListener = function(key, listener) { if(arguments.length < 2) { throw 'Invalid number of arguments'; } if(isInvalidKey(key)) { throw 'Invalid key'; } buildHierarchicalStructure(registeredListeners, key.split(':'), listener); return function() { unRegisterListener(registeredListeners, key.split(':')); } }; var removeRegisteredListener = function(key) { if(isInvalidKey(key)) { throw 'Invalid key'; } if(isEmptyObject(registeredListeners)) { return; } unRegisterListener(registeredListeners, key.split(':')) }; var execGroupedListeners = function(keys, params) { if(Array.isArray(keys)) { if(isEmptyObject(registeredListeners)) { return; } var args = Array.isArray(params) ? params : [params]; for(var i = 0; i < keys.length; i++) { findNodeListenersToExecute(registeredListeners, keys[i].split(':'), args[i] || args[0], $exceptionHandler); } return; } if(isInvalidKey(keys)) { throw 'Invalid key'; } if(isEmptyObject(registeredListeners)) { return; } findNodeListenersToExecute(registeredListeners, keys.split(':'), params, $exceptionHandler); }; var clearListeners = function() { registeredListeners = {}; }; return { on: registerHierarchicalListener, remove: removeRegisteredListener, exec: execGroupedListeners, clear: clearListeners }; }]; });
import React from 'react'; import SvgImage from 'components/svg-image'; import ChartLabel from 'components/chart-label'; import { getLayout } from 'layouts/flexbox'; import getCenter from 'decorators/get-center'; @getCenter export default class HorizontalBarDetail extends React.Component { static propTypes = { height: React.PropTypes.number.isRequired, icon: React.PropTypes.string, iconHeight: React.PropTypes.number, label: React.PropTypes.string, width: React.PropTypes.number.isRequired, } static defaultProps = { height: 0, icon: '', iconHeight: 0, label: '', width: 0, } state = { layout: {}, } componentDidMount() { this.setStateFromProps(this.props); } componentWillReceiveProps(nextProps) { this.setStateFromProps(nextProps); } getLayout(props) { return getLayout(React.findDOMNode(this), { alignItems: 'center', flexDirection: 'row', flexWrap: 'nowrap', height: props.height, justifyContent: 'flex-end', width: props.width, }, [ {style: {marginRight: 10}}, {style: {marginRight: 10}}, ]); } setStateFromProps(props) { this.setState({ centerY: this.getCenter(props.height), layout: this.getLayout(props), }); } render() { return ( <g className={'horizontal-bar-detail'}> {this.props.label ? ( <ChartLabel className={'horizontal-bar-detail-label'} text={this.props.label} x={this.state.layout.children ? this.state.layout.children[0].left : 0} y={this.state.centerY} /> ) : null} {this.props.icon ? ( <SvgImage className={'horizontal-bar-detail-icon'} height={this.props.iconHeight} url={this.props.icon} width={this.props.iconHeight} x={this.state.layout.children ? this.state.layout.children[1].left : 0} y={this.state.layout.children ? this.state.layout.children[1].top : 0} /> ) : null} </g> ); } }
;(function(jqi, $, undefined) { function Dive(index, $step, $previous, options) { var z = $step.attr('data-z'), x = $previous.attr('data-x'), y = $previous.attr('data-y'); if (!z) z = -2000; else z = parseInt(z) - 2000; $step.attr({'data-z' : z, 'data-x' : x, 'data-y' : y }); return this; } jqi.Dive = Dive; }(jqImpress, jQuery));
/* 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("devtools","ko",{title:"구성 요소 정보",dialogName:"다이얼로그 윈도우 이름",tabName:"탭 이름",elementId:"요소 ID",elementType:"요소 형식"});
/** * Title CountFactors * URL https://codility.com/programmers/task/count_factors/ * * Author Norman Gamage <norman.gamage@gmail.com> * Version 2.0 * Last Update 2016 Jul 02 */ function solution(N) { var cnt = 0, i; for (i = 1; i <= Math.sqrt(N); i++) { if (N % i === 0) { cnt += (i * i === N) ? 1 : 2; } } return cnt; }
jsonp({"cep":"58745000","cidade":"Imaculada","uf":"PB","estado":"Para\u00edba"});
import React, { PropTypes } from 'react' import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as TinderActions from '../actions/tinderActions'; import Profile from '../components/Profile'; import '../sass/matchesPage.scss'; const MatchesPage = React.createClass({ componentWillMount() { this.actions = bindActionCreators(TinderActions, this.props.dispatch); }, componentDidMount: function() { this.actions.getHistory(); }, render () { let {tinderStore} = this.props; return ( <div className="matches-page"> <div className="profiles"> { tinderStore.matches.map(profile=> <Profile key={profile._id} profile={profile}/> ) } </div> </div> ) } }) export default connect(state => { return {tinderStore : state.tinder.toJS()} })(MatchesPage);
require('newrelic'); var _ = require("underscore"); var Twit = require('twit'), debug = false; // Express server page: var express = require('express'); var app = express(); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); }); // Work out whether a search term matches a given tweet function hasKeyword(searchterms, text){ return _.some(searchterms,function(d){ return new RegExp(d, 'ig').test(text); }); } var valid = function (tweet) { // Don't reply to tweets mentioning November 19th: var November = hasKeyword(['November','Nov','19','19th'], tweet.text); // Don't reply to Richard Herring var Richard = tweet.user.screen_name === 'Herring1967'; // Don't reply to RTs var RT = tweet.retweeted_status !== undefined; return !November && !Richard && !RT; }; // Matched array of keywords and corresponding replies: var keywords = [ "international men's day", "international man's day", "international mens day", "international mans day", "national men's day", "national man's day", "national mens day", "national mans day" ]; var reply = "It's November 19th."; var backlog = []; var auto = true; // Start the twitter stream: var T = new Twit({ consumer_key: process.env.consumer_key, consumer_secret: process.env.consumer_secret, access_token: process.env.access_token, access_token_secret: process.env.access_token_secret }); var stream = T.stream('statuses/filter', { track: keywords }); stream.on('tweet', function (tweet) { if (valid(tweet)) { if (auto) { // Reply: sendTweet(tweet); } else { // Add tweet to backlog: backlog.push(tweet); } } }); function sendTweet(tweet){ var response = '@'+ tweet.user.screen_name + ' ' + reply; if (!debug) { var params = { status: response, in_reply_to_status_id: tweet.id_str }; T.post('statuses/update', params, function (err, reply) { if (err) { console.log(err); } else { var now = new Date(); console.log('[' + now.toJSON() + '] SENT: ' + response); } }); } else { var now = new Date(); console.log('[' + now.toJSON() + '] ' + response); } } stream.on('warning', function (item) { console.log('WARNING: ' + item); }); stream.on('disconnect', function (item) { console.log('Stream disconnected.'); }); stream.on('connect', function (item) { console.log('Stream connected.'); }); stream.on('reconnect', function (item) { console.log('Stream reconnected.'); }); // Handle AJAX requests app.get('/query', function(req, res){ var p = req.query; if (p.clear === 'clear') { backlog = []; } if (p.approve !== undefined) { var tweet = _.find(backlog,function(d){ return +d.id === +p.id; }); var now = new Date(); if (p.approve === 'true' || p.approve === true) { console.log('[' + now.toJSON() + '] Approved tweet: @' + tweet.user.screen_name + ':' + tweet.text); sendTweet(tweet); } else { console.log('[' + now.toJSON() + '] Rejected tweet: @' + tweet.user.screen_name + ':' + tweet.text); } backlog = _.reject(backlog,function(d){ return +d.id === +p.id; }); } if (p.mode !== undefined) { // Toggle mode auto = p.mode !== 'Auto'; } res.send({ mode: auto ? 'Auto' : 'Manual', backlog: backlog }); });
jsonp({"cep":"85607000","cidade":"Jacutinga","uf":"PR","estado":"Paran\u00e1"});
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("devtools","he",{title:"מידע על האלמנט",dialogName:"שם הדיאלוג",tabName:"שם הטאב",elementId:"ID של האלמנט",elementType:"סוג האלמנט"});
app.factory("ActivityIndexService",ActivityIndexService); ActivityIndexService.$inject = ['$http']; function ActivityIndexService($http){ return {getActivities: function(offsets){ var url = "/index_pagination?page="+offsets; return $http.get(url); } } } app.factory("ActivityOtherUserService",ActivityOtherUserService); ActivityOtherUserService.$inject = ['$http']; function ActivityOtherUserService($http){ return { getFeed:function(user_id,trackable_id,trackable_type){ var tr_type = angular.lowercase(trackable_type); var url = "/show_others_details?trackable_id="+trackable_id+"&user_id="+user_id+"&trackable_type="+trackable_type; return $http.get(url); } } } app.factory("ActivityRemoveService",ActivityRemoveService); ActivityRemoveService.$inject = ['$resource']; function ActivityRemoveService($resource){ return { removeFeed:function(){ return $resource("/activities/remove_activity"); } } }
class Controller extends Phaser.Scene { constructor () { super(); } resize (width, height) { if (width === undefined) { width = this.game.config.width; } if (height === undefined) { height = this.game.config.height; } this.cameras.resize(width, height); } }
angular.module('ui-components') .factory('DatetimeRange', function DatetimeRangeFactory(DatetimeHelper) { return function DatetimeRange() { var data = { 'startDate': null, 'endDate' : null, 'allDay' : false }, startTimeCache, endTimeCache, /** * Sets start or end date with ISOString. * * @param {string} key The data key to update. Can be 'start' or 'end'. * @param {string} date Any date format that moment accepts. * @param {object} time The time object from pickadate. * @private */ setDateTime = function (key, date, time) { var datetime = DatetimeHelper.create(date, time); data[key + 'Date'] = datetime; return this; }, /** * Convenience to ensure the time is set alongside the date. * * @public */ setStartDate = function (date) { setDateTime('start', date, startTimeCache); console.info('changed start date to:'); console.info(date); return this; }, /** * Convenience to ensure the time is set alongside the date. * * @public */ setEndDate = function (date) { setDateTime('end', date, endTimeCache); console.info('changed end date to:'); console.info(date); return this; }, /** * @public */ setStartTime = function (time) { startTimeCache = time; data.startDate = DatetimeHelper.create(data.startDate, time); console.info('changed start time to:'); console.info(data.startDate); return this; }, /** * @public */ setEndTime = function (time) { endTimeCache = time; data.endDate = DatetimeHelper.create(data.endDate, time); console.info('changed end time to:'); console.info(data.endDate); return this; }, /** * Sets the all day flag and updates the date string to reflect an * all day event. * * @todo What happens if something is not all day? Should we cache the previous * times and replace them into the date strings? * * @public * @param {Boolean} isAllDay */ setAllDay = function (isAllDay) { console.info('changed all day to:'); console.log(isAllDay); if (isAllDay) { // startDate and endDate always exist setDateTime('start', DatetimeHelper.getStartOfDay(data.startDate)); setDateTime('end', DatetimeHelper.getEndOfDay(data.endDate)); } else { setStartDate(data.startDate); setEndDate(data.endDate); } }, isSameDay = function () { return DatetimeHelper.getStartOfDay(data.startDate) === DatetimeHelper.getStartOfDay(data.endDate); }, /** * @public */ getData = function () { return data; }; // API return { 'setStartDate': setStartDate, 'setEndDate': setEndDate, 'setStartTime': setStartTime, 'setEndTime': setEndTime, 'setAllDay': setAllDay, 'isSameDay': isSameDay, 'getData': getData }; }; });
if (typeof $ != 'function') { var $ = jQuery; } $(document).ready(function () { //var table = $('.price-body tr'); $('.price-body tr:even').addClass('odd'); $('.price-body td:not(:first-child)').addClass('c'); $('.price-body tr').hover( function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); } ); $("ul.tabs").tabs("div.panes > div"); $("ul.tabss").tabs("div.paness > div"); });
// slideshow settings $(document).ready(function() { $('.slideshow').cycle({ fx: 'fade' // transition type : fade, scrollUp, shuffle, etc... }); }); $(document).ready( function() { Cufon.replace('.footer-one-third h2', { fontFamily: 'ColaborateLight', fontSize: '20px', color:'#cdb380' } ); Cufon.replace('.footer-one-third h3', { fontFamily: 'ColaborateLight', fontSize: '20px', color:'#cdb380' } ); }); $(document).ready( function() { Cufon.replace('#content h1', { fontFamily: 'ColaborateLight', fontSize: '40px', color:'#000000' } ); Cufon.replace('#content h2', { fontFamily: 'ColaborateLight', fontSize: '22px', color:'#000000' } ); Cufon.replace('#content h3', { fontFamily: 'ColaborateLight', fontSize: '18px', color:'#000000' } ); Cufon.replace('h3.post-title', { fontFamily: 'ColaborateLight', fontSize: '30px', color:'#000000' } ); Cufon.replace('h2.date-header', { fontFamily: 'ColaborateLight', fontSize: '10px', color:'#000000' } ); $('.rounded').corner(); $('#sidebar .widget').corner(); });
/** * @extends storeLocator.StaticDataFeed * @constructor */ function MedicareDataSource() { jQuery.extend(this, new storeLocator.StaticDataFeed); var csv_filepath = Drupal.settings.fc_storelocator_google.csv_filepath; var that = this; jQuery.get(csv_filepath, function(data) { that.setStores(that.parse_(data)); }); } /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( // new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), // new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * @private * @param {string} csv * @return {!Array.<!storeLocator.Store>} */ MedicareDataSource.prototype.parse_ = function(csv) { var stores = []; var rows = csv.split('\n'); var headings = this.parseRow_(rows[0]); for (var i = 1, row; row = rows[i]; i++) { row = this.toObject_(headings, this.parseRow_(row)); var features = new storeLocator.FeatureSet; // features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair)); // features.add(this.FEATURES_.getById('Audio-' + row.Audio)); var position = new google.maps.LatLng(row.Ycoord, row.Xcoord); // var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', '); // var locality = this.join_([row.Locality, row.Postcode], ', '); var store = new storeLocator.Store(row.uuid, position, features, { title: row.title, address: row.detail // hours: row.Hrs_of_bus }); stores.push(store); } return stores; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Very rudimentary CSV parsing - we know how this particular CSV is formatted. * IMPORTANT: Don't use this for general CSV parsing! * @private * @param {string} row * @return {Array.<string>} */ MedicareDataSource.prototype.parseRow_ = function(row) { // Strip leading quote. if (row.charAt(0) == '"') { row = row.substring(1); } // Strip trailing quote. There seems to be a character between the last quote // and the line ending, hence 2 instead of 1. if (row.charAt(row.length - 2) == '"') { row = row.substring(0, row.length - 2); } row = row.split('","'); return row; }; /** * Creates an object mapping headings to row elements. * @private * @param {Array.<string>} headings * @param {Array.<string>} row * @return {Object} */ MedicareDataSource.prototype.toObject_ = function(headings, row) { var result = {}; for (var i = 0, ii = row.length; i < ii; i++) { result[headings[i]] = row[i]; } return result; };
/* global angular */ angular.module("app").factory("cepsAPI", function ($http, config) { var _getCeps = function () { return $http.get(config.baseUrl + "DbAuditPronatec-3.2/api/ceps"); }; var _getCep = function (id) { return $http.get(config.baseUrl + "DbAuditPronatec-3.2/api/ceps/" + id); }; var _saveCep = function (cep) { return $http.post(config.baseUrl + "DbAuditPronatec-3.2/api/ceps", cep); }; var _getDelete = function (id) { return $http.delete(config.baseUrl + "DbAuditPronatec-3.2/api/ceps/" + id); }; var _deleteCep = function (id) { return $http.delete(config.baseUrl + "DbAuditPronatec-3.2/api/ceps/" + id); }; return { getCeps : _getCeps, getCep : _getCep, saveCep : _saveCep, getDelete : _getDelete, deleteCep : _deleteCep//delete }; });
(function($) { $.fn.pypi = function(options) { if(typeof(options) == 'undefined') options = {} var package_ = options.package; if(typeof(package_) == 'undefined') package_ = this.attr("data-package"); if(typeof(package_) == 'undefined') throw "A package-name has not been provided."; var package_url = "https://pypi.python.org/pypi/" + package_; var parent = this; function received(data) { var name = data.info.name var counts = data.info.downloads; last_month = counts.last_month * 1; last_week = counts.last_week * 1; last_day = counts.last_day * 1; var html = "<div class=\"pypi-container\">" + "<div class=\"pypi-title\">" + "<em><a href=\"" + package_url + "\" target=\"_blank\">" + name + "</a></em><br />usage" + "</div>" + "<div class=\"pypi-row\">" + "<div class=\"pypi-label\">" + "Last Day:" + "</div>" + "<div class=\"pypi-count\">" + last_day + "</div>" + "<div class=\"pypi-float-stop\"></div>" + "</div>" + "<div class=\"pypi-row\">" + "<div class=\"pypi-label\">" + "Last Week:" + "</div>" + "<div class=\"pypi-count\">" + last_week + "</div>" + "<div class=\"pypi-float-stop\"></div>" + "</div>" + "<div class=\"pypi-row\">" + "<div class=\"pypi-label\">" + "Last Month:" + "</div>" + "<div class=\"pypi-count\">" + last_month + "</div>" + "<div class=\"pypi-float-stop\"></div>" + "</div>" + "</div>"; parent.html(html); } var url = package_url + "/json?callback=?"; $.getJSON(url, received); return this; }; }(jQuery));
app.controller("PositionMaintainController", function ($rootScope, $scope, PowerLine, NowPosition) { $rootScope.activeLeftMenu = $rootScope.leftMenus[2]; $rootScope.showLoading(); initBMap("bmap1", $scope, function () { $rootScope.closeLoading(); NowPosition.startListener(function () { $scope.map.removeOverlay($scope.mapArrow); $scope.map.removeOverlay($scope.mapAccuracy); if ($scope.mapPolyline != null) { $scope.mapPolyline.forEach(function (polyline) { $scope.map.removeOverlay(polyline); $scope.map.addOverlay(polyline); }); } var _point = new BMap.Point(NowPosition.getPosition().longitude, NowPosition.getPosition().latitude); if (NowPosition.getPosition().compassHead != null) { $scope.mapArrow = new BMap.Marker(_point, { icon: new BMap.Symbol(BMap_Symbol_SHAPE_FORWARD_CLOSED_ARROW, { scale: 2, anchor: new BMap.Size(0, 8), strokeWeight: 0, strokeColor: "green", rotation: NowPosition.getPosition().compassHead, fillColor: "green", fillOpacity: 1 }) }); } else { $scope.mapArrow = new BMap.Marker(_point, { icon: new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, { scale: 4, strokeWeight: 0, strokeColor: "red", fillColor: "red", fillOpacity: 1 }) }); } $scope.mapAccuracy = new BMap.Circle(_point, NowPosition.getPosition().accuracy, { strokeColor: "blue", strokeWeight: 1, fillOpacity: 0.3 }); $scope.map.addOverlay($scope.mapAccuracy); $scope.map.addOverlay($scope.mapArrow); }); $scope.showPowerline(); }); $scope.showPowerline = function () { $rootScope.showLoading(); $scope.powerline = PowerLine.getPowerline(); $scope.mapPolyline = []; if ($scope.powerline != null) { var beginPoint = new BMap.Point( $scope.powerline.location.startLongitude, $scope.powerline.location.startLatitude); var endPoint = new BMap.Point( $scope.powerline.location.endLongitude, $scope.powerline.location.endLatitude); $scope.map.centerAndZoom(beginPoint, 25); $scope.map.addOverlay(new BMap.Marker(beginPoint)); $scope.map.addOverlay(new BMap.Marker(endPoint)); var polyline = new BMap.Polyline([beginPoint, endPoint], { strokeColor: "red", strokeWeight: 5, strokeOpacity: 0.5 }); $scope.map.addOverlay(polyline); var routePolicy = [ BMAP_DRIVING_POLICY_LEAST_TIME, BMAP_DRIVING_POLICY_LEAST_DISTANCE, BMAP_DRIVING_POLICY_AVOID_HIGHWAYS ]; var driving = new BMap.DrivingRoute( $scope.map, { renderOptions: { map: $scope.map, autoViewport: true }, policy: routePolicy[0] }); navigator.geolocation.getCurrentPosition(function (position) { BMap.Convertor.translate(new BMap.Point( position.coords.longitude, position.coords.latitude), 0, function (point) { driving.search(new BMap.Point(point.lng, point.lat), beginPoint); driving.setPolylinesSetCallback(function () { $scope.map.getOverlays().forEach(function (overlay) { if (overlay.toString() == "[object Polyline]") { $scope.mapPolyline.push(overlay); } }); }); $rootScope.closeLoading(); }); }, function (error) { $rootScope.closeLoading(); $rootScope.showError("无法定位,请重试"); }); } else { $rootScope.closeLoading(); } }; $scope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) { if (toState.name == "app.maintain.position" && fromState.name == "app.maintain.powerline") { if ($scope.map != null) { $scope.map.clearOverlays(); $scope.showPowerline(); } } }); $scope.$on("$destroy", function () { NowPosition.stopListener(); }); });
const true_ = ['yes', 'y', 'true', 't', 'on', 'enabled', '1', '-1']; const false_ = ['no', 'n', 'false', 'f', 'off', 'disabled', '0']; module.exports = function validateNumber(expr, allowNull, options) { expr = expr.toLowerCase(); if (~true_.indexOf(String(expr))) { return true; } else if (~false_.indexOf(String(expr))) { return false; } else if (expr === null && allowNull) { return null; } else { throw new Error('Invalid boolean: ' + JSON.stringify(expr)); } };
/** * Created by qufan on 2015/7/28 0028. */ var Sequelize = require('sequelize'); var sequelize = require('./../lib/mysqlHelper'); var db = sequelize.db; var orm_video_cc_callback = db.define('video_cc_callback', { id:{ type:Sequelize.INTEGER, primaryKey:true, autoIncrement:true }, ctime:{type:Sequelize.DATE}, videoid:{type:Sequelize.STRING}, status:{type:Sequelize.STRING}, during:{type:Sequelize.INTEGER}, image:{type:Sequelize.STRING}, json:{type:Sequelize.STRING} }, { tableName:'video_cc_callback' } ); module.exports = orm_video_cc_callback;
/* ************************************************************************ 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) ************************************************************************ */ /* ************************************************************************ ************************************************************************ */ /** * Optimized version of SuperTextile * @deprecated: Old stuff, even does not work correctly. String performance is * quite slow. Better to omit these stuff at all at client side. */ qx.Class.define("qx.legacy.html.Textile", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Textilizes a string * http://www.textism.com/tools/textile/ * * @param s {String} Text to be textilized. * @return {String} The textilized text. */ textilize : function(s) { var r = s; // quick tags first var qtags = [ [ "\\*", "strong" ], [ "\\?\\?", "cite" ], [ "\\+", "ins" ], [ "~", "sub" ], [ "\\^", "sup" ], [ "@", "code" ] ]; var ttag, htag, re, line, lines, nr, changed, inlist, listtype; for (var i=0; i<qtags.length; i++) { ttag = qtags[i][0]; htag = qtags[i][1]; re = new RegExp(ttag + "\\b(.+?)\\b" + ttag, "g"); r = r.replace(re, "<" + htag + ">" + "$1" + "</" + htag + ">"); } // underscores count as part of a word, so do them separately re = new RegExp("\\b_(.+?)_\\b", "g"); r = r.replace(re, "<em>$1</em>"); // jeff: so do dashes re = new RegExp("[\s\n]-(.+?)-[\s\n]", "g"); r = r.replace(re, "<del>$1</del>"); // links re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)', 'g'); r = r.replace(re, '<a href="$3" title="$2">$1</a>'); re = new RegExp('"\\b(.+?)\\b":([^\\s]+)', 'g'); r = r.replace(re, '<a href="$2">$1</a>'); // images re = new RegExp("!\\b(.+?)\\(\\b(.+?)\\b\\)!", "g"); r = r.replace(re, '<img src="$1" alt="$2">'); re = new RegExp("!\\b(.+?)\\b!", "g"); r = r.replace(re, '<img src="$1">'); // block level formatting // Jeff's hack to show single line breaks as they should. // insert breaks - but you get some....stupid ones re = new RegExp("(.*)\n([^#\*\n].*)", "g"); r = r.replace(re, "$1<br />$2"); // remove the stupid breaks. re = new RegExp("\n<br />", "g"); r = r.replace(re, "\n"); lines = r.split("\n"); nr = ""; for (var i=0; i<lines.length; i++) { line = lines[i].replace(/\s*$/, ""); changed = 0; if (line.search(/^\s*bq\.\s+/) != -1) { line = line.replace(/^\s*bq\.\s+/, "\t<blockquote>") + "</blockquote>"; changed = 1; } // jeff adds h#. if (line.search(/^\s*h[1-6]\.\s+/) != -1) { re = new RegExp("h([1-6])\.(.+)", "g"); line = line.replace(re, "<h$1>$2</h$1>"); changed = 1; } if (line.search(/^\s*\*\s+/) != -1) { // for bullet list; make up an liu tag to be fixed later line = line.replace(/^\s*\*\s+/, "\t<liu>") + "</liu>"; changed = 1; } if (line.search(/^\s*#\s+/) != -1) { // # for numeric list; make up an lio tag to be fixed later line = line.replace(/^\s*#\s+/, "\t<lio>") + "</lio>"; changed = 1; } if (!changed && (line.replace(/\s/g, "").length > 0)) { line = "<p>" + line + "</p>"; } lines[i] = line + "\n"; } // Second pass to do lists inlist = 0; listtype = ""; for (var i=0; i<lines.length; i++) { line = lines[i]; if (inlist && listtype == "ul" && !line.match(/^\t<liu/)) { line = "</ul>\n" + line; inlist = 0; } if (inlist && listtype == "ol" && !line.match(/^\t<lio/)) { line = "</ol>\n" + line; inlist = 0; } if (!inlist && line.match(/^\t<liu/)) { line = "<ul>" + line; inlist = 1; listtype = "ul"; } if (!inlist && line.match(/^\t<lio/)) { line = "<ol>" + line; inlist = 1; listtype = "ol"; } lines[i] = line; } r = lines.join("\n"); // jeff added : will correctly replace <li(o|u)> AND </li(o|u)> r = r.replace(/li[o|u]>/g, "li>"); return r; } } });
'use strict'; angular .module('scruman') .controller('LoginController', LoginController); LoginController.$inject = ['$http', '$auth', '$location']; function LoginController($http, $auth, $location) { var vm = this; vm.authenticate = authenticate; isAuthenticated(); function authenticate(provider) { $auth.authenticate(provider).then(authSuccess).catch(loginError); function authSuccess(response) { console.log(response); isAuthenticated(); } function loginError(errors) { console.log(errors); } } function isAuthenticated() { if ($auth.isAuthenticated()) { $location.path('/dashboard'); } return false; } }
define([ 'taoQtiItem/qtiCreator/widgets/states/factory', 'taoQtiItem/qtiCreator/widgets/interactions/states/Answer', 'taoQtiItem/qtiCreator/widgets/interactions/helpers/answerState' ], function(stateFactory, Answer, answerStateHelper){ var ChoiceInteractionStateAnswer = stateFactory.extend(Answer, function(){ //forward to one of the available sub state, according to the response processing template answerStateHelper.forward(this.widget); }, function(){ }); return ChoiceInteractionStateAnswer; });
var Gelato_Pulse = { form : null, init: function() { Gelato_Pulse.form = jQuery( '.pulse-form' ); jQuery('<input />') .attr( 'type', 'hidden' ) .attr( 'class', 'ss_synctime' ) .attr( 'name', 'ss_synctime' ) .appendTo( Gelato_Pulse.form ); Gelato_Pulse.form.find( 'textarea').keyup( function() { Gelato_Media.pauseForModule(); } ); Gelato_Pulse.form.submit( function( e ) { console.log( Gelato_Media.media.roundTime()); jQuery('.ss_synctime').val( Gelato_Media.media.roundTime() ); Gelato_Media.playForModule(); } ); }, onContentLoad: function() { if ( typeof CTLT_Stream != 'undefined' ) { // Check for stream activity CTLT_Stream.on( 'server-push', Gelato_Pulse.listen ); } Gelato_Media.media.on( 'loadedmetadata', Gelato_Pulse.loadPulses ); Gelato_Media.media.on( 'loadedmetadata', Gelato_Pulse.loadMarkers ); }, listen: function( data ) { if ( data.type == 'pulse' ) { // We are interested var pulse_data = jQuery.parseJSON(data.data); Gelato_Pulse.addPulse( pulse_data, pulse_data.synctime, true ); } }, loadMarkers: function() { if( typeof gelatoScoop.bookmarks != 'undefined') { for ( index in gelatoScoop.bookmarks.list ) { var bookmark = gelatoScoop.bookmarks.list[index]; Gelato_Media.media.pulse( { start: bookmark.synctime, end: Gelato_Media.media.duration(), text: '<a class="bookmark" onclick="Gelato_Media.skipTo('+bookmark.synctime+');">'+bookmark.title+'<span class="time">'+bookmark.time+'</span></a>', sort: true, target: "pulse-list", } ); } } }, loadPulses: function() { var list = gelatoScoop.pulse; console.log(list); for ( index in list ) { Gelato_Pulse.addPulse( list[index], list[index].synctime, false ); } }, addPulse: function( data, start, sort ) { var new_pulse = Pulse_CPT_Form.single_pulse_template( data ); Gelato_Media.media.pulse( { start: start, end: Gelato_Media.media.duration(), text: new_pulse, sort: sort, target: "pulse-list", } ); }, } Gelato_Pulse.init(); document.addEventListener( "DOMContentLoaded", Gelato_Pulse.onContentLoad, false );
const Slider = require('./hooters/slider.js'); window.SETTINGS.addDomScanListener(function ($scanContainer) { window.SETTINGS.initElement($scanContainer, '[data-slider]', function() { var options = { stagePadding: 330, margin: 0, items: 1, loop: true, smartSpeed: 450, fluidSpeed: 450, dragEndSpeed: 450, dots: true, dotsContainer: '.bullet-nav', dotsContainerTemplate: '.bullet-nav-template' }; new Slider(this, options); }); window.SETTINGS.initElement($scanContainer, '[data-slider-linked]', function() { var $slider = this.find('.owl-carousel'); var $thumbs = this.find('.thumbs'); var animation = $slider.data('animation-style') ? $slider.data('animation-style') : false; console.log(animation); var owl = $slider.owlCarousel({ items: 1, dots: false, mouseDrag: false, touchDrag: false, pullDrag: false, animateOut: animation }); $thumbs.on('click', 'a', function(event) { var idx = $(this).index(); $thumbs.find('a').removeClass('is-active'); $(this).addClass('is-active'); $slider.trigger('to.owl.carousel', [idx, 200, true]); }); }); });
$(document).ready(function() { status('Choose a file :)'); var timerId; timerId = setInterval(function() { if($('#userPhotoInput').val() !== '') { clearInterval(timerId); $('#uploadForm').submit(); } }, 500); $('#uploadForm').submit(function() { status('uploading the file ...'); $(this).ajaxSubmit({ dataType: 'text', error: function(xhr) { status('Error: ' + xhr.status); }, success: function(response) { try { response = $.parseJSON(response); } catch(e) { status('Bad response from server'); return; } if(response.error) { status('Oops, something bad happened'); return; } var imageUrlOnServer = response.path; status('Success, file uploaded to:' + imageUrlOnServer); } }); return false; }); function status(message) { $('#status').text(message); } });
let path = require('path'); let fs = require('fs'); let Site = require('./Site.js'); let option = require('optionJS'); let File = require('./File.js'); let Font = require('./Font.js'); let Style = require('./Style.js'); let Script = require('./Script.js'); // 帮助信息 function showHelp() { console.log('使用方法:'); console.log(' -d --domain=feDomain\t设定域名'); console.log(' -o --out=outputPath\t目标目录'); console.log(' -w --watch\t\t开启监听'); console.log(' -v --version\t\t显示版本号并退出'); console.log(' -h --help\t\t显示帮助信息并退出'); process.exit(0); }; // 转换绝对路径 function toAbsolute(cwd, value) { let foo = value; if (!path.isAbsolute(value)) { foo = path.normalize(path.join(cwd, value)); } return foo.length ? foo : cwd; } // 参数检查 function argCheck(args, cwd = '.') { if (args['version']) { console.log('fe-builder 0.1 (C) 2017 JamesWatson LICENSE GPL2.0'); process.exit(0); } if (args['help'] || !args.out || '' === args.out || !args.default || '' === args.default || !args.domain || '' === args.domain) { showHelp(); } cwd = fs.realpathSync(cwd); args['default'] = toAbsolute(cwd, args['default']); args['out'] = toAbsolute(cwd, args['out']); } // 编译字体文件 function mkFont(input, incName, outFontFile, outCssFile, callback) { let iconFont = new Font(input); let style = `@font-face{font-family:"${iconFont.fontName}";src:url(${incName}?_=${new Date().getTime()}) format("woff")}.${iconFont.fontName}{display:inline;vertical-align: middle}.${iconFont.fontName}:after{display:inline;width:1em;font-family:"${iconFont.fontName}";font-style:normal}`; let writed = 0; // 生成svg字体文件 iconFont.on('toSvg', () => { // 转成woff iconFont.toWOFF(); // 拼装css style += iconFont.fontVector.map((icon) => { return `.${iconFont.fontName}.icon-${icon.name}:after{content:"\\${icon.code}"}`; }).join(' '); // 写入woff文件 iconFont .on('writed', (err) => { writed++; if ((err || 2 === writed) && callback) { writed += 2; let handle = setTimeout(() => { clearTimeout(handle); callback(err); }, 0); } }) .writeWoff(outFontFile); // 写入css文件 new Style(style) .compress() .on('writed', (err) => { writed++; if ((err || 2 === writed) && callback) { writed += 2; let handle = setTimeout(() => { clearTimeout(handle); callback(err); }, 0); } }).write(outCssFile); }); } let foo = { '.less': function(fileObj, info) { return new Promise((resolve, reject) => { let styleFile = new Style(fileObj); styleFile.fileName = info.srcFileName; styleFile .less() .then(() => { // 解析less完成 styleFile.compress(); resolve([styleFile]); }) .catch(reject); }); }, '.es6': function(fileObj) { let scriptFile = new Script(fileObj).es6().compress(); return new Promise((resolve, reject) => { resolve([scriptFile]); }); } }; function parseAFile(fileObj, info) { let func = foo[info.type]; if ('function' === typeof func) { return func(fileObj, info); } return new Promise((resolve, reject) => { resolve([fileObj, { hash: false, min: false }]); }); } function main(args) { console.log('start...'); // 参数检查 argCheck(args); // 初始化一个网站 let site = new Site(args['out'], args['domain'], args['default']); let count = 0; let htmls = []; site .map() .then((mapper) => { //mkFont() // 遍历引用关系图 console.log('共发现' + mapper.size + '个文件'); let mapFinish = false; for (let [index, info] of mapper) { // 跳过不存在的文件 if (info.notFound) { continue; } if (info.html) { htmls.push(info); continue; } count++; File .read(info.srcFileName) // 读取完成,开始解析 .then((fileObj) => { return parseAFile(fileObj, info); }) // 解析完成,写入目标文件 .then(([fileObj, opt]) => { if (!fileObj) return new Promise((resolve, reject) => { resolve(); }); return info.writeRes(fileObj, opt); }) // 写入完成 .then(() => { if (0 !== --count || !mapFinish) return; console.log(`html页面共计${htmls.length}个`); for (page of htmls) { // 引用替换 page.link.forEach((item) => { // 查找对应的资源文件 let resFileObj = mapper.get(item); if (!resFileObj || resFileObj.notFound) { return; } page.html._out = page.html._out.replace(item, resFileObj.outFileIndex); }); // 写入 page.html.write(path.format(page.outFileName)).on('writed', () => { // 重置 page.html.reset(); }); } }) // 出错 .catch(console.error); } mapFinish = true; }) .catch(console.error); console.log('mapping...'); return 0; } (function() { main(option([{ opt: 'v', option: 'version', argument: false }, { opt: 'h', option: 'help', argument: false }, { opt: 'w', option: 'watch', argument: false }, { opt: 'o', option: 'out', argument: true }, { opt: 'd', option: 'domain', argument: true }])); })();
module.exports = require('./lib/moninode.js');
'use strict'; const mongoose = require('mongoose'); const Promise = require('bluebird'); mongoose.Promise = Promise; mongoose.connect('mongodb://192.168.132.129/test'); const Schema = mongoose.Schema; const schema = new Schema({ name: { type: String }, val: {type: Number}, user: {type: String} }); let InCode = mongoose.model('InCodeSchema', schema); let task = Promise.coroutine(function* () { yield InCode.remove(); yield InCode.create({ name: 'dd', val: 100, user: 'dd' }); let entry = yield InCode.findOne({name: 'dd'}).exec(); console.log(entry); for (let i = 0; i< 10; i++) { yield InCode.update({}, {$set: {val: 1}}); let entry = yield InCode.findOne().exec(); console.log(`${i} entry:${entry.__v}`); } }) task().then((r) => { console.log(r) })
import "bootstrap/js/dist/button"; import "bootstrap/js/dist/collapse"; import "bootstrap/js/dist/dropdown"; import "bootstrap/js/dist/modal"; import "bootstrap/js/dist/tab"; import "bootstrap/js/dist/tooltip";
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach() { var newnode = $('upload').cloneNode(true); var id = nowid; var tags; newnode.id = 'upload_' + id; tags = newnode.getElementsByTagName('input'); for(i = 0;i < tags.length;i++) { if(tags[i].name == 'attach') { tags[i].id = 'attach_' + id; tags[i].name = 'attach'; tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)}; tags[i].unselectable = 'on'; } } tags = newnode.getElementsByTagName('span'); for(i = 0;i < tags.length;i++) { if(tags[i].id == 'localfile') { tags[i].id = 'localfile_' + id; } } nowid++; $('attachbody').appendChild(newnode); } function insertAttach(id) { var path = $('attach_' + id).value; if(path == '') { return; } var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase(); var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig"); if(extensions != '' && (re.exec(extensions) == null || ext == '')) { alert('¹ï¤£°_¡A¤£¤ä«ù¤W¶Ç¦¹Ãþ¤å¥ó'); return; } var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1); $('localfile_' + id).innerHTML = localfile + ' ¤W¶Ç¤¤...'; $('attach_' + id).style.display = 'none'; $('upload_' + id).action += '&attach_target_id=' + id; $('upload_' + id).submit(); addAttach(); } function deleteAttach(attachid, url) { ajaxget(url); $('attach_list_' + attachid).style.display = 'none'; } function setConver(attach) { $('conver').value = attach; } addAttach();
'use strict'; var wallas = angular.module('wallasApp'); wallas.factory('PercentSpendingService', ['$http', function($http) { var percentSpendingService = {}; percentSpendingService.getPercents = function(login, startDate, endDate) { var startDateUTC = startDate.getUTCFullYear() + '-' + (startDate.getUTCMonth() + 1)+ '-' + startDate.getUTCDate()+'T'+startDate.getUTCHours()+':'+startDate.getUTCMinutes()+'Z'; var endDateUTC = endDate.getUTCFullYear() + '-' + (endDate.getUTCMonth() + 1)+ '-' + endDate.getUTCDate()+'T'+endDate.getUTCHours()+':'+endDate.getUTCMinutes()+'Z'; return $http.get('rest/percents/'.concat(login) + '?startDate=' + startDateUTC + '&endDate=' + endDateUTC); }; return percentSpendingService; }]);
angular.module('bhima.controllers') .controller('StockSettingsController', StockSettingsController); StockSettingsController.$inject = [ 'StockSettingsService', 'EnterpriseService', 'util', 'NotifyService', 'SessionService', 'bhConstants', ]; /** * Stock Settings Controller * This module is a for getting/updating the parameters/settings related to Stock */ function StockSettingsController( StockSettings, Enterprises, util, Notify, Session, bhConstants, ) { const vm = this; vm.enterprise = {}; vm.settings = {}; let $touched = false; // bind methods vm.submit = submit; vm.onSelectCostCenter = onSelectCostCenter; // fired on startup function startup() { // load enterprises Enterprises.read() .then(enterprises => { // Assume the enterprise data has been created already [vm.enterprise] = enterprises; const params = { enterprise_id : vm.enterprise.id }; // Now look up the stock settings // (assume they have already been created ) return StockSettings.read(null, params); }) .then(settings => { if (settings.length > 0) { [vm.settings] = settings; } }) .catch(Notify.handleError); // load algorithms for Average Consumption vm.algorithms = bhConstants.average_consumption_algo; } function onSelectCostCenter(cc) { const ccKey = 'default_cost_center_for_loss'; vm.settings[ccKey] = cc.id; } // form submission function submit(form) { if (form.$invalid) { Notify.danger('FORM.ERRORS.HAS_ERRORS'); return 0; } // make sure only fresh data is sent to the server. if (form.$pristine && !$touched) { Notify.warn('FORM.WARNINGS.NO_CHANGES'); return 0; } const changes = util.filterFormElements(form, true); Object.keys(vm.settings).forEach(key => { delete changes[key]; }); changes.settings = angular.copy(vm.settings); const promise = StockSettings.update(vm.enterprise.id, changes); return promise .then(() => Notify.success('FORM.INFO.UPDATE_SUCCESS')) .then(() => Session.reload()) // Should we just refresh the stock settings in the Session? .catch(Notify.handleError); } /** * @function proxy * * @description * Proxies requests for different stock settings. * * @returns {function} */ function proxy(key) { return (enabled) => { vm.settings[key] = enabled; $touched = true; }; } vm.enableAutoStockAccounting = proxy('enable_auto_stock_accounting'); vm.enableAutoPurchaseOrderConfirmation = proxy('enable_auto_purchase_order_confirmation'); vm.enableStrictDepotPermission = proxy('enable_strict_depot_permission'); vm.enableSupplierCredit = proxy('enable_supplier_credit'); vm.enableStrictDepotDistribution = proxy('enable_strict_depot_distribution'); vm.enableExpiredStockOut = proxy('enable_expired_stock_out'); vm.setMonthAverage = function setMonthAverage() { $touched = true; }; vm.setDefaultMinMonthsSecurityStock = function setDefaultMinMonthsSecurityStock() { $touched = true; }; vm.setMinDelay = () => { $touched = true; }; vm.setPurchaseInterval = () => { $touched = true; }; startup(); }
/** Copyright 2011 Red Hat, Inc. This software is licensed to you under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License (GPLv2) or (at your option) any later version. There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY, NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 along with this software; if not, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. */ var notices = (function() { return { setup_notices: function(pollingTimeOut) { if (pollingTimeOut === undefined) { pollingTimeOut = 45000; } notices.checkTimeout = pollingTimeOut; //start continual checking for new notifications notices.start(); }, clearPreviousFailures: function(requestType) { $('.' + requestType).closest('.jnotify-notification').remove(); }, displayNotice: function(level, notice, requestType) { var noticesParsed = $.parseJSON(notice), options = { type: level, slideSpeed: 200, alwaysClosable: true }, generate_list = function(notices){ var notices_list = '<ul class='+requestType+'>', i, length = notices.length; for( i=0; i < length; i += 1) { notices_list += '<li>' + notices[i] + '</li>'; } notices_list += '</ul>'; return notices_list; }; if (level === 'success') { notices.clearPreviousFailures(requestType); } if ((level === "error") || (level === "warning")) { options["sticky"] = true; options["fadeSpeed"] = 600; } else if( level === "message" ) { options["sticky"] = true; options["fadeSpeed"] = 600; } else { options["sticky"] = false; options["fadeSpeed"] = 600; } if( noticesParsed['validation_errors'] !== undefined ){ var validation_html = generate_list(noticesParsed['validation_errors']); validation_html = '<span>' + i18n.validation_errors + '</span>' + validation_html; $.jnotify(validation_html, options); $('.jnotify-message ul').css({'list-style': 'disc', 'margin-left': '30px'}); } if( noticesParsed['notices'] && noticesParsed['notices'].length !== 0 ){ $.jnotify(generate_list(noticesParsed['notices']), options); } }, addNotices: function(data) { if (!data || data.new_notices.length === 0) { return true; } //if coming from the server may have new count if (data.unread_count) { $("#unread_notices").text(data.unread_count); } $.each(data.new_notices, function(index, notice) { notices.displayNotice(notice.level, window.JSON.stringify({ "notices": [notice.text] }), notice.request_type); }); return true; }, checkNotices : function() { var url = $('#get_notices_url').attr('data-url'); //Make sure when we load the page we get notifs $.ajax({ type: 'GET', url: url, dataType: 'json', global: false, success: notices.addNotices }); }, checkNoticesInResponse : function(xhr) { var message, messageType; if (xhr !== undefined) { message = xhr.getResponseHeader('X-Message'); if (message) { messageType = xhr.getResponseHeader('X-Message-Type'); messageRequestType = xhr.getResponseHeader('X-Message-Request-Type'); notices.displayNotice(messageType, KT.common.decode(message), messageRequestType); } } }, start: function () { var url = $('#get_notices_url').attr('data-url'); // do not wait for PeriodUpdater, check new notices immediately $.ajax({ type:"GET", url:url, cache:false, success:notices.addNotices }); var pu = $.PeriodicalUpdater(url, { method: 'get', type: 'json', global: false, minTimeout: notices.checkTimeout, maxTimeout: notices.checkTimeout }, notices.addNotices); } }; })(); $(document).ready(function() { // perform periodic polling of notices (e.g. async scenarios) //notices.checkNotices(); $(document).ajaxComplete(function(event, xhr, options){ // look for notices in the response (e.g. sync scenarios) notices.checkNoticesInResponse(xhr); }); });
/* * 响应式 */ // 添加导航菜单 $(window).resize(function(){ var window_width = $(window).width(),$menu = $('#response-menu'); if(window_width <= _options_.response_phone_width) { if($menu.length <= 0) { $('#menu').before('<a id="response-menu"></a>'); $('#search-area').insertBefore('#menu'); $menu = $('#response-menu'); } $menu.show(); $('#menu .sub-menu').show(); $('#menu,#search-area').not('.phone-hidden').hide().addClass('phone-hidden'); } else { $menu.hide(); } }).resize(); $('body').on('click','#response-menu',function(){ $('#menu,#search-area').slideToggle(); }); // 显示边栏 $(window).resize(function(){ if($(window).width() > _options_.response_phone_width) { $('.phone-hide-sidebar').remove(); } }); /* * 页面需要尽快加载的代码 */ // 下拉菜单效果 $(window).resize(function(){ if($(window).width() <= _options_.response_phone_width) { $('#menu .menu-item-has-children').unbind('mouseenter mouseleave'); return; } $('#menu,#search-area').show().removeClass('phone-hidden'); $('#menu .sub-menu').hide(); var $timer = {}; $timer.menu = false; $('#menu .menu-item-has-children').bind('mouseenter',function(){ var $this = $(this),$child = $this.children('.sub-menu'); $('#menu .menu-item-has-children .sub-menu').fadeOut(100); $child.hide(); clearTimeout($timer.menu); $timer.menu = setTimeout(function(){ $child.fadeIn(300); },200); }).bind('mouseleave',function(){ var $this = $(this),$child = $this.children('.sub-menu'); clearTimeout($timer.menu); $timer.menu = setTimeout(function(){ $child.fadeOut(100); },100); }); }).resize(); // 响应式布局切换 $(window).resize(function(){ var window_width = $(window).width(), screen_style = _options_.template_url + '/css/' + _options_.style_color + '-screen.css', pad_style = _options_.template_url + '/css/' + _options_.style_color + '-pad.css', phone_style = _options_.template_url + '/css/' + _options_.style_color + '-phone.css', $style = $('#response-style-link'); if(window_width <= _options_.response_phone_width)$style.attr('href',phone_style); else if(window_width <= _options_.response_pad_width)$style.attr('href',pad_style); else if(window_width <= _options_.response_screen_width)$style.attr('href',screen_style); else $style.removeAttr('href'); }).resize(); // 幻灯片 if($('#slider').length > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/jquery.devrama.slider.js">\x3C/script>'); $('#slider').DrSlider({onLoad:function(){ $('#slider').slideDown(500); }}); } // 图片延时加载 if(_options_.img_lazyload && $('.post img').length > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/jquery.lazyload.min.js">\x3C/script>'); $('.post img').not('.pagenavi-loading-image').lazyload({effect:"fadeIn",threshold:200}); } // 固定边栏 if($('#fixed-sidebar').length > 0 && $(window).width() > _options_.response_phone_width) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/fixed-widget.js">\x3C/script>'); $.fixedwidget({ fixedObj : '#fixed-sidebar', bottomObj : '#footer', fixedPos : 10 }); } // 无限加载 if($('#pagenavi').length > 0 && _options_.pagenavi_num > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/pagenavi-ajax.js">\x3C/script>'); $.pagenavajax({ loading_html : '<img src="' + _options_.template_url + '/images/loading.gif" style="clear:both;display:block;margin:0 auto;text-align:center;" alt="正在加载..." class="pagenavi-loading-image" />', pagenav : '#pagenavi', container : '#post-list', pendObj : 'div.post', startPos : 50, currentNav : 'span.current', real_current_page : _options_.real_current_page, nav_page_num : _options_.pagenavi_num, is_forever_btn : false, call_before_fun : function() { if(_options_.img_lazyload && $('.post img').length > 0)$('.post img').addClass('lazyload'); }, call_back_fun : function(){ if(_options_.img_lazyload && $('.post img').length > 0 && $('.post img').not('.lazyload').length > 0) { $('.post img').not('.lazyload').lazyload({effect:"fadeIn",threshold:200}); } } }); } // 返回顶部按钮 $('body').append('<a href="javascript:void(0);" class="to-top" id="to-top-btn"></a>'); $(document).on('click','#to-top-btn',function(){ $('html,body').animate({scrollTop:0},500); }); $(window).scroll(function(){ var scrollTop = $(window).scrollTop(); if(scrollTop > 200) { $('#to-top-btn').fadeIn(500); } else { $('#to-top-btn:visible').fadeOut(500); } }).scroll(); /* * 等到加载完才执行的代码 */ jQuery(function($){ // 非本站链接跳出 $(document).on('click','a',function(e){ var href = $(this).attr('href'); if(href.indexOf('http://') >= 0 && $href.indexOf(window.location.host) < 0){ window.open(href); return false; } }); // 主要区域的高度 function set_same_height() { if($('#sidebar').is(':hidden')) return; var left = $('#content').outerHeight(true), right = $('#sidebar').outerHeight(true); if(right > left) $('#main').css('min-height',right + 100 + 'px'); } $(window).load(function(){set_same_height();}); });
// RU lang variables KOI8-R tinyMCE.addToLang('',{ insert_advhr_desc : '÷ÓÔÁ×ÉÔØ / ÒÅÄÁËÔÉÒÏ×ÁÔØ ÇÏÒÉÚÏÎÔÁÌØÎÙÊ ÒÁÚÄÅÌÉÔÅÌØ', insert_advhr_width : 'ûÉÒÉÎÁ', insert_advhr_size : '÷ÙÓÏÔÁ', insert_advhr_noshade : 'âÅÚ ÔÅÎÉ' });
/* Bulgarian initialisation for the jQuery UI date picker plugin. */ /* Written by Stoyan Kyosev (http://svest.org). */ jQuery(function ($) { $.datepicker.regional['bg'] = { closeText: 'затвори', prevText: '&#x3c;назад', nextText: 'напред&#x3e;', nextBigText: '&#x3e;&#x3e;', currentText: 'днес', monthNames: ['Януари', 'Февруари', 'Март', 'Април', 'Май', 'Юни', 'Юли', 'Август', 'Септември', 'Октомври', 'Ноември', 'Декември'], monthNamesShort: ['Яну', 'Фев', 'Мар', 'Апр', 'Май', 'Юни', 'Юли', 'Авг', 'Сеп', 'Окт', 'Нов', 'Дек'], dayNames: ['Неделя', 'Понеделник', 'Вторник', 'Сряда', 'Четвъртък', 'Петък', 'Събота'], dayNamesShort: ['Нед', 'Пон', 'Вто', 'Сря', 'Чет', 'Пет', 'Съб'], dayNamesMin: ['Не', 'По', 'Вт', 'Ср', 'Че', 'Пе', 'Съ'], weekHeader: 'Wk', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['bg']); });
module("Array.prototype.reduce") test("reducing an array", function () { var a = [1,2,3], total total = a.reduce(function (a, b) { return a + b }) equal(6, total, "should sum the array") }) test("passing an initial value into the reduce", function () { var a = [1,2,3], total total = a.reduce(function (a, b) { return a + b }, 10) equal(16, total, "should sum the array") }) test("arguments that are passed to the function", function () { var a = [1, 2], previousValue, currentValue, index, array a.reduce(function (b,c,d,e) { previousValue = b currentValue = c index = d array = e }) equal(1, previousValue, "the previous value should be 0 initially and be the first argument to the function") equal(2, currentValue, "the current value should be 1 and be the second argument to the function") equal(1, index, "the index should be the third argument passed to the function") deepEqual(array, a, "the array being reduced should be passed as the fourth argument") }) test("skipping non existent indexes", function () { var a = [,,,,,,,,], count = 0 a.reduce(function () { count++ }, {}) equal(0, count, 'should skip non existent indexes') })
angular.module('project', ['ngRoute', 'firebase']) .value('fbURL', 'https://angularjs-projects.firebaseio.com/') .factory('Projects', function($firebase, fbURL) { return $firebase(new Firebase(fbURL)).$asArray(); }) .config(function($routeProvider) { $routeProvider .when('/', { controller:'ListCtrl', templateUrl:'list.html' }) .when('/edit/:projectId', { controller:'EditCtrl', templateUrl:'detail.html' }) .when('/new', { controller:'CreateCtrl', templateUrl:'detail.html' }) .otherwise({ redirectTo:'/' }); }) .controller('ListCtrl', function($scope, Projects) { $scope.projects = Projects; }) .controller('CreateCtrl', function($scope, $location, Projects) { $scope.save = function() { Projects.$add($scope.project).then(function(data) { $location.path('/'); }); }; }) .controller('EditCtrl', function($scope, $location, $routeParams, Projects) { var projectId = $routeParams.projectId, projectIndex; $scope.projects = Projects; projectIndex = $scope.projects.$indexFor(projectId); $scope.project = $scope.projects[projectIndex]; $scope.destroy = function() { $scope.projects.$remove($scope.project).then(function(data) { $location.path('/'); }); }; $scope.save = function() { $scope.projects.$save($scope.project).then(function(data) { $location.path('/'); }); }; }); /** * Created by kurtulus on 08/12/14. */
angular.module('hexafacture') .controller('RootCtrl', function (TheDebug, TheExport, TheIcons ) { var vmRoot = this; vmRoot.TheIcons = TheIcons; vmRoot.isDev = TheDebug.isDev; });
/* * jUIcy Button Select * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js */ (function( $ ) { $.widget( "juicy.buttonselect", { options: { name: '', items: {}, wrapTemplate: '', click: null }, _create: function() { this.element.addClass( 'juicy-buttonselect' ); this._appendInputs(); }, _setOption: function( key, value ) { $.Widget.prototype._setOption.apply( this, arguments ); switch( key ) { case 'name': case 'items': case 'wrapTemplate': this.refresh(); break; } }, destroy: function() { this.element .removeClass( 'juicy-buttonselect juicy-buttonselect-single' ) .empty(); $.Widget.prototype.destroy.call( this ); }, /** * settings = { * type: radio|checkbox * id: id attribute * name: name attribute * value: value attribute * labelText: label text * wrap: element to wrap around input * checked: boolean * } */ _newInput: function( target, settings ) { var realTarget, input = $('<input />') .attr( 'type', settings.type ) .attr( 'id', settings.id ) .attr( 'name', settings.name ) .attr( 'value', settings.value ), label = $('<label></label>') .attr( 'for', settings.id ) .html( settings.labelText ); if ( settings.checked ) { input.attr( 'checked', 'checked' ); } if ( settings.wrap.length ) { realTarget = $( settings.wrap ).appendTo( target ); } else { realTarget = target; } realTarget.append( input, label ); return input; }, _appendInputs: function() { var self = this, o = this.options, checked = true; this.element.addClass( 'juicy-buttonselect-single' ); $.each( o.items, function( key, val ){ self._newInput( self.element, { type: 'radio', id: o.name + '-' + key, name: o.name, value: key, labelText: val, wrap: o.wrapTemplate, checked: checked } ) .button() .click( function(){ self._updButtons(); o.click(); }); checked = false; }); self._updButtons(); }, _getButtonIcon: function( input ) { if ( input.is(':checked') ) { return 'ui-icon-bullet'; } else { return 'ui-icon-radio-off'; } }, _updButtons: function() { var self = this; $( 'input', this.element ) .each( function() { var input = $(this), icon = self._getButtonIcon( input ); input .button( 'refresh' ) .button( 'option', 'icons', {primary: icon} ); }); }, refresh: function() { this.element.empty(); this._appendInputs(); }, selectedValue: function( newValue ) { if ( arguments.length ) { $( 'input', this.element ) .each( function(){ $(this).removeAttr( 'checked' ); if ( $(this).val() == newValue ) { $(this).attr( 'checked', 'checked' ); } }); this._updButtons(); return null; } else { return $( 'input:checked', this.element ).val(); } } }); $.widget( "juicy.buttonselectmulti", $.juicy.buttonselect, { destroy: function() { this.element.removeClass( 'juicy-buttonselectmulti' ); $.juicy.buttonselect.destroy.call( this ); }, _appendInputs: function() { var self = this, o = this.options; this.element.addClass( 'juicy-buttonselectmulti' ); $.each( o.items, function( key, val ){ self._newInput( self.element, { type: 'checkbox', id: o.name + '-' + key, name: o.name, value: key, labelText: val, wrap: o.wrapTemplate, checked: true } ) .button() .click( function() { self._updButtons(); o.click(); }); }); self._updButtons(); }, _getButtonIcon: function( input ) { if ( input.is(':checked') ) { return 'ui-icon-circle-check'; } else { return 'ui-icon-circle-plus'; } }, selectedValue: function( newValue ) { if ( arguments.length ) { $( 'input', this.element ) .each( function(){ $(this).removeAttr( 'checked' ); if ( $.inArray( $(this).val(), newValue ) != -1 ) { $(this).attr( 'checked', 'checked' ); } }); this._updButtons(); return null; } else { var value = []; $( 'input:checked', this.element ) .each( function(){ value.push( $(this).val() ); }); return value; } } }); }( jQuery ) );
jQuery(function( $ ){ // add js body class $('body').addClass('js'); // find time for each entry and move it inside the image link $('.home-middle article, .home-top article').each(function(){ var $time = $(this).find('.entry-time'); $(this).find('a.alignleft, a.alignnone, a.alignright').append($time); }); });
var events = require('events'), Event = new events.EventEmitter(), moment = require('moment-timezone'); var App = { "bot": global.Configuration.bot, "Event": Event, "Package": (function() { var package = require('../package.json'); return { "version": package.version, "name": package.name, "description": package.description, "author": package.author }; }()) }; var plugins = {}; global.Configuration.plugins.map(function(plugin) { plugins[plugin.name] = require('./plugins/' + plugin.name)( plugin.configuration, App, function() { var args = Array.prototype.slice.call(arguments); // Add plugin name as sender args.unshift('<' + plugin.name + '>'); // Add timestamp args.unshift('[' + moment().format('YYYY-MM-DD hh:mma (ss.SSS)') + ']'); console.log.apply(null, args); } ); return true; }); module.exports.App = App; module.exports.plugins = (function() { return { call: function(plugin, action, data, method) { if (plugins.hasOwnProperty(plugin)) { plugins[plugin](action, data, method); } } }; }());
// notify for the new incoming messages // modified from pcmanx-gtk2 function AlertsService(buf) { this.buf = buf; this.lastChanged = 0; } AlertsService.prototype={ alert: function() { var prefs = this.buf.view.conn.listener.prefs; if(!prefs.Popup && !prefs.Beep) return; //FIXME: Distinguish the system alert and the message in a better way if(Date.now() - this.lastChanged > 500) var msgTimeout = true; if(this.timer) { //FIXME: some valid messages may miss this.timer.cancel(); delete this.timer; } var _this = this; this.timer = setTimer(false, function() { var msg = msgTimeout ? "" : _this.getMsg(); if(prefs.Beep) _this.beep(msg); if(prefs.Popup && msg) _this.showPopups(msg); delete _this.timer; }, 500); }, getMsg: function() { var text = this.buf.getRowText(this.buf.rows-1, 0, this.buf.cols); return text.replace(/ +$/,""); }, beep: function(msg) { /* var sound = Components.classes["@mozilla.org/sound;1"] .createInstance(Components.interfaces.nsISound); */ if(msg) { // sound.playEventSound(sound.EVENT_NEW_MAIL_RECEIVED); speak("You got a message."); } else { // sound.beep(); speak("Warning"); } //FIXME: support custum sound: //https://developer.mozilla.org/en/nsISound#play() }, showPopups: function(msg) { //FIXME: PopupNotifications.jsm is an alternative but works only in FX4+ // nsIPromptService is more flexible but more coding is needed var column = msg.replace(/^ +/,"").split(" "); var summary = document.title + " - " + column.shift(); var body = column.join(" "); /* Components.classes['@mozilla.org/alerts-service;1'] .getService(Components.interfaces.nsIAlertsService) .showAlertNotification(null, summary, body, false, '', null); */ //FIXME: Should we set the active tab as this page? //https://developer.mozilla.org/En/NsIAlertsService //window.webkitNotifications.createHTMLNotification('http://ab.cd'); var notification = window.webkitNotifications.createNotification( 'icon48.png', summary, body ); //notification.ondisplay = function() {}; //notification.onclose =function() {}; notification.show(); this.lastChanged = 0; // Prevent unnecessary popups }, lineUpdated: function() { this.lastChanged = Date.now(); } }
http://jsfiddle.net/fusioncharts/jraum9Lw/ http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Chart/Data-values/Pie-chart-showing-data-values-in-tooltips_102/
/** * @name initFile * @description Initializes the file upload widget. * @return Void * @param context - The context to use for initialization. */ this.initFile = function(context) { // when the file types checkbox is checked, hide the file types field, when it is // unchecked, show the file types field $('.form-element-file-types :checkbox', context).bond('click', function() { if (this.checked) { $('.form-element-file-types span', context).hide(); } else { $('.form-element-file-types span', context).show(); } }); }; /** * @name initRadio * @description Initializes the radio list widget. * @return Void * @param context - The context to use for initialization. */ this.initRadio = function(context, showFirst) { _initOptions(context, showFirst); _initOther(context); }; /** * @name initSelect * @description Initializes the select list widget. * @return Void * @param context - The context to use for initialization. */ this.initSelect = function(context, showFirst) { _initOptions(context, showFirst); }; /** * @name initSelectCountries * @description Initializes the country select list variation of the select widget. * @return Void * @param context - The context to use for initialization. */ this.initSelectCountry = function(context) { this.initSelect(context, false); var fillData = { fieldData : [] }; var countryList = [ 'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombi', 'Comoros', 'Congo (Brazzaville)', 'Congo', 'Costa Rica', "Cote d'Ivoire", 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor (Timor Timur)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia, The', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North', 'Korea, South', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepa', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe' ]; for (var i = 0; i < countryList.length; i++) { fillData.fieldData[i] = { label : countryList[i] }; } _addFields(context, fillData.fieldData); _fillWidget(context, fillData); }; /** * @name initText * @description Initializes the text widget. * @return Void * @param context - The context to use for initialization. */ this.initText = function(context) { }; /** * @name initTextarea * @description Initializes the textarea widget. * @return Void * @param context - The context to use for initialization. */ this.initTextarea = function(context) { };
EasySocial.module( 'oauth/facebook', function($) { var module = this; EasySocial.require() .done(function() { EasySocial.Controller( 'OAuth.Facebook', { defaultOptions : { "{login}" : "[data-oauth-facebook-login]", "{revoke}" : "[data-oauth-facebook-revoke]", "{pushInput}" : "[data-oauth-facebook-push]" } }, function( self ) { return { init : function() { }, openDialog : function( url ) { var left = (screen.width/2)-( 300 /2), top = (screen.height/2)-( 300 /2); window.open( url , "" , 'scrollbars=no,resizable=no,width=300,height=300,left=' + left + ',top=' + top ); }, "{pushInput} change" : function( el ) { var enabled = $(el).val(); if( enabled == 1 && self.options.requestPush ) { self.openDialog( self.options.addPublishURL ) } if( enabled == 0 ) { self.openDialog( self.options.revokePublishURL ); } }, "{login} click" : function() { self.openDialog( self.options.url ); }, "{revoke} click" : function() { var callback = self.element.data( 'callback' ); EasySocial.dialog( { content : EasySocial.ajax( 'site/views/oauth/confirmRevoke' , { "client" : 'facebook' , "callbackUrl" : callback } ) }); } } }); module.resolve(); }); }); // module end
/** * JBZoo App is universal Joomla CCK, application for YooTheme Zoo component * * @package jbzoo * @version 2.x Pro * @author JBZoo App http://jbzoo.com * @copyright Copyright (C) JBZoo.com, All rights reserved. * @license http://jbzoo.com/license-pro.php JBZoo Licence * @coder Alexander Oganov <t_tapak@yahoo.com> */ ; (function ($, window, document, undefined) { $.fn.Directories = function (options) { var args = arguments, method = args[0] ? args[0] : null, $this = $(this), input = $this; this.options = $.extend({ url : "", title : "Folders", mode : "folder", msgDelete: "Delete" }, method); var finder = $('<div class="finder" />') .insertAfter('body') .finder(this.options) .delegate("a", "click", function (e) { finder.find("li").removeClass("selected"); var li = $(this).parent().addClass("selected"); if (options.mode != "file" || li.hasClass("file")) { $this.focus().val(li.data("path")).blur() } }); var widget = finder.dialog($.extend({ autoOpen : false, resizable: false, open : function () { widget.position({ of: handle, my: "center top", at: "center bottom" }) } }, this.options)).dialog("widget"); var handle = $('<span title="' + options.title + '" class="' + options.mode + 's" />') .insertAfter(input) .bind("click", function () { finder.dialog(finder.dialog("isOpen") ? "close" : "open") } ); $('<span title="' + options.msgDelete + '" class="delete-file" />') .insertAfter(handle) .bind("click", function () { input.val("") } ); $("body").bind("click", function (event) { if (finder.dialog("isOpen") && !handle.is(event.target) && !widget.find(event.target).length) { finder.dialog("close") } }) }; })(jQuery, window, document);
var app = require('../../server'); var request = require('supertest'); var should = require('should'); var mongoose = require('mongoose'); var User = mongoose.model('User'); var Ranking = mongoose.model('Ranking'); var user, ranking; describe('Ranking controller unit tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Some', lastName: 'Name', email: 'mail@example.com', username: 'usrn', password: 'pass>=6', }); user.save(function() { ranking = new Ranking({ name: 'My Ranking', description: 'Test ranking', formula: 'x + y', published: true, user: user, }); ranking.save(function(err) { done(); }); }); }); describe('Testing the GET methods', function() { it('Should be able to get the list of rankings', function(done) { request(app).get('/api/rankings/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { res.body.should.be.an.Array.and.have.lengthOf(1); res.body[0].should.have.property('name', ranking.name); res.body[0].should.have.property('description', ranking.description); res.body[0].should.have.property('formula', ranking.formula); res.body[0].should.have.property('published', ranking.published); done(); }) ; }); }); afterEach(function(done) { Ranking.remove().exec(); User.remove().exec(); done(); }); });
App.IndexController = Ember.Controller.extend({ actions:{ } }); App.IndexRoute = Ember.Route.extend({ model: function() { if(this.get('loaded') == true){ console.log('cached'); return Ember.RSVP.hash({ "news":this.store.all('news'), "assignments":this.store.all('assignment') }) } else console.log('not cached'); this.set('loaded',true); return Ember.RSVP.hash({ "news":this.store.find('news'), "assignments":this.store.find('assignment') }) //return }, actions: { loading: function(transition, originRoute) { // displayLoadingSpinner(); // Return true to bubble this event to `FooRoute` // or `ApplicationRoute`. $("body").spin(true); this.router.one('didTransition', function() { $("body").spin(false); }); return true; } }, setupController: function(controller,model){ this._super(controller, model); controller.set('loaded',new Date()); } });
jQuery(document).ready(function($) { "use strict"; $('#woocommerce_pip_reset_start').live('click', function(){ $('#woocommerce_pip_invoice_start').attr('readonly', 'readonly'); if ($(this).is(':checked')) { $('#woocommerce_pip_invoice_start').removeAttr('readonly'); } }); $('#pip_settings').validate({ rules: { woocommerce_pip_invoice_start: { min: 1, digits: true } } }); // Handling uploading of the logo on PIP settings form. // Adapted from Mike Jolley // http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ var file_frame; $('#upload_image_button').live('click', function( event ){ event.preventDefault(); // If the media frame already exists, reopen it. if ( file_frame ) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: jQuery( this ).data( 'uploader_title' ), button: { text: jQuery( this ).data( 'uploader_button_text' ), }, // Set to true to allow multiple files to be selected multiple: false }); // When an image is selected, run a callback. file_frame.on( 'select', function() { // We set multiple to false so only get one image from the uploader var attachment = file_frame.state().get('selection').first().toJSON(); // Send the value of attachment.url back to PIP settings form jQuery('#woocommerce_pip_logo').val(attachment.url); }); // Finally, open the modal file_frame.open(); }); });
/* * JCE Editor 2.2.0 * @package JCE * @url http://www.joomlacontenteditor.net * @copyright Copyright (C) 2006 - 2012 Ryan Demmer. All rights reserved * @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html * @date 20 June 2012 * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * 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. * * NOTE : Javascript files have been compressed for speed and can be uncompressed using http://jsbeautifier.org/ */ (function(){var WFExtensions={types:{},add:function(n,o){this[n]=o;return this[n];},addType:function(n){this.types[n]={};},addExtension:function(type,n,o){if(typeof this.types[type]=='undefined'){this.addType(type);} this.types[type][n]=o;},getType:function(type){return this.types[type]||false;},getExtension:function(type,ext){var s=this.getType(type);return s[ext];}};window.WFExtensions=WFExtensions;})();
jQuery(document).ready(function(){ // open new window for 'popup' class element or external links $('a').each(function(i, elem) { if ($(elem).hasClass('popup') || elem.href.indexOf('//') >= 0 && elem.href.indexOf('//'+location.host) < 0) { $(elem).on('click keypress', function(event) { window.open($(this).attr('href')); event.preventDefault(); }); } }); // open link on click 'clickable' class element $('.clickable').each(function() { var elem = $(this); var href = elem.children('a').attr('href'); if (href) { elem.on('click', function(e) { location.href = href; e.stopPropagation(); }); } }); });
module.exports = function(Promotion) { };
var express = require('express'), xml2js = require('xml2js'), parser = new xml2js.Parser({explicitArray: false, mergeAttrs: true, explicitRoot: false}); var xmlBodyParser = function(req, res, next) { if (req._body) return next(); req.body = req.body || {}; // ignore GET if ('GET' == req.method || 'HEAD' == req.method) return next(); // check Content-Type if ('text/xml' != req.header('content-type')) return next(); // flag as parsed req._body = true; // parse var buf = ''; req.setEncoding('utf8'); req.on('data', function(chunk){ buf += chunk }); req.on('end', function() { parser.parseString(buf, function(err, json) { if (err) { err.status = 400; next(err); } else { req.body = json; next(); } }); }); }; exports.init = function(publicPath, builder) { app = express(); app.use(xmlBodyParser); app.post('/hex', function(req, res) { logger.info('Client requests hex ' + req.headers['user-agent']); builder.handleBuildJob(req, function(status, hexfile) { if (status) { var body = '<xml><firmware>' + hexfile + '</firmware></xml>'; res.setHeader('Content-Type', 'text/xml'); res.setHeader('Content-Length', body.length); res.end(body); } else { var body = '<xml><error>' + hexfile + '</error></xml>'; res.setHeader('Content-Type', 'text/xml'); res.setHeader('Content-Length', body.length); res.send(500, body); } }); }); app.use(express.static(publicPath)); app.listen(8888); logger.info('Server started'); };
var description = { "author":"mengcraft.com", "name":"AntiBedFucker", "version":"1.0", } plugin.addListener("blockbreakevent", function(event) { var b = event.block if (b.type == org.bukkit.Material.BED_BLOCK) { var p = event.player var target = p.getTargetBlock(null, 5) if (target == null || target.type != org.bukkit.Material.BED_BLOCK) { event.cancelled = true } } })
/** * NamespaceManager NamespaceDialog * * Part of BlueSpice for MediaWiki * * @author Robert Vogel <vogel@hallowelt.biz> * @author Stephan Muggli <muggli@hallowelt.biz> * @package Bluespice_Extensions * @subpackage NamespaceManager * @copyright Copyright (C) 2013 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later * @filesource */ Ext.define( 'BS.NamespaceManager.NamespaceRemoveDialog', { extend: 'BS.Window', currentData: {}, selectedData: {}, afterInitComponent: function() { var msg = mw.message( 'bs-from-something', this.nsName ).text(); this.rgNamespacenuker = Ext.create('Ext.form.RadioGroup', { // Arrange radio buttons into two columns, distributed vertically columns: 1, vertical: true, items: [ { boxLabel: mw.message( 'bs-namespacemanager-willdelete' ).text(), name: 'rb', inputValue: '0' }, { boxLabel: mw.message( 'bs-namespacemanager-willmove' ).text(), name: 'rb', inputValue: '1' }, { boxLabel: mw.message( 'bs-namespacemanager-willmovesuffix', msg ).text(), name: 'rb', inputValue: '2' } ] }); this.items = [{ html: mw.message( 'bs-namespacemanager-deletewarning' ).text() }, { html: mw.message( 'bs-namespacemanager-pagepresent' ).text() }, this.rgNamespacenuker ]; this.callParent(arguments); }, resetData: function() { this.rgNamespacenuker.reset(); this.callParent(); }, setData: function( obj ) { this.currentData = obj; }, getData: function() { this.selectedData.doarticle = this.rgNamespacenuker.getValue(); return this.selectedData; } } );