code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
//Twitter Operations let Twitter = require('twitter') let requireDir = require('require-dir') let Post = require('../models/post.js').Post; let nodeifyit = require('nodeifyit') let config = requireDir('../../config', {recurse: true}) let staticPosts = requireDir('../../data', {recurse: true}) const NODE_ENV = process.env.NODE_ENV require('songbird') module.exports = { timeline: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) let [tweets] = await client.promise.get('statuses/home_timeline') let posts = [] for(let tweet of tweets){ //console.log(tweet) let post = new Post(tweet.id_str, tweet.user.profile_image_url_https, tweet.text, tweet.user.name, tweet.user.screen_name, tweet.favorited, 'twitter', 'Twitter', tweet.created_at) posts.push(post) } req.posts = posts next() }().catch(next) }, compose: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) //console.log(req.body.reply) let params = {status: req.body.reply} let [tweet] = await client.promise.post('statuses/update', params) //console.log(tweet) next() }().catch(next) }, like: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) let params = {id:req.params.statusId} console.log(params) try{ let [tweet] = await client.promise.post('favorites/create', params) }catch(e){ console.log(e) } next() }().catch(next) }, unlike: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) let params = {id:req.params.statusId} //console.log(params) let [tweet] = await client.promise.post('favorites/destroy', params) next() }().catch(next) }, findTweet: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) let params = {id:req.params.statusId} //console.log(params) try{ let [tweet] = await client.promise.get('/statuses/show', params) let post = new Post(tweet.id_str, tweet.user.profile_image_url_https, tweet.text, tweet.user.name, tweet.user.screen_name, tweet.favorited, 'twitter', 'Twitter', tweet.created_at) req.post = post //console.log(tweet) }catch(e){ console.log(e) } next() }().catch(next) }, replyTweet: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) //console.log(req.body.reply) let params = {in_reply_to_status_id: req.params.statusId, status:req.body.reply} let [tweet] = await client.promise.post('statuses/update', params) //console.log(tweet) next() }().catch(next) }, shareTweet: (req, res, next) => { async () =>{ let client = new Twitter({ consumer_key: config.auth[NODE_ENV].twitter.consumerKey, consumer_secret: config.auth[NODE_ENV].twitter.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.tokenSecret }) //console.log(req.body.reply) let params = {id: req.params.statusId} try{ let [tweet] = await client.promise.post('statuses/retweet', params) }catch(e){ console.log(e) } //console.log(tweet) next() }().catch(next) } }
lkolla/social-feed
app/middlewares/twitter-operations.js
JavaScript
mit
4,636
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'ArrestDBcmd', 'fi', { save: 'Tallenna' } );
gbrault/ArrestDB
ckeditor/plugins/ArrestDBcmd/lang/fi.js
JavaScript
mit
215
var Lab = require('lab') var Code = require('code') var sinon = require('sinon') var lab = exports.lab = Lab.script() var expect = Code.expect var logging = require('../../../lib/logging') lab.experiment('logging', function () { lab.test('returns object of log level functions', function (done) { var logger = logging(0) expect(logger).to.be.an.object() expect(logger).to.include('WARN', 'INFO', 'DEBUG') done() }) lab.test('verbosity levels', function (done) { var tests = [ { level: -1, WARN: false, INFO: false, DEBUG: false }, { level: 0, WARN: true, INFO: false, DEBUG: false }, { level: 1, WARN: true, INFO: true, DEBUG: false }, { level: 2, WARN: true, INFO: true, DEBUG: true } ] var levels = ['WARN', 'INFO', 'DEBUG'] tests.forEach(function (t) { var logger = logging(t.level) levels.forEach(function (level) { sinon.stub(console, 'log') logger[level]('testing') expect(console.log.calledOnce).to.equal(t[level]) console.log.restore() }) }) done() }) })
maxbeatty/aws-lambda-deploy
test/unit/lib/logging.js
JavaScript
mit
1,095
var _ = require('lodash'); process.stdin.resume(); process.stdin.setEncoding('utf8'); var data = ""; process.stdin.on('data', function(chunk) { data += chunk; }); process.stdin.on('end', function() { var app = JSON.parse(data); var result = { name: app.name, version: app.version }; if (app.dependencies) { result.dependencies = clean_deps(app.dependencies); } var info = process.env.VCAP_APPLICATION; if (info) { info = JSON.parse(info); result.appId = info.application_id; result.uris = info.uris; } result.platform = "NodeJS"; console.log(JSON.stringify(result)); }); function clean_deps(deps) { return _.map(deps, function(dep, name) { var result = { name: name, version: dep.version, from: dep.from }; if (dep.dependencies) { result.dependencies = clean_deps(dep.dependencies); } return result; }); }
mmgm/nodejs-buildpack
lib/extract_modules.js
JavaScript
mit
1,056
// @flow import { ensureCacheRepo, getCacheRepoDir, verifyCLIVersion, } from '../cacheRepoUtils'; import {getSignedCodeVersion, verifySignedCode} from '../codeSign'; import {getFilesInDir} from '../fileUtils'; import type {FlowVersion} from '../flowVersion'; import { disjointVersionsAll as disjointFlowVersionsAll, parseDirString as parseFlowDirString, toSemverString as flowVersionToSemver, } from '../flowVersion'; import {findLatestFileCommitHash} from '../git'; import {fs, path} from '../node'; import { getRangeLowerBound, getRangeUpperBound, versionToString, } from '../semver'; import semver from 'semver'; import got from 'got'; import type {ValidationErrors as VErrors} from '../validationErrors'; import {validationError} from '../validationErrors'; const P = Promise; export type NpmLibDef = {| scope: null | string, name: string, version: string, flowVersion: FlowVersion, path: string, testFilePaths: Array<string>, |}; export type NpmLibDefFilter = {| type: 'exact', pkgName: string, pkgVersion: string, flowVersion?: FlowVersion, |}; const TEST_FILE_NAME_RE = /^test_.*\.js$/; async function extractLibDefsFromNpmPkgDir( pkgDirPath: string, scope: null | string, pkgNameVer: string, validationErrors?: VErrors, validating?: boolean, ): Promise<Array<NpmLibDef>> { const errContext = `npm/${scope === null ? '' : scope + '/'}${pkgNameVer}`; const parsedPkgNameVer = parsePkgNameVer( pkgNameVer, errContext, validationErrors, ); if (parsedPkgNameVer === null) { return []; } const {pkgName, pkgVersion} = parsedPkgNameVer; const npmDefsDirPath = scope === null ? path.resolve(pkgDirPath, '..') : path.resolve(pkgDirPath, '..', '..'); const pkgVersionStr = versionToString(pkgVersion); const libDefFileName = `${pkgName}_${pkgVersionStr}.js`; const pkgDirItems = await fs.readdir(pkgDirPath); if (validating) { const fullPkgName = `${scope === null ? '' : scope + '/'}${pkgName}`; await _npmExists(fullPkgName).then().catch(error => { // Only fail spen on 404, not on timeout if (error.statusCode === 404) { const pkgError = `Package does not exist on npm!`; validationError(fullPkgName, pkgError, validationErrors); } }); } const commonTestFiles = []; const parsedFlowDirs: Array<[string, FlowVersion]> = []; pkgDirItems.forEach(pkgDirItem => { const pkgDirItemPath = path.join(pkgDirPath, pkgDirItem); const pkgDirItemContext = path.relative(npmDefsDirPath, pkgDirItemPath); const pkgDirItemStat = fs.statSync(pkgDirItemPath); if (pkgDirItemStat.isFile()) { if (path.extname(pkgDirItem) === '.swp') { return; } const isValidTestFile = TEST_FILE_NAME_RE.test(pkgDirItem); if (isValidTestFile) { commonTestFiles.push(pkgDirItemPath); return; } const error = `Unexpected file name. This directory can only contain test files ` + `or a libdef file named ${'`' + libDefFileName + '`'}.`; validationError(pkgDirItemContext, error, validationErrors); } else if (pkgDirItemStat.isDirectory()) { const errCount = validationErrors == null ? 0 : validationErrors.size; const parsedFlowDir = parseFlowDirString( pkgDirItem, `${pkgNameVer}/${pkgDirItem}`, validationErrors, ); // If parsing a flow directory incurred a validation error, don't keep it // around in our list of parsed flow directories // TODO: Make the parseFlowDirString API return `null` when there's an // error if (validationErrors != null && errCount !== validationErrors.size) { return; } parsedFlowDirs.push([pkgDirItemPath, parsedFlowDir]); } else { const error = 'Unexpected directory item'; validationError(pkgDirItemContext, error, validationErrors); } }); if (!disjointFlowVersionsAll(parsedFlowDirs.map(([_, ver]) => ver))) { validationError( errContext, 'Flow versions not disjoint!', validationErrors, ); } if (parsedFlowDirs.length === 0) { validationError(errContext, 'No libdef files found!', validationErrors); } const libDefs = []; await P.all( parsedFlowDirs.map(async ([flowDirPath, flowVersion]) => { const testFilePaths = [].concat(commonTestFiles); let libDefFilePath: null | string = null; (await fs.readdir(flowDirPath)).forEach(flowDirItem => { const flowDirItemPath = path.join(flowDirPath, flowDirItem); const flowDirItemContext = path.relative( npmDefsDirPath, flowDirItemPath, ); const flowDirItemStat = fs.statSync(flowDirItemPath); if (flowDirItemStat.isFile()) { if (path.extname(flowDirItem) === '.swp') { return; } // Is this the libdef file? if (flowDirItem === libDefFileName) { libDefFilePath = path.join(flowDirPath, flowDirItem); return; } // Is this a test file? const isValidTestFile = TEST_FILE_NAME_RE.test(flowDirItem); if (isValidTestFile) { testFilePaths.push(flowDirItemPath); return; } const error = `Unexpected file. This directory can only contain test files ` + `or a libdef file named ${'`' + libDefFileName + '`'}.`; validationError(flowDirItemContext, error, validationErrors); } else { const error = `Unexpected sub-directory. This directory can only contain test ` + `files or a libdef file named ${'`' + libDefFileName + '`'}.`; validationError(flowDirItemContext, error, validationErrors); } }); if (libDefFilePath === null) { libDefFilePath = path.join(flowDirPath, libDefFileName); const error = `No libdef file found. Looking for a file named ${libDefFileName}`; validationError(flowDirPath, error, validationErrors); return; } libDefs.push({ scope, name: pkgName, version: pkgVersionStr, flowVersion, path: libDefFilePath, testFilePaths, }); }), ); return libDefs; } async function getCacheNpmLibDefs() { await ensureCacheRepo(); await verifyCLIVersion(); return getNpmLibDefs(path.join(getCacheRepoDir(), 'definitions')); } const PKG_NAMEVER_RE = /^(.*)_v\^?([0-9]+)\.([0-9]+|x)\.([0-9]+|x)(-.*)?$/; function parsePkgNameVer( pkgNameVer: string, errContext: string, validationErrors?: VErrors, ) { const pkgNameVerMatches = pkgNameVer.match(PKG_NAMEVER_RE); if (pkgNameVerMatches == null) { const error = `Malformed npm package name! ` + `Expected the name to be formatted as <PKGNAME>_v<MAJOR>.<MINOR>.<PATCH>`; validationError(pkgNameVer, error, validationErrors); return null; } let [_, pkgName, major, minor, patch, prerel] = pkgNameVerMatches; major = validateVersionNumPart(major, 'major', errContext, validationErrors); minor = validateVersionPart(minor, 'minor', errContext, validationErrors); patch = validateVersionPart(patch, 'patch', errContext, validationErrors); if (prerel != null) { prerel = prerel.substr(1); } return {pkgName, pkgVersion: {major, minor, patch, prerel}}; } /** * Given a number-or-wildcard part of a version string (i.e. a `minor` or * `patch` part), parse the string into either a number or 'x'. */ function validateVersionPart( part: string, partName: string, context: string, validationErrs?: VErrors, ): number | 'x' { if (part === 'x') { return part; } return validateVersionNumPart(part, partName, context, validationErrs); } /** * Given a number-only part of a version string (i.e. the `major` part), parse * the string into a number. */ function validateVersionNumPart( part: string, partName: string, context: string, validationErrs?: VErrors, ): number { const num = parseInt(part, 10); if (String(num) !== part) { const error = `Invalid ${partName} number: '${part}'. Expected a number.`; validationError(context, error, validationErrs); return -1; } return num; } function pkgVersionMatch(pkgSemver: string, libDefSemverRaw: string) { // The package version should be treated as a semver implicitly prefixed by a // `^`. (i.e.: "foo_v2.2.x" is the same range as "^2.2.x") // UNLESS it is prefixed by the equals character (i.e. "foo_=v2.2.x") let libDefSemver = libDefSemverRaw[0] !== '=' && libDefSemverRaw[0] !== '^' ? '^' + libDefSemverRaw : libDefSemverRaw; if (semver.valid(pkgSemver)) { // Test the single package version against the LibDef range return semver.satisfies(pkgSemver, libDefSemver); } if (semver.valid(libDefSemver)) { // Test the single LibDef version against the package range return semver.satisfies(libDefSemver, pkgSemver); } if (!(semver.validRange(pkgSemver) && semver.validRange(libDefSemver))) { return false; } const pkgRange = new semver.Range(pkgSemver); const libDefRange = new semver.Range(libDefSemver); if (libDefRange.set[0].length !== 2) { throw new Error( 'Invalid npm libdef version! It appears to be a non-continugous range.', ); } const libDefLower = getRangeLowerBound(libDefRange); const libDefUpper = getRangeUpperBound(libDefRange); const pkgBelowLower = semver.gtr(libDefLower, pkgSemver); const pkgAboveUpper = semver.ltr(libDefUpper, pkgSemver); if (pkgBelowLower || pkgAboveUpper) { return false; } const pkgLower = pkgRange.set[0][0].semver.version; return libDefRange.test(pkgLower); } function filterLibDefs( defs: Array<NpmLibDef>, filter: NpmLibDefFilter, ): Array<NpmLibDef> { return defs .filter(def => { let filterMatch = false; switch (filter.type) { case 'exact': filterMatch = filter.pkgName.toLowerCase() === def.name.toLowerCase() && pkgVersionMatch(filter.pkgVersion, def.version); break; default: (filter: empty); } if (!filterMatch) { return false; } const filterFlowVersion = filter.flowVersion; if (filterFlowVersion !== undefined) { const {flowVersion} = def; switch (flowVersion.kind) { case 'all': return true; case 'ranged': case 'specific': return semver.satisfies( flowVersionToSemver(filterFlowVersion), flowVersionToSemver(def.flowVersion), ); default: (flowVersion: empty); } } return true; }) .sort((a, b) => { const aZeroed = a.version.replace(/x/g, '0'); const bZeroed = b.version.replace(/x/g, '0'); return semver.gt(aZeroed, bZeroed) ? -1 : 1; }); } async function _npmExists(pkgName: string): Promise<Function> { const pkgUrl = `https://www.npmjs.com/package/${pkgName}`; return got(pkgUrl, {method: 'HEAD'}); } export async function findNpmLibDef( pkgName: string, pkgVersion: string, flowVersion: FlowVersion, ): Promise<null | NpmLibDef> { const libDefs = await getCacheNpmLibDefs(); const filteredLibDefs = filterLibDefs(libDefs, { type: 'exact', pkgName, pkgVersion, flowVersion, }); return filteredLibDefs.length === 0 ? null : filteredLibDefs[0]; } type InstalledNpmLibDef = | {|kind: 'LibDef', libDef: NpmLibDef|} | {|kind: 'Stub', name: string|}; export async function getInstalledNpmLibDefs( flowProjectRootDir: string, libdefDir?: string, ): Promise<Map<string, InstalledNpmLibDef>> { const typedefDir = libdefDir || 'flow-typed'; const libDefDirPath = path.join(flowProjectRootDir, typedefDir, 'npm'); const installedLibDefs = new Map(); if (await fs.exists(libDefDirPath)) { const filesInNpmDir = await getFilesInDir(libDefDirPath, true); await P.all( [...filesInNpmDir].map(async fileName => { const fullFilePath = path.join(libDefDirPath, fileName); const terseFilePath = path.relative(flowProjectRootDir, fullFilePath); const fileStat = await fs.stat(fullFilePath); if (fileStat.isFile()) { const fileContent = (await fs.readFile(fullFilePath)).toString(); if (verifySignedCode(fileContent)) { const signedCodeVer = getSignedCodeVersion(fileContent); if (signedCodeVer === null) { return; } const matches = signedCodeVer.match( /([^\/]+)\/(@[^\/]+\/)?([^\/]+)\/([^\/]+)/, ); if (matches == null) { return; } if (matches[1] === '<<STUB>>') { installedLibDefs.set(terseFilePath, { kind: 'Stub', name: matches[2], }); return; } const scope = matches[2] == null ? null : matches[2].substr(0, matches[2].length - 1); const nameVer = matches[3]; if (nameVer === null) { return; } const pkgNameVer = parsePkgNameVer(nameVer, '', new Map()); if (pkgNameVer === null) { return; } const {pkgName, pkgVersion} = pkgNameVer; const flowVerMatches = matches[4].match( /^flow_(>=|<=)?(v[^ ]+) ?(<=(v.+))?$/, ); const flowVerStr = flowVerMatches == null ? matches[3] : flowVerMatches[3] == null ? flowVerMatches[2] : `${flowVerMatches[2]}-${flowVerMatches[4]}`; const flowDirStr = `flow_${flowVerStr}`; const context = `${nameVer}/${flowDirStr}`; const flowVer = flowVerMatches == null ? parseFlowDirString(flowDirStr, context) : parseFlowDirString(flowDirStr, context); installedLibDefs.set(terseFilePath, { kind: 'LibDef', libDef: { scope, name: pkgName, version: versionToString(pkgVersion), flowVersion: flowVer, path: terseFilePath, testFilePaths: [], }, }); } } }), ); } return installedLibDefs; } /** * Retrieve a list of *all* npm libdefs. */ export async function getNpmLibDefs( defsDirPath: string, validationErrors?: VErrors, validating?: boolean, ): Promise<Array<NpmLibDef>> { const npmLibDefs: Array<NpmLibDef> = []; const npmDefsDirPath = path.join(defsDirPath, 'npm'); const dirItems = await fs.readdir(npmDefsDirPath); await P.all( dirItems.map(async itemName => { const itemPath = path.join(npmDefsDirPath, itemName); const itemStat = await fs.stat(itemPath); if (itemStat.isDirectory()) { if (itemName[0] === '@') { // This must be a scoped npm package, so go one directory deeper const scope = itemName; const scopeDirItems = await fs.readdir(itemPath); await P.all( scopeDirItems.map(async itemName => { const itemPath = path.join(npmDefsDirPath, scope, itemName); const itemStat = await fs.stat(itemPath); if (itemStat.isDirectory()) { const libDefs = await extractLibDefsFromNpmPkgDir( itemPath, scope, itemName, validationErrors, validating, ); libDefs.forEach(libDef => npmLibDefs.push(libDef)); } else { const error = `Expected only sub-directories in this dir!`; validationError(itemPath, error, validationErrors); } }), ); } else { // itemPath must be a package dir const libDefs = await extractLibDefsFromNpmPkgDir( itemPath, null, // No scope itemName, validationErrors, validating, ); libDefs.forEach(libDef => npmLibDefs.push(libDef)); } } else { const error = `Expected only directories to be present in this directory.`; validationError(itemPath, error, validationErrors); } }), ); return npmLibDefs; } export async function getNpmLibDefVersionHash( repoDirPath: string, libDef: NpmLibDef, ): Promise<string> { const latestCommitHash = await findLatestFileCommitHash( repoDirPath, path.relative(repoDirPath, libDef.path), ); return ( `${latestCommitHash.substr(0, 10)}/` + (libDef.scope === null ? '' : `${libDef.scope}/`) + `${libDef.name}_${libDef.version}/` + `flow_${flowVersionToSemver(libDef.flowVersion)}` ); } export { extractLibDefsFromNpmPkgDir as _extractLibDefsFromNpmPkgDir, parsePkgNameVer as _parsePkgNameVer, validateVersionNumPart as _validateVersionNumPart, validateVersionPart as _validateVersionPart, };
mkscrg/flow-typed
cli/src/lib/npm/npmLibDefs.js
JavaScript
mit
17,256
var require = { baseUrl: '', paths: { node_modules: '/node_modules', antie: '/node_modules/tal/static/script', text: '/node_modules/text/text' } };
ignaciolg/generator-tal
generators/app/templates/src/script/config/require.config.js
JavaScript
mit
183
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { fillOpacity: ".3", d: "M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z" }), h("path", { d: "M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z" })), 'BatteryCharging30Outlined');
AlloyTeam/Nuclear
components/icon/esm/battery-charging30-outlined.js
JavaScript
mit
403
/** * Provides the Firebolt function for making AJAX calls with extended functionality. * * @module ajax/extended * @overrides ajax/basic * @requires core * @requires ajax/shared * @requires string/extras * * @closure_globals setTimeout, clearTimeout */ 'use strict'; //#region VARS var ajaxSettings = { accepts: { '*': '*/*', html: 'text/html', json: 'application/json, text/javascript', script: 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript', text: 'text/plain', xml: 'application/xml, text/xml' }, async: true, headers: {'X-Requested-With': 'XMLHttpRequest'}, isLocal: /^(?:file|.*-extension|widget):/.test(location.href), jsonp: 'callback', jsonpCallback: function() { var callback = oldCallbacks.pop() || Firebolt.expando + '_' + (timestamp++); this[callback] = true; return callback; }, type: 'GET', url: location.href, xhr: XMLHttpRequest }; var rgxDataType = /\b(?:xml|json)\b|script\b/; // Matches a data type in a Content-Type header var oldCallbacks = []; var lastModifiedValues = {}; //#endregion VARS /* * Returns the status text string for AJAX requests. */ function getAjaxErrorStatus(xhr) { return xhr.readyState ? xhr.statusText.replace(xhr.status + ' ', '') : ''; } /** * @summary Perform an asynchronous HTTP (AJAX) request. * * @description * This is the extended version of `$.ajax()`, and is closer to jQuery's version of `$.ajax()`. * * For documentation, see {@link http://api.jquery.com/jQuery.ajax/|jQuery.ajax()}. * However, Firebolt AJAX requests differ from jQuery's in the following ways: * * + Instead of passing a "jqXHR" to callbacks, the native XMLHttpRequest object is passed. * + The `contents` and `converters` settings are not supported. * + The `data` setting may be a string or a plain object or array to serialize and is appended * to the URL as a string for any request that is not a POST request. * + The `processData` setting has been left out because Firebolt will automatically process only * plain objects and arrays (so you wouldn't need to set it to `false` to send another type of * data&emsp;such as a FormData object). * + The `global` setting and the global AJAX functions defined by jQuery are not supported. * * @function Firebolt.ajax * @variation 3 * @param {Object} [settings] - A set of key-value pairs that configure the Ajax request. All settings are optional. * @returns {XMLHttpRequest} The XMLHttpRequest object this request is using * (returns a mock XMLHttpRequest object when the `dataType` is `"script"` or `"jsonp"`). */ Firebolt.ajax = function(url, settings) { //Parameter processing if (typeofString(url)) { settings = settings || {}; settings.url = url; } else { settings = url; } // Merge the passed in settings object with the default values settings = extend(true, {}, ajaxSettings, settings); url = settings.url; var beforeSend = settings.beforeSend; var complete = settings.complete || []; var completes = isArray(complete) ? complete : [complete]; var context = settings.context || settings; var dataType = settings.dataType; var dataTypeJSONP = dataType === 'jsonp'; var error = settings.error || []; var errors = isArray(error) ? error : [error]; var headers = settings.headers; var ifModified = settings.ifModified; var lastModifiedValue = ifModified && lastModifiedValues[url]; var success = settings.success; var successes = isArray(success) ? success : [success]; var timeout = settings.timeout; var type = settings.type.toUpperCase(); var data = settings.data; var textStatus, statusCode, xhr, i; function callCompletes(errorThrown) { if (timeout) { clearTimeout(timeout); } // Execute the status code callback (if there is one that matches the status code) if (settings.statusCode) { var callback = settings.statusCode[statusCode]; if (callback) { if (textStatus == 'success') { callback.call(context, data, textStatus, xhr); } else { callback.call(context, xhr, textStatus, errorThrown || getAjaxErrorStatus(xhr)); } } } // Execute all the complete callbacks for (i = 0; i < completes.length; i++) { completes[i].call(context, xhr, textStatus); } } function callErrors(errorThrown) { // Execute all the error callbacks for (i = 0; i < errors.length; i++) { errors[i].call(context, xhr, textStatus, errorThrown || getAjaxErrorStatus(xhr)); } } function callSuccesses() { // Handle last-minute JSONP if (dataTypeJSONP) { // Call errors and return if the JSONP function was not called if (!responseContainer) { textStatus = 'parsererror'; return callErrors(jsonpCallback + ' was not called'); } // Set the data to the first item in the response data = responseContainer[0]; } if (success) { // Call the user-supplied data filter function if there is one if (settings.dataFilter) { data = settings.dataFilter(data, dataType); } // Execute all the success callbacks for (i = 0; i < successes.length; i++) { successes[i].call(context, data, textStatus, xhr); } } } if (data) { // Process data if necessary if (isArray(data) || isPlainObject(data)) { data = Firebolt.param(data, settings.traditional); } // If the request is not a POST request, append the data string to the URL if (type != 'POST') { url = url.appendParams(data); data = null; // Clear the data so it is not sent later on } } if (dataTypeJSONP) { var jsonpCallback = settings.jsonpCallback; var responseContainer, overwritten; if (!typeof(jsonpCallback)) { jsonpCallback = settings.jsonpCallback(); } // Append the callback name to the URL url = url.appendParams(settings.jsonp + '=' + jsonpCallback); // Install callback overwritten = window[jsonpCallback]; window[jsonpCallback] = function() { responseContainer = arguments; }; // Push JSONP cleanup onto complete callback array completes.push(function() { // Restore preexisting value window[jsonpCallback] = overwritten; if (settings[jsonpCallback]) { // Save the callback name for future use oldCallbacks.push(jsonpCallback); } // Call if `overwritten` was a function and there was a response if (responseContainer && typeof overwritten == 'function') { overwritten(responseContainer[0]); } responseContainer = overwritten = UNDEFINED; }); } if ((dataType === 'script' || dataTypeJSONP) && (settings.crossDomain || url.indexOf('//') >= 0 && url.indexOf('//' + document.domain) < 0 || settings.isLocal)) { // Set up an HTML script loader // Prevent caching unless the user explicitly set cache to true if (settings.cache !== true) { url = url.appendParams('_=' + (timestamp++)); } var script = createElement('script').prop({ charset: settings.scriptCharset || '', src: url, onload: function() { textStatus = 'success'; callSuccesses(); callCompletes(); }, onerror: function(e) { textStatus = textStatus || 'error'; callErrors(e && e.type); callCompletes(e ? e.type : textStatus); } }); // Create a sort-of XHR object xhr = { send: function() { // Append the script to the head of the document to load it document.head.appendChild(script); }, abort: function() { textStatus = textStatus || 'abort'; script.onerror(); } }; // Always remove the script after the request is done completes.push(function fn() { script.remove(); completes.remove(fn); }); } else { // Set up a true XHR xhr = extend(new settings.xhr(), settings.xhrFields); // Create the XHR and give it settings // Override the requested MIME type in the XHR if there is one specified in the settings if (settings.mimeType) { xhr.overrideMimeType(settings.mimeType); } // Prevent caching if necessary if ((type == 'GET' || type == 'HEAD') && settings.cache === false) { url = url.appendParams('_=' + (timestamp++)); } // Open the request xhr.open(type, url, settings.async, settings.username, settings.password); // Set the content type header if there is data to submit or the user has specifed a particular content type if (data || settings.contentType) { headers['Content-Type'] = settings.contentType || 'application/x-www-form-urlencoded; charset=UTF-8'; } // If the data type has been set, set the accept header if (settings.dataType) { headers.Accept = settings.accept[settings.dataType] || settings.accept['*']; } // If there is a lastModifiedValue URL, set the 'If-Modified-Since' header if (lastModifiedValue) { headers['If-Modified-Since'] = lastModifiedValue; } // Set the request headers in the XHR for (i in headers) { xhr.setRequestHeader(i, headers[i]); } // The main XHR function for when the request has loaded (and track states in between for abort or timeout) xhr.onreadystatechange = function() { if (xhr.readyState < 4) { return; } statusCode = xhr.status; if (statusCode >= 200 && statusCode < 300 || statusCode === 304 || settings.isLocal && xhr.responseText) { // Success if (statusCode === 204 || type == 'HEAD') { textStatus = 'nocontent'; } else if (ifModified && url in lastModifiedValues && statusCode === 304) { textStatus = 'notmodified'; } else { textStatus = 'success'; if (ifModified) { lastModifiedValues[url] = xhr.getResponseHeader('Last-Modified'); } } try { // Only need to process data of there is content if (textStatus != 'nocontent') { // If the data type has not been set, try to figure it out if (!dataType) { if (dataType = rgxDataType.exec(xhr.getResponseHeader('Content-Type'))) { dataType = dataType[0]; } } // Set data based on the data type if (dataType == 'xml') { data = xhr.responseXML; } else if (dataType == 'json') { data = JSON.parse(xhr.responseText); } else { data = xhr.responseText; if (dataType == 'script' || dataTypeJSONP) { Firebolt.globalEval(data); } } } else { data = ''; } callSuccesses(); } catch (e) { textStatus = 'parsererror'; callErrors(); } } else { // Error textStatus = textStatus || (xhr.readyState < 3 ? 'abort' : 'error'); callErrors(); } callCompletes(); }; } if (beforeSend && beforeSend.call(context, xhr, settings) === false) { return false; // Do not send the request } // Set a timeout if there is one if (timeout > 0) { timeout = setTimeout(function() { textStatus = 'timeout'; xhr.abort(); }, timeout); } xhr.send(data); // Send the request return xhr; };
woollybogger/Firebolt
src/ajax/extended.js
JavaScript
mit
11,531
$(function(){ $('#select_template').unbind().change(function(){ $('#newsletter_details').html(''); $.post('newsletter/ajax.php',{action: 'select_template', template: $(this).val()},function(data){ $('#select_newsletter').html(data); }); }); $('#select_newsletter').unbind().change(function(){ if($(this).hasClass('stats')) var url = 'newsletter/stat_second.php'; else var url = 'newsletter/details.php'; if($(this).val() != '') $.post(url, {template: $('#select_template').val(), id: $('#select_newsletter').val()}, function(data){ $('#newsletter_details').html(data) .show(); }); else $('#newsletter_details').html(''); }); $('#show_preview').unbind().click(function(event){ event.preventDefault(); if($('#newsletter_preview').html() == "") $.post('newsletter/ajax.php',{action: 'load_preview', template: $('#select_template').val(), id: $('#select_newsletter').val()},function(data){ $('#newsletter_preview').html(data) .slideToggle(); }); else $('#newsletter_preview').slideToggle(); if($(this).find('.openclose').html() == "[openen]") $(this).find('.openclose').html("[sluiten]"); else $(this).find('.openclose').html("[openen]"); }); $('#show_stats').unbind().click(function(event){ event.preventDefault(); if($('#newsletter_stats').html() == "") $.post('newsletter/ajax.php',{action: 'load_stats', template: $('#select_template').val(), id: $('#select_newsletter').val()},function(data){ $('#newsletter_stats').html(data) .slideToggle(); }); else $('#newsletter_stats').slideToggle(); if($(this).find('.openclose').html() == "[openen]") $(this).find('.openclose').html("[sluiten]"); else $(this).find('.openclose').html("[openen]"); }); $('#show_log').unbind().click(function(event){ event.preventDefault(); if($('#newsletter_log').html() == "") $.post('newsletter/ajax.php',{action: 'load_log', template: $('#select_template').val(), id: $('#select_newsletter').val()},function(data){ $('#newsletter_log').html(data) .slideToggle(); }); else $('#newsletter_log').slideToggle(); if($(this).find('.openclose').html() == "[openen]") $(this).find('.openclose').html("[sluiten]"); else $(this).find('.openclose').html("[openen]"); }); $('#send_single').unbind().click(function(event){ event.preventDefault(); processing(); $.post('newsletter/ajax.php',{ action: 'send_single', email: $('#single_email').val(), template: $('#select_template').val(), id: $('#select_newsletter').val()}, function(data){ finished_processing(); cmsalert(data); } ); }); $('#send_mult').unbind().click(function(event){ event.preventDefault(); var group = ''; processing(); if($('#group_all').is(':checked')) group = "all"; else $(".group_check:checked:not('#group_all')").each(function(){ if($(this).val() != "undefined" && typeof $(this).val() != "undefined") group += $(this).val()+","; }); $.post('newsletter/ajax.php',{ action: 'send_mult', group: group, template: $('#select_template').val(), id: $('#select_newsletter').val()}, function(data){ tmp = data.split("|"); $('#resend_form').html(''); if(tmp[0] != ""){ emails = tmp[0].split('#'); for(var i in emails){ var email = emails[i]; if(email == "") continue; $('#resend_form').append('<span class="right"><input type="checkbox" id="check_'+email+'" name="'+email+'" value="'+email+'" /> <label for="check_'+email+'" style="position:relative;bottom:2px;">'+email+'</label></span> '); $('#resend').slideDown(); } } if(tmp[1] != "") cmsalert(tmp[1]); finished_processing(); } ); }); $('#send_re').unbind().click(function(event){ event.preventDefault(); var emails = ''; $("#resend_form input:checkbox:checked").each(function(){ if($(this).val() != "undefined" && typeof $(this).val() != "undefined") emails += $(this).val()+","; }); $.post('newsletter/ajax.php',{ action: 'send_re', emails: emails, template: $('#select_template').val(), id: $('#select_newsletter').val()}, function(data){ cmsalert(data); $('#resend').slideUp(); } ); }); $('.group_check').unbind().change(function(event){ if($(this).is(':checked')){ if($(this).attr('id') == "group_all") $('.group_check').attr('checked','checked'); else if($('.group_check:not(:checked):not(#group_all)').length == 0) $('#group_all').attr('checked','checked'); }else{ $('#group_all').removeAttr('checked'); if($(this).attr('id') == "group_all") $('.group_check').removeAttr('checked'); } }); });
merqwaardig/autototaalhaarlem
cmsdev/newsletter/newsletter.js
JavaScript
mit
5,140
'use strict'; var http = require('http'); var tape = require('tape'); var qs = require('qs'); global.fetch = require('node-fetch'); require('../../'); require('fetch-stringify'); var rawBody = require('raw-body'); var server = http.createServer(function (req, res) { console.log(req.headers); rawBody(req, {length: req.headers['content-length']}, function (err, buf) { console.log(arguments); res.writeHead(200, {'Content-Type': 'text/plain'}); var body = JSON.parse(buf.toString()); if (err) return res.end(err.toString()); console.log(body); res.end(JSON.stringify({url: req.url, body: body})); }); }) var address = server.listen().address(); console.log(address); tape('default querystring stringify function', function (test) { test.plan(1); fetch('http://127.0.0.1:' + address.port + '/post', { querystring: {a: [1, 2]}, method: 'POST', body: { arr: [1,2,3,'中文'] } }).then(function (response) { console.log(response.header); response.json().then(function (json) { test.deepEqual(json, {url:'/post?a%5B0%5D=1&a%5B1%5D=2', body:{"arr":[1,2,3,"中文"]}}); }) }); }); tape('set fetch.querystring function', function (test) { test.plan(1); fetch.querystring = function (qo) { return qs.stringify(qo, {arrayFormat: 'repeat'}); } fetch('http://127.0.0.1:' + address.port + '/post', { querystring: {a: [1, 2]}, method: 'POST', body: { arr: [1,2,3,'中文'] } }).then(function (response) { console.log(response.header); response.json().then(function (json) { test.deepEqual(json, {url:'/post?a=1&a=2', body:{"arr":[1,2,3,"中文"]}}); server.close(); }) }); });
undoZen/fetch-querystring
test/cases/node.js
JavaScript
mit
1,846
// This file is generated import * as getTodosSaga from './getTodosSaga'; import * as postTodoSaga from './postTodoSaga'; const actionTypes = Object.assign( {}, getTodosSaga.actionTypes, postTodoSaga.actionTypes ); const actions = Object.assign( {}, getTodosSaga.actions, postTodoSaga.actions ); const sagas = { getTodosTakeEverySaga: getTodosSaga.takeEverySaga, getTodosTakeLatestSaga: getTodosSaga.takeLatestSaga, postTodosTakeEverySaga: postTodoSaga.takeEverySaga, postTodosTakeLatestSaga: postTodoSaga.takeLatestSaga, }; export { actionTypes, actions, sagas, };
movio/movio-todomvc
src/generated/todo/index.js
JavaScript
mit
597
WizardInstallationAmazonCustomHandler = Class.create(); WizardInstallationAmazonCustomHandler.prototype = { // --------------------------------------- initialize: function() { this.marketplaces = []; this.index = 0; this.marketplacesLastIndex = 0; this.percent = 0; }, // --------------------------------------- marketplacesSynchronizationAction: function(obj) { obj.hide(); var self = this; self.progressBarStartLoad(0); setTimeout(function() { self.synchronizeMarketplaces(); }, 0); }, // --------------------------------------- setNextStep: function(nextStep) { var currentStep = WizardHandlerObj.steps.current; WizardHandlerObj.setStep(nextStep, function() { WizardHandlerObj.renderStep(currentStep); }); return this; }, setMarketplacesData: function(marketplaces) { this.marketplaces = marketplaces; this.marketplacesLastIndex = marketplaces.length - 1; return this; }, getMarketplacesData: function() { return this.marketplaces; }, completeStep: function(step) { WizardHandlerObj.skipStep(step); $('wizard_complete').show(); }, // --------------------------------------- synchronizeMarketplaces: function() { if (this.index > this.marketplacesLastIndex) { $('custom-progressbar').hide(); this.completeStep('marketplacesSynchronization'); return; } var self = this, marketplaces = this.getMarketplacesData(), marketplaceId = marketplaces[self.index] != undefined ? marketplaces[self.index].id : 0, current = $$('.code-'+ marketplaces[self.index].code)[0]; if (marketplaceId <= 0) { this.completeStep('marketplacesSynchronization'); } ++this.index; var startPercent = self.percent; self.percent += Math.round(100 / marketplaces.length); self.marketplaceSynchProcess(current); new Ajax.Request(M2ePro.url.get('marketplacesSynchronization'), { method: 'get', parameters: { id: marketplaceId }, asynchronous: true, onSuccess: (function(transport) { if (transport.responseText == 'success') { self.progressBarStartLoad( startPercent + 1, self.percent, function() { self.marketplaceSynchComplete(current); self.synchronizeMarketplaces(); } ); } return false; }).bind(this) }) }, // --------------------------------------- progressBarStartLoad: function(from, to, callback) { var self = this, progressBar = $('custom-progressbar'), progressBarLoad = $('custom-progressbar-load'), progressBarPercent = $('custom-progressbar-percentage'), step = 2, total = from; if (from == 0 || to == 0) { progressBarLoad.style.width = '0px'; progressBarPercent.innerHTML = '0%'; progressBar.show(); return; } progressBarLoad.style.width = 0 + 'px'; progressBarPercent.innerHTML = 0 + '%'; progressBar.show(); var interval = setInterval(function() { progressBarLoad.style.width = total * 3 + 'px'; progressBarPercent.innerHTML = total + '%'; total += step; if (total >= to) { clearInterval(interval); callback && callback(); } }, 100); }, marketplaceSynchComplete: function(element) { var span = new Element('span', {class: 'synchComplete'}); span.innerHTML = ' (Completed)'; $$('.status-process').each(function(el) { el.hide(); }); element.appendChild(span); element.removeClassName('synchProcess'); element.addClassName('synchComplete'); }, marketplaceSynchProcess: function(element) { var span = new Element('span', { class: 'synchProcess status-process'}); span.innerHTML = ' (In Progress)'; element.appendChild(span); element.addClassName('synchProcess'); } // --------------------------------------- };
portchris/NaturalRemedyCompany
src/js/M2ePro/Wizard/InstallationAmazon/CustomHandler.js
JavaScript
mit
4,740
require.config({ paths: { "jquery": "/plugins/jquery/2.1.3/jquery.min", "semantic": "/plugins/semantic-ui/2.0/semantic.min", "lc4e": "/js/lc4e/jquery-extend", "se-accordion": "/plugins/semantic-ui/2.0/components/accordion.min", "se-api": "/plugins/semantic-ui/2.0/components/api.min", "se-breadcrumb": "/plugins/semantic-ui/2.0/components/breadcrumb.min", "se-checkbox": "/plugins/semantic-ui/2.0/components/checkbox.min", "se-dimmer": "/plugins/semantic-ui/2.0/components/dimmer.min", "se-form": "/plugins/semantic-ui/2.0/components/form.min", "se-dropdown": "/plugins/semantic-ui/2.0/components/dropdown.min", "se-modal": "/plugins/semantic-ui/2.0/components/modal.min", "se-nag": "/plugins/semantic-ui/2.0/components/nag.min", "se-popup": "/plugins/semantic-ui/2.0/components/popup.min", "se-progress": "/plugins/semantic-ui/2.0/components/progress.min", "se-rating": "/plugins/semantic-ui/2.0/components/rating.min", "se-search": "/plugins/semantic-ui/2.0/components/search.min", "se-shape": "/plugins/semantic-ui/2.0/components/shape.min", "se-sidebar": "/plugins/semantic-ui/2.0/components/sidebar.min", "se-site": "/plugins/semantic-ui/2.0/components/site.min", "se-state": "/plugins/semantic-ui/2.0/components/state.min", "se-sticky": "/plugins/semantic-ui/2.0/components/sticky.min", "se-tab": "/plugins/semantic-ui/2.0/components/tab.min", "se-table": "/plugins/semantic-ui/2.0/components/table.min", "se-transition": "/plugins/semantic-ui/2.0/components/transition.min", "se-video": "/plugins/semantic-ui/2.0/components/video.min", "se-visibility": "/plugins/semantic-ui/2.0/components/visibility.min", }, shim: { 'lc4e': ['jquery', 'semantic'], 'semantic': ['jquery'], "se-accordion": ['jquery'], "se-api": ['jquery'], "se-breadcrumb": ['jquery'], "se-checkbox": ['jquery'], "se-dimmer": ['jquery'], "se-form": ['jquery'], "se-dropdown": ['jquery'], "se-modal": ['jquery'], "se-nag": ['jquery'], "se-popup": ['jquery'], "se-progress": ['jquery'], "se-rating": ['jquery'], "se-search": ['jquery'], "se-shape": ['jquery'], "se-sidebar": ['jquery'], "se-site": ['jquery'], "se-state": ['jquery'], "se-sticky": ['jquery'], "se-tab": ['jquery'], "se-table": ['jquery'], "se-transition": ['jquery'], "se-video": ['jquery'], "se-visibility": ['jquery'], } }); require(['jquery', 'lc4e', 'semantic'], function ($) { $.lc4e.index = { ready: function () { var getArticles; $('#menu .ui.dropdown.item').dropdown({ action: "nothing", transition: "scale", on: 'click' }); $('#searchSite').on('focus', function () { $(this).addClass('expended'); }).on('blur', function () { $(this).removeClass('expended') }); $('#expendHeader').on('click', function () { $('#menu').toggleClass('expended'); }); $('#menu .column div:first a').on('click', function () { $('#menu>.column>.allmenus').transition({ animation: "fly down", duration: 500, onComplete: function () { $('#menu>.column>.allmenus').toggleClass('menuhidden').removeClass("transition visible hidden").attr('style', ''); } }); }); $('#config-tool-options .angle.double.left.icon').on('click', function () { if ($($('#config-tool-options .ui.animated.selection.list:not(.hidden)').transition('fade left').attr('data-parent')).transition('fade left').attr('id') == 'menu1') { $(this).addClass('transition hidden'); } }); $("#config-tool-options .ui.list .item[data-target^='#']").on('click', function () { $(this).parent().transition('fade left'); $($(this).attr('data-target')).transition('fade left'); $('#config-tool-options .angle.double.left.icon').removeClass('transition hidden'); }); $('#config-tool-cog').on('click', function () { $('#config-tool').toggleClass('closed'); }); var timer; $('#menuheader').visibility({ offset: -1, continuous: true, onTopPassed: function () { $.requestAnimationFrame(function () { $('#menu').addClass('fixed'); }) }, onTopPassedReverse: function () { clearTimeout(timer); timer = setTimeout(function () { $.requestAnimationFrame(function () { $('#menu').removeClass('fixed'); }) }, 300); } }); $('#GTTop').visibility({ offset: -1, once: false, continuous: false, onTopPassed: function () { $.requestAnimationFrame(function () { $('#GTTop').transition('fade'); }); }, onTopPassedReverse: function () { $.requestAnimationFrame(function () { $('#GTTop').transition('fade'); }); } }); $('#userItem img.ui.image').popup({ position: 'bottom center', transition: "horizontal flip", popup: $('#userCardPop'), exclusive: false, hideOnScroll: false, on: 'click', closable: true }); $('#config-tool-options .ui.checkbox').checkbox(); $('#fixFooter').checkbox({ onChange: function (e) { $('#content').toggleClass('footerFixed'); $('.ui.footer').toggleClass('fixed'); } }); $('#boxedLayout').checkbox({ onChange: function (e) { $('#articlelist').toggleClass('nobox'); } }); $('#announce').shape(); setInterval(function () { $('#announce').shape('flip down'); }, 4000); var page = parseInt($("#articlelist").attr("page")); window.onpopstate = function (e) { console.log(e); } $.Lc4eAjax({ url: "/Articles", cjson: false, type: "get", dataType: "html", }).success(function (data) { $('#articlelist>.ui.divided.items').append(data); $('#articlelist>.ui.divided.items>.item'). transition({ animation: 'fade up', duration: 500, interval: 100, onComplete: function () { $('#articlelist>.ui.divided.items>.item').find('.ui.fluid.image img').popup(); $("#articlelist").attr("page", page); } }) }) $.get('/TopHots').done(function (data) { $('#todayHot>.ui.divided.items,#yesterdayHot>.ui.divided.items').empty().append(data); $('#todayHot>.ui.divided.items>.item,#yesterdayHot>.ui.divided.items>.item'). transition({ animation: 'fade right', duration: 300, interval: 80, }) }); $('#GTTop').on('click', function (e) { e.preventDefault(); $('html').animatescroll({ scrollSpeed: 1000, easing: 'easeOutBounce' }); }); $('#prePage,#nextPage').on('click', function () { var page = parseInt($("#articlelist").attr("page")) + 1; $.Lc4eAjax({ url: "/Articles", cjson: false, type: "get", dataType: "html" }).success(function (data) { $('#articlelist>.ui.divided.items').empty().append(data); $('#articlelist>.ui.divided.items>.item'). transition({ animation: 'fade up', duration: 500, interval: 100, onComplete: function () { $('#articlelist>.ui.divided.items>.item').find('.ui.fluid.image img').popup(); $("#articlelist").attr("page", page); } }) }) }) } }; $(function () { $.lc4e.index.ready(); }) })
Teddy-Zhu/lc4e-spring
src/main/webapp/WEB-INF/resources/javascript/index.js
JavaScript
mit
9,721
import React from "react"; import api from "../app/api"; export default React.createClass({ logout(e) { e.preventDefault(); this.props.app.trigger("user:logout"); }, renderLogout() { if (this.props.app.model.pageName !== "login") { return <a href="" onClick={this.logout}>logout</a> } }, render() { return <div className="footer"> {this.renderLogout()} <a href="https://fortawesome.github.io/Font-Awesome/icons/">fa-icons</a> </div>; } });
fleidloff/todos
froodle/frontend/js/components/footer.js
JavaScript
mit
537
(function () { 'use strict'; angular .module('replies') .run(menuConfig); menuConfig.$inject = ['Menus']; function menuConfig(menuService) { // Set top bar menu items menuService.addMenuItem('topbar', { title: 'Replies', state: 'replies', type: 'dropdown', roles: ['admin'] }); // Add the dropdown list item menuService.addSubMenuItem('topbar', 'replies', { title: 'List Replies', state: 'replies.list', roles: ['admin'] }); // Add the dropdown create item menuService.addSubMenuItem('topbar', 'replies', { title: 'Create Reply', state: 'replies.create', roles: ['admin'] }); } }());
e178551/mean.edu
modules/replies/client/config/replies.client.config.js
JavaScript
mit
703
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _alaska = require('alaska'); var _PostCat = require('./PostCat'); var _PostCat2 = _interopRequireDefault(_PostCat); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class Post extends _alaska.Model { async preSave() { if (!this.createdAt) { this.createdAt = new Date(); } if (!this.seoTitle) { this.seoTitle = this.title; } if (this.cat) { let cats = []; if (this.cat) { // $Flow findById let catTemp = await _PostCat2.default.findById(this.cat); if (catTemp) { cats.push(catTemp); } while (catTemp && catTemp.parent) { // $Flow findById let c = await _PostCat2.default.findById(catTemp.parent); catTemp = c; cats.push(catTemp); } // $Flow cat._id和PostCat不兼容 cats = cats.map(cat => cat._id); } this.cats = cats; } } } exports.default = Post; Post.label = 'Post'; Post.icon = 'file-text-o'; Post.defaultColumns = 'pic title cat user createdAt'; Post.defaultSort = '-createdAt'; Post.searchFields = 'title summary'; Post.autoSelect = false; Post.api = { paginate: 1, show: 1 }; Post.populations = { tags: {}, user: { select: ':tiny' }, cat: { select: 'title' }, relations: { select: ':tiny' } }; Post.scopes = { tiny: 'title hots createdAt', list: 'title user summary pic tags commentCount hots createdAt' }; Post.fields = { title: { label: 'Title', type: String, required: true }, user: { label: 'User', type: 'relationship', ref: 'alaska-user.User' }, cat: { label: 'Post Category', type: 'category', ref: 'PostCat' }, cats: { label: 'Categories', ref: ['PostCat'], hidden: true, private: true }, seoTitle: { label: 'SEO Title', type: String, default: '' }, seoKeywords: { label: 'SEO Keywords', type: String, default: '' }, seoDescription: { label: 'SEO Description', type: String, default: '' }, summary: { label: 'Summary', type: String, default: '' }, pic: { label: 'Main Picture', type: 'image' }, content: { label: 'Content', type: 'html', default: '' }, tags: { label: 'Tags', ref: ['PostTag'] }, source: { label: 'Source', type: String }, commentCount: { label: 'Comment Count', type: Number, default: 0 }, hots: { label: 'Hots', type: Number, default: 0 }, recommend: { label: 'Recommend', type: Boolean }, relations: { label: 'Related Posts', ref: ['Post'] }, topics: { label: 'Related Topic', ref: ['PostTopic'] }, createdAt: { label: 'Created At', type: Date } };
maichong/alaska
packages/alaska-post/models/Post.js
JavaScript
mit
2,899
import React from 'react'; import SVG from './SVG'; export default props => ( <SVG viewBox="0 0 1000 1000" fill="black" {...props}> <metadata> Svg Vector Icons : http://www.onlinewebfonts.com/icon </metadata> <g> <path d="M990,503.4c0,25.9-21,46.9-46.9,46.9H56.9c-25.9,0-46.9-21-46.9-46.9v-4.6c0-25.9,21-46.9,46.9-46.9h886.1c25.9,0,46.9,21,46.9,46.9V503.4z" /><path d="M430.9,131.1c18.3,18.3,18.3,48.1,0,66.4L93.1,535.2c-18.3,18.3-48.1,18.3-66.4,0l-2.9-2.9C5.5,514,5.5,484.3,23.9,466l337.7-337.7c18.3-18.3,48.1-18.3,66.4,0L430.9,131.1z" /><path d="M430.9,868.9c18.3-18.3,18.3-48.1,0-66.4L93.1,464.8c-18.3-18.3-48.1-18.3-66.4,0l-2.9,2.9C5.5,486,5.5,515.7,23.9,534l337.7,337.7c18.3,18.3,48.1,18.3,66.4,0L430.9,868.9z" /> </g> </SVG> );
bogas04/SikhJS
src/components/Icons/Previous.js
JavaScript
mit
757
(function(app) { "use strict"; app.controller("BookEditCtrl", [ "$rootScope", "$routeParams", "$location", "apiService", "notifierService", "identityService", "fileService", "sharedService", function($rootScope, $routeParams, $location, apiService, notifierService, identityService, fileService, sharedService) { var vm = this; vm.init = function() { vm.book = {}; vm.categories = []; apiService.get("/api/books/" + $routeParams.id).success(function(result) { vm.book = result; apiService.get("/api/categories/").success(function(categories) { vm.categories = categories; }); }).error(function() { $location.path("/").replace(); }); }(); vm.update = function() { vm.BookEditForm.submitted = true; if (identityService.isLoggedIn() && vm.BookEditForm.$valid) { vm.editingBook = true; var config = { headers: identityService.getSecurityHeaders() } apiService.put("/api/books/", vm.book, config).success(function() { notifierService.notifySuccess("Book updated successfully!"); vm.editingBook = false; }).error(function(errorResponse) { vm.editingBook = false; sharedService.displayErrors(errorResponse); }); } }; $rootScope.$on("Broadcast::RatingAvailable", function(event, score) { vm.book.rating = score; }); vm.uploadPhoto = function(file) { if (!file) { return; } var errorMessages = []; if (file.size > 1024 * 1024 * 2) { errorMessages.push("File size is too large. Max upload size is 2MB."); } if (errorMessages.length) { notifierService.notifyInfo(errorMessages); } else { if (fileService.isFileReaderSupported && file.type.indexOf("image") > -1) { vm.editingBook = true; var uploadConfig = { url: "/api/books/upload", data: { id: $routeParams.id, file: file } }; fileService.postMultipartForm(uploadConfig).progress(function(evt) { console.log("percent: " + parseInt(100.0 * evt.loaded / evt.total)); }).success(function(result) { vm.book = result; notifierService.notifySuccess("Cover updated successfully!"); vm.editingBook = false; }).error(function(errorResponse) { vm.editingBook = false; sharedService.displayErrors(errorResponse); }); } } }; } ]); })(angular.module("books"));
shibbir/bookarena
Source/BookArena.Presentation/Scripts/books/controllers/books.edit.controller.js
JavaScript
mit
3,357
const { viewModes } = require('../../../core/lib/viewMode'); /** * Interactions handlers for Voxels object * @method Voxels * @memberof K3D.Providers.ThreeJS.Interactions */ module.exports = function (object, K3D) { function onClickCallback(intersect) { K3D.dispatch(K3D.events.OBJECT_CLICKED, intersect); return false; } function onHoverCallback(intersect) { K3D.dispatch(K3D.events.OBJECT_HOVERED, intersect); return false; } return { onHover(intersect, viewMode) { switch (viewMode) { case viewModes.callback: return onHoverCallback(intersect); default: return false; } }, onClick(intersect, viewMode) { switch (viewMode) { case viewModes.callback: return onClickCallback(intersect); default: return false; } }, }; };
K3D-tools/K3D-jupyter
js/src/providers/threejs/interactions/intersectCallback.js
JavaScript
mit
1,010
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ const wiggleSort = function (nums) { if (!nums || nums.length < 2) { return; } let midVal = findKthElement(nums, Math.floor(nums.length / 2)); let smallerCount = 0, biggerCount = 0; for (let num of nums) { if (num > midVal) { ++biggerCount; } else if (num < midVal) { ++smallerCount; } } let leftMidCount = Math.ceil(nums.length / 2) - smallerCount; let leftMidEnd = (leftMidCount - 1) * 2; let rightMidBegin = biggerCount * 2 + 1; let smallerBegin = leftMidEnd + 2; let s = getNextSmallerIndex(-1, smallerBegin); let m = getNextMidIndex(-2, leftMidEnd, rightMidBegin); let b = getNextBiggerIndex(-1); while (s < nums.length) { if (nums[s] === midVal) { swap(nums, s, m); m = getNextMidIndex(m, leftMidEnd, rightMidBegin); } else if (nums[s] > midVal) { swap(nums, s, b); b = getNextBiggerIndex(b); } else { s = getNextSmallerIndex(s, smallerBegin); } } while (b < rightMidBegin) { if (nums[b] === midVal) { swap(nums, b, m); m = getNextMidIndex(m, leftMidEnd, rightMidBegin); } else { b = getNextBiggerIndex(b); } } }; // use prevIndex = -2 to get the first index function getNextMidIndex(prevIndex, leftMidEnd, rightMidBegin) { return prevIndex === leftMidEnd ? rightMidBegin : prevIndex + 2; } // use prevIndex = -1 to get the first index function getNextSmallerIndex(prevIndex, smallerBegin) { return prevIndex === -1 ? smallerBegin : prevIndex + 2; } // use prevIndex = -1 to get the first index function getNextBiggerIndex(prevIndex) { return prevIndex === -1 ? 1 : prevIndex + 2; } // k is from 0. O(n) time and O(1) space function findKthElement(nums, k) { return quickHelper(nums, k, 0, nums.length - 1); } function quickHelper(nums, k, left, right) { let pivot = nums[right]; let pivotIndex = partition(nums, left, right - 1, pivot); if (pivotIndex === k) { return pivot; } swap(nums, pivotIndex, right); return pivotIndex > k ? quickHelper(nums, k, left, pivotIndex - 1) : quickHelper(nums, k, pivotIndex + 1, right); } function partition(nums, left, right, pivot) { let idx = left, storeIdx = left; while (idx <= right) { if (nums[idx] < pivot) { swap(nums, idx, storeIdx); ++storeIdx; } ++idx; } return storeIdx; } function swap(nums, m, n) { [nums[m], nums[n]] = [nums[n], nums[m]]; } module.exports = wiggleSort;
alenny/leetcode
src/wiggle-sort-2/index.js
JavaScript
mit
2,741
(function () { 'use strict'; angular.module('commonModule'). service('Adsense', [function () { this.url = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'; this.isAlreadyLoaded = false; }]). directive('adsense', function () { return { restrict: 'E', replace: true, scope: { adClient: '@', adSlot: '@', adFormat: '@', inlineStyle: '@', viewportMinWidth: '@', viewportMaxWidth: '@' }, template: '<div data-ng-show="adFitInViewport" class="ads mt-2">' + '<ins data-ng-class="{\'adsbygoogle\': adFitInViewport}" ' + 'data-ad-client="{{adClient}}" ' + 'data-ad-slot="{{adSlot}}" ' + 'ng-attr-data-ad-format="{{adFormat || undefined}}" ' + 'style="{{inlineStyle}}" ' + '"></ins></div>', controller: ['Adsense', '$scope', '$window', '$timeout', function (Adsense, $scope, $window, $timeout) { $scope.adFitInViewport = true; if (($scope.viewportMinWidth && $window.innerWidth < $scope.viewportMinWidth) || ($scope.viewportMaxWidth && $window.innerWidth > $scope.viewportMaxWidth)) { $scope.adFitInViewport = false; return; } if (!Adsense.isAlreadyLoaded) { var s = document.createElement('script'); s.type = 'text/javascript'; s.src = Adsense.url; s.async = true; document.body.appendChild(s); Adsense.isAlreadyLoaded = true; } /** * We need to wrap the call the AdSense in a $apply to update the bindings. * Otherwise, we get a 400 error because AdSense gets literal strings from the directive */ $timeout(function () { (window.adsbygoogle = window.adsbygoogle || []).push(); }); }] }; }); }());
mdarif-k/way2programming
src/js/adsense.js
JavaScript
mit
2,414
"use strict"; var session = require('../utils/session.js'); var errors = require('../utils/errors.js'); var Service = { /** * @param {String} params.username The user username or email. * @param {String} params.password The user (hashed) password. */ login: function(params, callback, sid, req, res) { session.initiate(params.username, params.password, res).then(function(data) { callback(null, data); }).catch(function(err) { callback(err); }); }, logout: function(params, callback, sid, req) { session.verify(req).then(function() { callback(null, true); }).catch(function(err) { callback(err); }); }, /** * Returns the currently authenticated user. */ user: function(params, callback, sid, req) { session.verify(req).then(function(session) { callback(null, session.user); }).catch(function(err) { callback(err); }); } }; module.exports = Service;
sencha-extjs-examples/Coworkee
server/api/auth.js
JavaScript
mit
1,055
define(function (require) { describe("scaleValue tests", function () { var d3 = require("d3"); var scaleValue = require("src/modules/helpers/scale_value"); var d3scale = d3.scale.linear(); var domain = [1, 200]; var range = [0, 100]; var callback = function (d) { return d.y; }; var data = [ {y: 45}, {y: 55}, {y: 65}, {y: 75}, {y: 85} ]; var scale; beforeEach(function () { d3scale.domain(domain).range(range); scale = scaleValue(d3scale, callback); }); it("should return a function", function () { chai.assert.isFunction(scale); }); it("should scale values", function () { var scaledValues = data.map(function (d) { return scale(d); }); chai.assert.equal(scaledValues[0], d3scale(data[0].y)); chai.assert.equal(scaledValues[4], d3scale(data[4].y)); }); }); });
panda01/jubilee
test/unit/specs/modules/helpers/scale_value.js
JavaScript
mit
910
define([ 'backbone' ], function (Backbone) { var PostModel = Backbone.Model.extend({ }); return PostModel; });
dobrite/zebra
public/js/post_model.js
JavaScript
mit
129
////////// JS theme file for PopCalendarXP 9.0 ///////// // This file is totally configurable. You may remove all the comments in this file to minimize the download size. // Since the plugins are loaded after theme config, sometimes we would redefine(override) some theme options there for convenience. //////////////////////////////////////////////////////// // ---- PopCalendar Specific Options ---- var gsSplit="/"; // separator of date string. If set it to empty string, then giMonthMode and gbPadZero will be fixed to 0 and true. var giDatePos=1; // date format sequence 0: D-M-Y ; 1: M-D-Y; 2: Y-M-D var gbPadZero=true; // whether to pad the digits with 0 in the left when less than 10. var giMonthMode=0; // month format 0: digits ; 1: full name from gMonths; >2: abbreviated month name in specified length. var gbShortYear=false; // year format true: 2-digits; false: 4-digits var gbAutoPos=true; // enable auto-adpative positioning or not var gbPopDown=true; // true: pop the calendar below the dateCtrl; false: pop above if gbAutoPos is false. var gbAutoClose=true; // whether to close the calendar after selecting a date. var gPosOffset=[0,0]; // Offsets used to adjust the pop-up postion, [leftOffset, topOffset]. var gbFixedPos=false; // true: pop the calendar absolutely at gPosOffset; false: pop it relatively. // ---- Common Options ---- var gMonths=["January","February","March","April","May","June","July","August","September","October","November","December"]; var gWeekDay=["S","M","T","W","T","F","S"]; // weekday caption from Sunday to Saturday var gBegin=[1980,1,1]; // calendar date range begin from [Year,Month,Date]. Using gToday here will make it start from today. var gEnd=[2030,12,31]; // calendar date range end at [Year,Month,Date] var gsOutOfRange="Sorry, you may not go beyond the designated range!"; // out-of-date-range error message. If set to "", no alerts will popup on such error. var guOutOfRange=null; // the background image url for the out-range dates. e.g. "outrange.gif" var giFirstDOW=0; // indicates the first day of week. 0:Sunday; 1-6:Monday-Saturday. var gcCalBG="white"; // the background color of the outer calendar panel. var guCalBG=null; // the background image url for the inner table. var gcCalFrame="white"; // the background color of the inner table, showing as a frame. var gsInnerTable="border=0 cellpadding=1 cellspacing=0"; // HTML tag properties of the inner <table> tag, which holds all the calendar cells. var gsOuterTable=NN4?"border=1 cellpadding=3 cellspacing=0":"border=0 cellpadding=0 cellspacing=1"; // HTML tag properties of the outmost container <table> tag, which holds the top, middle and bottom sections. var gbHideTop=false; // true: hide the top section; false: show it according to the following settings var giDCStyle=1; // the style of month-controls in top section. 0: use predefined html dropdowns & gsNavPrev/Next; 1: use gsCalTitle & gsNavPrev/Next; 2: use only gsCalTitle; var gsCalTitle="gMonths[gCurMonth[1]-1]+' '+gCurMonth[0]"; // dynamic statement to be eval()'ed as the title when giDCStyle>0. var gbDCSeq=true; // (effective only when giDCStyle is 0) true: show month box before year box; false: vice-versa; var gsYearInBox="i"; // dynamic statement to be eval()'ed as the text shown in the year box. e.g. "'A.D.'+i" will show "A.D.2001" var gsNavPrev="<IMG id='navPrev' class='MonthNav' src='arrowl.gif' width='6' height='10' border='0' alt='' onmousedown='showPrevMon()' onmouseup='stopShowMon()' onmouseout='stopShowMon();if(this.blur)this.blur()'>"; // the content of the left month navigator var gsNavNext="<IMG id='navNext' class='MonthNav' src='arrowr.gif' width='6' height='10' border='0' alt='' onmousedown='showNextMon()' onmouseup='stopShowMon()' onmouseout='stopShowMon();if(this.blur)this.blur()'>"; // the content of the right month navigator var gbHideBottom=false; // true: hide the bottom section; false: show it with gsBottom. var gsBottom=(NN4?"":"<DIV class='BottomDiv'>")+"<A class='BottomAnchor' href='javascript:void(0)' onclick='if(this.blur)this.blur();if(!fSetDate(gToday[0],gToday[1],gToday[2]))alert(\"You cannot select today!\");return false;' onmouseover='return true;' >Today</A>"+(NN4?"":"</DIV>"); // the content of the bottom section. var giCellWidth=NN4?18:16; // calendar cell width; var giCellHeight=14; // calendar cell height; var giHeadHeight=14; // calendar head row height; var giWeekWidth=22; // calendar week-number-column width; var giHeadTop=0; // calendar head row top offset; var giWeekTop=0; // calendar week-number-column top offset; var gcCellBG="white"; // default background color of the cells. Use "" for transparent!!! var gsCellHTML=""; // default HTML contents for days without any agenda, usually an image tag. var guCellBGImg=""; // url of default background image for each calendar cell. var gsAction=" "; // default action to be eval()'ed on everyday except the days with agendas, which have their own actions defined in agendas. var gsDays="dayNo"; // the dynamic statement to be eval()'ed into each day cell. var giWeekCol=-1; // -1: disable week-number-column; 0~7: show week numbers at the designated column. var gsWeekHead="#"; // the text shown in the table head of week-number-column. var gsWeeks="weekNo"; // the dynamic statement to be eval()'ed into the week-number-column. e.g. "'week '+weekNo" will show "week 1", "week 2" ... var gcWorkday="#606060"; // Workday font color var gcSat="#606060"; // Saturday font color var gcSatBG=null; // Saturday background color var gcSun="#606060"; // Sunday font color var gcSunBG=null; // Sunday background color var gcOtherDay="gainsboro"; // the font color of days in other months; It's of no use when giShowOther is set to hide. var gcOtherDayBG=gcCellBG; // the background color of days in other months. when giShowOther set to hiding, it'll substitute the gcOtherDay. var giShowOther=1+2; // control the look of days in OTHER months. 1: show date & agendas effects; 2: show selected & today effects; 4: hide days in previous month; 8: hide days in next month; 16: when set with 4 and/or 8, the days will be visible but not selectable. NOTE: values can be added up to create mixed effects. var gbFocus=false; // whether to enable the gcToggle highlight whenever mouse pointer focuses over a calendar cell. var gcToggle="#D4D0C8"; // the highlight color for the focused cell var gcFGToday="white"; // the font color for today var gcBGToday="#800000"; // the background color for today var guTodayBGImg=""; // url of image as today's background var giMarkToday=2; // Effects for today - 0: nothing; 1: set background color with gcBGToday; 2: draw a box with gcBGToday; 4: bold the font; 8: set font color with gcFGToday; 16: set background image with guTodayBGImg; - they can be added up to create mixed effects. var gsTodayTip="Today"; // tooltip for today var gcFGSelected="white"; // the font color for the selected date var gcBGSelected=gcToggle; // the background color for the selected date var guSelectedBGImg=""; // url of image as background of the selected date var giMarkSelected=1+8; // Effects for selected date - 0: nothing; 1: set background color with gcBGSelected; 2: draw a box with gcBGSelected; 4: bold the font; 8: set font color with gcFGSelected; 16: set background image with guSelectedBGImg; - they can be added up to create mixed effects. var gsSelectedTip=""; // tooltip for selected dates var gbBoldAgenda=true; // whether to boldface the dates with agendas. var gbInvertBold=false; // true: invert the boldface effect set by gbBoldAgenda; false: no inverts. var gbShrink2fit=true; // whether to hide the week line if none of its day belongs to the current month. var gdSelect=[0,0,0]; // default selected date in format of [year, month, day]; [0,0,0] means no default date selected. var giFreeDiv=1; // The number of absolutely positioned layers you want to customize, they will be named as "freeDiv0", "freeDiv1"... var gAgendaMask=[-1,-1,gcCellBG,"black",null,false,null]; // [message, action, bgcolor, fgcolor, bgimg, boxit, html] - Set the relevant bit to -1 to keep the original agenda/event value of that bit intact. Any other value will be used to override the original one defined in agenda.js. Check the tutorial for details. var giResizeDelay=KO3?150:50; // delay in milliseconds before resizing the calendar panel. Calendar may have incorrect initial size if this value is too small. var gbFlatBorder=false; // flat the .CalCell css border of any agenda date by setting it to solid style. NOTE: it should always be set to false if .CalCell has no explicit border size. var gbInvertBorder=false; // true: invert the effect caused by gbFlatBorder; false: no change. var gbShareAgenda=false; // if set to true, a global agenda store will be created and used to share across calendars. Check tutorials for details. var gsAgShared="gContainer._cxp_agenda"; // shared agenda store name used when gbShareAgenda is true. var gbCacheAgenda=false; // false: will prevent the agenda url from being cached; true: cached as normal js file. var giShowInterval=250; // interval time in milliseconds that controls the auto-traverse speed.
victorwon/calendarxp
PopCalXP/themes/Outlook/outlook.js
JavaScript
mit
9,298
var _ = require('underscore'); module.exports = function (app) { app.post('/api/filter', function (req, res) { // console.log('inside service call'); //console.log(req.body); var resp = _.filter(_.where(req.body.payload, {drm: true}), function (item) { return item.episodeCount > 0 }); var newArray = []; resp.forEach(function (item) { var newItem = _.pick(item, 'image', 'slug', 'title'); newItem.image = _.propertyOf(newItem.image)('showImage'); newArray.push(newItem); }) res.send(newArray); }); };
pinda-kaas/node_codechallenge
app/routes.js
JavaScript
mit
624
var suctrl = angular.module("suctrl",[]); suctrl.controller("sucontroller", function($scope,$http,AuthService,API_ENDPOINT,toaster){ var getListFood = function(){ $http.get(API_ENDPOINT.url + '/api/foods/findResBelongName').success(function(response){ $scope.listFood = response.data; }); }; var getListOder = function(){ $http.get(API_ENDPOINT.url + '/api/orders/getResName').success(function(response){ $scope.listOrder = response.data; }); } var getListPublicity = function(){ $scope.listPublicity = [] $http.get(API_ENDPOINT.url + '/api/restaurants/getAllPublicity').success(function(response){ for(var item in response.data){ if(response.data[item].publicities.length != 0){ $scope.listPublicity.push({ res_name : response.data[item].res_name, publicities : response.data[item].publicities }); } } }); } var getListService = function(){ $scope.listService = [] $http.get(API_ENDPOINT.url + '/api/restaurants/getAllService').success(function(response){ for(var item in response.data){ if(response.data[item].services.length != 0){ $scope.listService.push({ res_name : response.data[item].res_name, services : response.data[item].services }); } } }); } getListPublicity(); getListService(); getListOder(); getListFood(); })
CreativityTeam/CMS3721
client/cms/jslib/controllers/suctrl.js
JavaScript
mit
1,674
module.exports = xsd2json const childProcess = require('child_process') const concat = require('concat-stream') const path = require('path') const CLI = path.resolve(__dirname, 'lib-pl', 'cli.exe') const CLIPL = path.resolve(__dirname, 'lib-pl', 'cli.pl') const SWI = 'swipl' const reservedKeys = [ 'noExe', 'swi' ] function xsd2json (filename, options, callback) { if (arguments.length === 1) { options = {} callback = null } else if (arguments.length === 2) { if (typeof options === 'function') { callback = options options = {} } else { callback = null } } let spawnArgs = [] for (const key in options) { if (reservedKeys.indexOf(key) >= 0) { continue } spawnArgs.push('--' + key + '=' + options[key]) } spawnArgs.push(filename) let outputStream if (options.noExe) { spawnArgs = [ '-g', 'main', CLIPL, '--' ].concat(spawnArgs) outputStream = childProcess.spawn(options.swi || SWI, spawnArgs) } else { outputStream = childProcess.spawn(CLI, spawnArgs) } if (typeof callback !== 'function') { // no callback given --> return stream return outputStream } outputStream.stderr.on('data', function (err) { if (options.trace) { const lines = err.toString().split(/\n/) lines.forEach(function (line) { if (/^CHR:\s+\([0-9]+\)\s+Apply:.*$/.test(line)) { console.log(line) } }) } else { callback(err) } }) outputStream.stdout.pipe(reader(callback)) } function reader (callback) { return concat(function (jsonBuff) { const jsonString = jsonBuff.toString() let schema try { schema = JSON.parse(jsonString) } catch (err) { return callback(err) } callback(null, schema) }) }
fnogatz/xsd2json
index.js
JavaScript
mit
1,819
module.exports = function(gulp, plugins) { gulp.task('prod', function(cb) { plugins.sequence( 'compile:hooks', ['compile:api', 'compile:domain', 'compile:test'], 'mocha:test', cb ); }); };
AcklenAvenue/jazz
tasks/register/prod.js
JavaScript
mit
206
(function () { "use strict"; m.factory("models.todo", function () { return function () { var self = this, collection = []; this.create = function (item) { collection.push({ title : m.prop(item.title), description : m.prop(item.description), done : m.prop(item.done) }); return self; }; this.list = function () { var storage = JSON.parse(localStorage.getItem('todos')); collection = []; if (Array.isArray(storage) && storage.length) { storage.forEach(self.create); } return collection; }; this.save = function (update) { if (update) { collection = update; } localStorage.setItem('todos', JSON.stringify(collection)); return collection; }; return this; } }); })();
ilsenem/mithril-todo
app/js/models/todo.js
JavaScript
mit
911
export { default as clone } from './clone' export { default as compose } from './compose' export { default as createTest } from './createTest' export { default as createTests } from './createTests' export { default as expectAllExactEqual } from './expectAllExactEqual' export { default as expectEqual } from './expectEqual' export { default as expectImmutableChange } from './expectImmutableChange' export { default as expectImmutableResult } from './expectImmutableResult' export { default as getType } from './getType' export { default as getTypeFactory } from './getTypeFactory' export { default as hintConvert } from './hintConvert' export { default as hintSameType } from './hintSameType' export { default as isImmutable } from './isImmutable' export { default as runTest } from './runTest' export { default as runTests } from './runTests' export { default as setupTest } from './setupTest' export { default as toArgs } from './toArgs' export { default as toImmutable } from './toImmutable' export { default as toMutable } from './toMutable'
brianneisler/mudash
src/core/__tests__/util/index.js
JavaScript
mit
1,047
/** * @module users */ module.exports = function (cfg, db) { var mixins = require('./mixins')(cfg, db), _ = require('lodash'), Contact = mixins.Contact, Storable = mixins.Storable, coll = db.collection('users'); /** * @constructor * @class users.User * @uses mixins.Contact * @uses mixins.Storable */ function User() { Contact.call(this); Storable.call(this); /** * Contains associated oauth accounts. * Where `fbOauthData` is an * {{crossLink 'users.OauthData'}}OauthData{{/crossLink}} object * * @property oauths * @type {Object} */ this.oauths = {}; } User.prototype = _.extend({}, Contact.prototype); User.prototype = _.extend(User.prototype, Storable.prototype); /** * Oauth provider data for a user * @constructor * @class users.OauthData */ function OauthData() { /** * Provider's unique user ID * @property id * @type {String} */ this.id = null; /** * Access token * @property token * @type {String} */ this.token = null; /** * Refresh token * @property refreshToken * @type {String} */ this.refreshToken = null; /** * Access token expiry time * @property tokenExpiry * @type {Date} */ this.tokenExpiry = null; } /** * @constructor * @class users.Repo */ function Repo() {} Repo.add = function (user) { return this.getByEmail(user.email) .then(function (fetched) { return new Promise(function (resolve, reject) { if (fetched) { return reject(new Error( 'A user with this email already exists' )); } user.touch(); // Proceed with insert coll.insert(user, function (err, doc) { if (err) { reject(err); } user._id = doc._id; resolve(user._id); }); }); }); }; /** * Get user from database by ID * * @static * @method getById * @for users.Repo * @param {Object} id * @return {Promise} A {{#crossLink "users.User"}}user{{/crossLink}} * object if found, else `null` */ Repo.getById = function (id) { return new Promise(function (resolve, reject) { coll.findOne({ '_id': id }, function (err, doc) { if (err) { reject(err); } resolve(doc ? _.create(new User(), doc) : null); }); }); }; /** * Get user from database by email address * * @static * @method getByEmail * @for users.Repo * @param {String} email * @return {Promise} A {{#crossLink "users.User"}}user{{/crossLink}} * object if found, else `null` */ Repo.getByEmail = function (email) { return new Promise(function (resolve, reject) { coll.findOne({ 'email': email }, function (err, doc) { if (err) { reject(err, null); } resolve(doc ? _.create(new User(), doc) : null); }); }); }; /** * Update a user. This will not update the following: * - email address * * @static * @method update * @for users.Repo * @param {users.User} user * @return {Promise} Boolean result */ Repo.update = function (user) { return new Promise(function (resolve, reject) { user.touch(); coll.update({ '_id': user._id }, {'$set': user}, function (err) { if (err) { return reject(err); } resolve(true); }); }); }; return { 'User' : User, 'OauthData': OauthData, 'Repo' : Repo }; };
jigarjain/singlehood
core/users.js
JavaScript
mit
4,483
module.exports = function(grunt) { grunt.initConfig({ uglify: { min: { files: { "picturecaption.min.js": "picturecaption.js" } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask("js", [ "uglify" ]); };
iandevlin/picturecaption
Gruntfile.js
JavaScript
mit
252
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { if (n === 1) return 1; return 5; } global.ng.common.locales['es-ve'] = [ 'es-VE', [['a. m.', 'p. m.'], u, u], u, [ ['d', 'l', 'm', 'm', 'j', 'v', 's'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'] ], [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'] ], [ ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sept.', 'oct.', 'nov.', 'dic.' ], [ 'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre' ] ], u, [['a. C.', 'd. C.'], u, ['antes de Cristo', 'después de Cristo']], 0, [6, 0], ['d/M/yy', 'd MMM y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', u, '{1} \'a\' \'las\' {0}', u], [',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '¤#,##0.00;¤-#,##0.00', '#E0'], 'Bs.S', 'bolívar soberano', { 'AUD': [u, '$'], 'BRL': [u, 'R$'], 'CAD': [u, '$'], 'CNY': [u, '¥'], 'ESP': ['₧'], 'EUR': [u, '€'], 'FKP': [u, 'FK£'], 'GBP': [u, '£'], 'HKD': [u, '$'], 'ILS': [u, '₪'], 'INR': [u, '₹'], 'JPY': [u, '¥'], 'KRW': [u, '₩'], 'MXN': [u, '$'], 'NZD': [u, '$'], 'RON': [u, 'L'], 'SSP': [u, 'SD£'], 'SYP': [u, 'S£'], 'TWD': [u, 'NT$'], 'USD': [u, '$'], 'VEF': ['Bs.'], 'VES': ['Bs.S'], 'VND': [u, '₫'], 'XAF': [], 'XCD': [u, '$'], 'XOF': [] }, plural, [ [['del mediodía', 'de la madrugada', 'de la mañana', 'de la tarde', 'de la noche'], u, u], [ ['m.', 'madrugada', 'mañana', 'tarde', 'noche'], ['mediodía', 'madrugada', 'mañana', 'tarde', 'noche'], u ], ['12:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '20:00'], ['20:00', '24:00']] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
mprobst/angular
packages/common/locales/global/es-VE.js
JavaScript
mit
3,108
var searchModule=function(n,t,i,r){var u=function(){var n=this,i=[{name:"Platform (All)",id:-1}];r.getConsoles().forEach(function(n){i.push(n)});n.activity=t.observable();n.consoleList=t.observableArray(i);n.consoleId=t.observable();n.microphone=t.observable();n.game=t.observable();n.search=function(){var n=t.toJSON({Name:this.activity,ConsoleId:this.consoleId,Game:this.game,Microphone:this.microphone});r.getActivities(n)}},f=function(){t.applyBindings(u,document.getElementById("Search"))};return{init:f}}(jQuery,ko,listActivitiesModule,dataModule);searchModule.init(); //# sourceMappingURL=vm.search.min.js.map
amerismail/LFG
LFG.Web/Scripts/app/vm.search.min.js
JavaScript
mit
620
var mapMain; // @formatter:off require([ "esri/map", "esri/toolbars/draw", "esri/graphic", "esri/graphicsUtils", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/Color", "dojo/ready", "dojo/parser", "dojo/on", "dojo/_base/array"], function (Map, Draw, Graphic, graphicsUtils, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Color, ready, parser, on, array) { // @formatter:on // Wait until DOM is ready *and* all outstanding require() calls have been resolved ready(function () { // Parse DOM nodes decorated with the data-dojo-type attribute parser.parse(); // Create the map mapMain = new Map("divMap", { basemap: "topo", center: [-122.45, 37.75], zoom: 12 }); /* * Step: Construct the Geoprocessor */ mapMain.on("load", function () { /* * Step: Set the spatial reference for output geometries */ }); // Collect the input observation point var tbDraw = new Draw(mapMain); tbDraw.on("draw-end", calculateViewshed); tbDraw.activate(Draw.POINT); function calculateViewshed(evt) { // clear the graphics layer mapMain.graphics.clear(); // marker symbol for drawing viewpoint var smsViewpoint = new SimpleMarkerSymbol(); smsViewpoint.setSize(12); smsViewpoint.setOutline(new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255]), 1)); smsViewpoint.setColor(new Color([0, 0, 0])); // add viewpoint to the map var graphicViewpoint = new Graphic(evt.geometry, smsViewpoint); mapMain.graphics.add(graphicViewpoint); /* * Step: Prepare the first input parameter */ /* * Step: Prepare the second input parameter */ /* * Step: Build the input parameters into a JSON-formatted object */ /* * Step: Wire and execute the Geoprocessor */ } function displayViewshed(results, messages) { // polygon symbol for drawing results var sfsResultPolygon = new SimpleFillSymbol(); sfsResultPolygon.setOutline(new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 0, 0.5]), 1)); sfsResultPolygon.setColor(new Color([255, 127, 0, 0.5])); /* * Step: Extract the array of features from the results */ // loop through results array.forEach(arrayFeatures, function (feature) { /* * Step: Symbolize and add each graphic to the map's graphics layer */ }); // update the map extent var extentViewshed = graphicsUtils.graphicsExtent(mapMain.graphics.graphics); mapMain.setExtent(extentViewshed, true); } }); });
TxDOT/JavaScriptClassPrep
jkleinert/Student/WAJA/ViewshedAnalysis/js/map.js
JavaScript
mit
3,504
import React from 'react' import DocumentTitle from 'react-document-title' import { config } from 'config' require('../components/ProseContent/prose-content.scss'); module.exports = React.createClass({ propTypes () { return { router: React.PropTypes.object, } }, render () { const post = this.props.route.page.data return ( <DocumentTitle title={`${post.title} | ${config.siteTitle}`}> <article className="prose-content"> <h1 className="prose-content__title">{post.title}</h1> <div className="prose-content__body" dangerouslySetInnerHTML={{ __html: post.body }} /> </article> </DocumentTitle> ) }, })
petemill/petemill-personal
wrappers/md.js
JavaScript
mit
684
/* * THIS FILE IS AUTO GENERATED from 'lib/statement.kep' * DO NOT EDIT */ "use strict"; var __o = require("./node"), Node = __o["Node"], defineNode = __o["defineNode"], Statement, DebuggerStatement, BlockStatement, ExpressionStatement, EmptyStatement, IfStatement, LabeledStatement, BreakStatement, ContinueStatement, WithStatement, SwitchStatement, ReturnStatement, ThrowStatement, TryStatement, WhileStatement, DoWhileStatement, ForStatement, ForInStatement; (Statement = (function() { var self = this; })); (Statement.prototype = new(Node)()); (EmptyStatement = defineNode(Statement, "EmptyStatement", [], [], (function(loc) { var self = this; Node.call(self, loc); }))); (DebuggerStatement = defineNode(Statement, "DebuggerStatement", [], [], (function(loc) { var self = this; Node.call(self, loc); }))); (BlockStatement = defineNode(Statement, "BlockStatement", ["body"], [], (function(loc, body) { var self = this; Node.call(self, loc); (self.body = body); }))); (ExpressionStatement = defineNode(Statement, "ExpressionStatement", ["expression"], [], (function(loc, expression) { var self = this; Node.call(self, loc); (self.expression = expression); }))); (IfStatement = defineNode(Statement, "IfStatement", ["test", "consequent", "alternate"], [], (function(loc, test, consequent, alternate) { var self = this; Node.call(self, loc); (self.test = test); (self.consequent = consequent); (self.alternate = (alternate || null)); }))); (LabeledStatement = defineNode(Statement, "LabeledStatement", ["body"], [], (function(loc, label, body) { var self = this; Node.call(self, loc); (self.label = label); (self.body = body); }))); (BreakStatement = defineNode(Statement, "BreakStatement", ["label"], [], (function(loc, label) { var self = this; Node.call(self, loc); (self.label = (label || null)); }))); (ContinueStatement = defineNode(Statement, "ContinueStatement", ["label"], [], (function(loc, label) { var self = this; Node.call(self, loc); (self.label = (label || null)); }))); (WithStatement = defineNode(Statement, "WithStatement", ["object", "body"], [], (function(loc, object, body) { var self = this; Node.call(self, loc); (self.object = object); (self.body = body); }))); (SwitchStatement = defineNode(Statement, "SwitchStatement", ["discriminant", "cases"], [], (function(loc, discriminant, cases) { var self = this; Node.call(self, loc); (self.discriminant = discriminant); (self.cases = cases); }))); (ReturnStatement = defineNode(Statement, "ReturnStatement", ["argument"], [], (function(loc, argument) { var self = this; Node.call(self, loc); (self.argument = (argument || null)); }))); (ThrowStatement = defineNode(Statement, "ThrowStatement", ["argument"], [], (function(loc, argument) { var self = this; Node.call(self, loc); (self.argument = argument); }))); (TryStatement = defineNode(Statement, "TryStatement", ["block", "handler", "finalizer"], [], (function(loc, block, handler, finalizer) { var self = this; Node.call(self, loc); (self.block = block); (self.handler = handler); (self.finalizer = finalizer); }))); (WhileStatement = defineNode(Statement, "WhileStatement", ["test", "body"], [], (function(loc, test, body) { var self = this; Node.call(self, loc); (self.test = test); (self.body = body); }))); (DoWhileStatement = defineNode(Statement, "DoWhileStatement", ["body", "test"], [], (function(loc, body, test) { var self = this; Node.call(self, loc); (self.test = test); (self.body = body); }))); (ForStatement = defineNode(Statement, "ForStatement", ["init", "test", "update", "body"], [], (function(loc, init, test, update, body) { var self = this; Node.call(self, loc); (self.init = (init || null)); (self.test = (test || null)); (self.update = (update || null)); (self.body = body); }))); (ForInStatement = defineNode(Statement, "ForInStatement", ["left", "right", "body"], [], (function(loc, left, right, body) { var self = this; Node.call(self, loc); (self.left = left); (self.right = right); (self.body = body); }))); (exports.Statement = Statement); (exports.DebuggerStatement = DebuggerStatement); (exports.BlockStatement = BlockStatement); (exports.ExpressionStatement = ExpressionStatement); (exports.EmptyStatement = EmptyStatement); (exports.IfStatement = IfStatement); (exports.LabeledStatement = LabeledStatement); (exports.BreakStatement = BreakStatement); (exports.ContinueStatement = ContinueStatement); (exports.WithStatement = WithStatement); (exports.SwitchStatement = SwitchStatement); (exports.ReturnStatement = ReturnStatement); (exports.ThrowStatement = ThrowStatement); (exports.TryStatement = TryStatement); (exports.WhileStatement = WhileStatement); (exports.DoWhileStatement = DoWhileStatement); (exports.ForStatement = ForStatement); (exports.ForInStatement = ForInStatement);
mattbierner/ecma-ast
dist_node/statement.js
JavaScript
mit
5,050
import Layout from '../components/Layout'; import Link from '../components/Link'; import Neumorphism from '../components/Neumorphism'; import PageHead from '../components/PageHead'; import { meta } from '../page-config'; const NeumorphismPage = () => ( <Layout> <PageHead meta={meta.neu} /> <article> <h1>Neumorphism Experiment</h1> <p> I&apos;ve been seeing a lot of &quot;Neumorphism&quot; designs appearing lately, so I thought I&apos;d have a go at implementing it using the tailwind colour palette. </p> <p> Tailwind lends itself to this quite nicely as it provides a good range across each colour set. </p> <p> To produce the hover effect I applied a shadow to the ::after element and an inset shadow to main element. This is necessary as I discovered you cannot animate to and from an inset/regular box shadow, so each is animated separately to and from transparent. </p> <p> Each element has 3 shadows made up of shades of the background colour. To see this more clearly, you can remove the background below. </p> <p> The tailwind plugin I wrote can be found {' '} <Link text="on Github." underline href="https://github.com/searleb/billsearle.me/tree/master/src/components/Neumorphism" /> </p> <Neumorphism /> </article> </Layout> ); export default NeumorphismPage;
searleb/searleb.github.io
src/pages/neumorphism-experiment.js
JavaScript
mit
1,506
import React from 'react'; const BlockPhoto = ({ photo }) => ( <div className="photo-view_img"> <h1>{photo.name}</h1> <img src={photo.image} alt="image" /> </div> ); BlockPhoto.propTypes = { photo: React.PropTypes.object, }; BlockPhoto.defaultProps = { photo: { name: '', image: '', comments: [], }, }; export default BlockPhoto;
sandim27/ReduxApp
app/components/PhotoBlock/index.js
JavaScript
mit
364
/** * Controller for Delving search module. */ define( ['backbone', 'backbone.marionette', 'communicator', 'plugins/module-search', 'backgrid', 'backgrid.paginator', 'plugins/zev/zev-collection', 'models/state', 'views/search/search-wait', 'views/results-view', 'views/search/search-field', 'plugins/zev/zev-facets-view', 'plugins/zev/zev-date-filter-view'], function(Backbone, Marionette, Communicator, SearchModule, Backgrid, PaginatorView, ZoekEnVindCollection, State, WaitView, ResultsView, SearchView, ZevFacetsView, ZevDateFilterView) { return SearchModule.extend({ module: { 'type': 'search', 'title': 'Zoek ONH' }, markers: null, facets: null, items: null, query: null, initialize: function(o) { var self = this; this.markers = o.markers_collection; this.facets = new Backbone.Collection(); this.results = new ZoekEnVindCollection(); var SearchModel = Backbone.Model.extend( { defaults: { terms: '', date: { from: '', to: '' }, facets: [], viewportFilter: false, numfound: 0 } }); this.model = new SearchModel(); // Event triggered by "VOEG TOE" action on search result card. Communicator.mediator.on( "marker:addModelId", function(options) { var result = self.results.findWhere( {cid: options.cid} ); if (!result) return; // The record model contains a lot of extract information that the marker doesn't need, // and the essential info (a unique ID) is not available. Here we extra the useful info // so the result model can be destroyed with pagination, etc. var attrs = ['__id__', 'title', 'image', 'description', 'youtube', 'externalUrl', 'spatial', 'year']; var vars = { type: options.type }; _.each(attrs, function(key) { vars[key] = result.get(key); }); if ( !State.getPlugin('geojson_features').collection.findWhere({ '__id__': vars['__id__'] })) { State.getPlugin('geojson_features').collection.add( vars ); } }); this.listenTo(this.model, "change:terms", function() { self.results.state.terms = self.model.get('terms'); self.getResults(); }); this.listenTo(this.model, "change:facets", function() { self.results.state.facets = self.model.get('facets'); self.getResults(); }); this.listenTo(this.model, "change:date", function() { self.results.state.date = self.model.get('date'); self.getResults(); }); this.listenTo(this.model, "change:viewportFilter", function() { self.getResults(); }); }, // Overrides parent to implement facets (a bit overkill) getResults: function() { var self = this; if (this.resultsView) this.resultsView.destroy(); if (this.facetsView) this.facetsView.remove(); if (this.paginationView) this.paginationView.remove(); this.layout.getRegion( 'progress' ).show( new WaitView() ); //reset paginator to first page this.results.state.currentPage = 1; if (self.model.get('viewportFilter')) { // Update model with current map location before executing the search. var map = Communicator.reqres.request( 'getMap'), bounds = map.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast(); self.results.state.geoFence = { type: 'AND', values: [ 'minGeoLat=' + sw.lat, 'minGeoLong=' + sw.lng, 'maxGeoLat=' + ne.lat, 'maxGeoLong=' + ne.lng ] }; } else { self.results.state.geoFence = null; } self.results.fetch({ success: function(collection) { self.facetsView = new ZevFacetsView({ collection: collection.getFacetConfig(), searchModel: self.model }); self.resultsView = new ResultsView( {collection: collection} ); self.paginationView = new Backgrid.Extension.Paginator( { collection: collection, windowSize: 5 } ); self.layout.getRegion( 'facets' ).show( self.facetsView ); self.layout.getRegion( 'results' ).show( self.resultsView ); self.layout.getRegion( 'pagination' ).show( self.paginationView ); self.layout.getRegion( 'progress' ).reset(); self.layout.getRegion( 'filters' ).show( new ZevDateFilterView({ model: self.model, results: self.results }) ); } }); }, render: function() { this.layout.getRegion('search').show(new SearchView({ model: this.model }) ); this.layout.getRegion( 'filters' ).show( new ZevDateFilterView({ model: this.model, results: null }) ); }, onRender: function() { this.layout.render(); } }); } );
TotalActiveMedia/erfgeoviewer
app/scripts/plugins/zev/zev.js
JavaScript
mit
5,297
/* * This file is part of the nivo project. * * Copyright 2016-present, Raphaël Benitte. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ResponsiveWrapper } from '@nivo/core' import ChoroplethCanvas from './ChoroplethCanvas' const ResponsiveChoroplethCanvas = props => ( <ResponsiveWrapper> {({ width, height }) => <ChoroplethCanvas width={width} height={height} {...props} />} </ResponsiveWrapper> ) export default ResponsiveChoroplethCanvas
plouc/nivo
packages/geo/src/ResponsiveChoroplethCanvas.js
JavaScript
mit
560
foundtruck.controller('NavMenuController', ['$scope','localStorageService', '$state', '$uibModalInstance', function($scope, localStorageService, $state, $uibModalInstance) { $scope.checkUserSession = function() { var userSession = localStorageService.get('userSession'); if (userSession == 'anon') { $scope.isAnon = true; $scope.name = 'Visitante'; } else { $scope.isAnon = false; var userData = JSON.parse(userSession); $scope.name = userData.name; } }; $scope.logoff = function() { // Clear user session data before redirect localStorageService.remove('userSession'); // Closes the side menu instance $uibModalInstance.close(); $state.go('userLogin'); } $scope.editUserData = function() { $state.go('editUser'); $uibModalInstance.close(); }; }]);
luizbaldi/found-truck
frontend/src/js/controllers/NavMenuController.js
JavaScript
mit
801
(function () { /** * Login Controller using the following services: * @constructor * @param $filter * @param $interval * @param ProjectHoursAdminService */ function ProjectHoursAdminController($filter, $interval, ProjectHoursAdminService) { var self = this; self.projects = []; self.oldProjects = []; self.requestStatus = { status: 0, description: '' }; self.addProjectItem = function () { self.projects.push({ number: 0, name: '', description: '' }) }; self.smartSave = function () { console.log("Timer triggered"); if (!angular.equals(self.projects, self.oldProjects)) { console.log("Save triggered"); var result = ProjectHoursAdminService.save(self.projects); self.oldProjects = angular.copy(self.projects); result.success(function (data) { if (data.status != 0) { console.log(data.debug); self.requestStatus.message = data.error; self.requestStatus.status = data.status; } }); result.error(function (data) { console.log(data.debug); self.requestStatus.message = data.error; self.requestStatus.status = data.status; }) } }; $interval(self.smartSave(), 1000); self.deleteProjectItem = function (project) { for (var i = 0; i < self.projects.length; i++) { if (angular.equals(project, self.projects[i])) { self.projects.splice(i, 1); return; } } }; self.sortProjectItems = function () { var orderBy = $filter('orderBy'); result = orderBy(self.projects, '+number', false); self.projects = angular.copy(result); }; self.cleanWarning = function () { self.requestStatus.status = 0; self.requestStatus.message = ''; }; self.init = function () { console.log("Inititalizing..."); var result = ProjectHoursAdminService.load(); result.success(function (data) { if (data.data != null) self.projects = angular.copy(data.data); else { self.projects = []; console.log(data.debug); self.requestStatus.message = data.error; self.requestStatus.status = data.status; } }); result.error(function (data) { console.log(data.debug); self.requestStatus.message = data.error; self.requestStatus.status = data.status; }); }; self.init(); } angular.module('finance.projectHours') .controller('ProjectHoursAdminController', ['$filter', '$interval', 'ProjectHoursAdminService', ProjectHoursAdminController]); }());
miooim/project_hours
src/admin/web/ph_admin.js
JavaScript
mit
3,255
// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com> // // 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. (function () { 'use strict'; var define = require('amdefine')(module); /** * Array of modules this one depends on. * @type {Array} */ var deps = [ './mongo' ]; define(deps, function(MongoDb) { module.exports = { MongoDb: MongoDb }; }); }());
korczis/lethe.it
lib/persistence/backends/index.js
JavaScript
mit
1,461
/** @name __inline_debug__ */ global.__defineSetter__('__inline_debug__', function (value) { var e = new Error; console.log(value); console.log(e.stack ? e.stack.split("\n").slice(3).join("\n") : 'no stack provided'); }); if (require.main === module) { console.log('called directly'); } else { console.log('required as a module'); } require('core-os'); /** @name MSAServer_Init */ /** @name MSAServer_Init_Success */ /** @name MSAServer_Init_Fail */ Core.registerRequestPoint('MSAServer_Init', {type: 'multi'}); const utils = require("./Utils.js"); var express = require('express'); var busboy = require('connect-busboy'); var cookieParser = require('cookie-parser'); var app = express(); var port = process.env.PORT || 8079; var url = require('url'); app.use(busboy()); app.use(cookieParser()); if (!process.env.PRODUCTION) { app.set('json spaces', 2); } var mongodb = require('mongodb'); var crypto = require('crypto'); var mongoClient = mongodb.MongoClient; var db; var io; fs = require('fs'); var mongoApiFile; var sitesCollection; classes = {}; require('./Auth.js'); require('./Plugin.js'); require('./Snapshots.js'); var glob = require("glob"); glob.sync('plugins/**/*.js', {ignore: ['**/node_modules/**', '**/bower_components/**', '**/_tests/**', __filename ]}) .map(function(file) { if(fs.readFileSync(file).toString().match(/require\(['"]core-os['"]\)/)) { require('../' + file); } }); var mongoHost = process.env.MONGO_URL || 'mongodb://127.0.0.1:27017/mongo-sites'; mongoClient.connect(mongoHost, function (err, dblink) { if (err) { console.log('Unable to connect to the mongoDB server from environment variable MONGO_URL=' + mongoHost + '. Error:', err); setTimeout(function() { process.exit(); }, 5000); } else { console.log('Connected to mongodb'); db = dblink; app.db = dblink; app.db.DBObject = db.db("mongo-sites"); sitesCollection = db.collection('_sites'); var server; FireRequest(new MSAServer_Init({app: app}), function() { console.log('Running on port ' + port); server = app.listen(port); io = app.io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('MgoClient_Subscribe', function(data) { var data = data || {}; socket.join('subscribed:' + data.to || 'all'); }); socket.on('MgoClient_Unsubscribe', function(data) { var data = data || {}; socket.leave('subscribed:' + data.to || 'all'); }); }); }); } }); app.get('/health/', function (req, res) { res.json({health: "ok"}); }); app.get('/+mongoSitesApi.js$', function (req, res) { res.contentType('text/javascript'); var origin = url.parse(req.headers.referer || 'http://localhost').host.replace(/^\d+\./,''); function send(site) { fs.readFile('./msa-jsapi-layer/mongoSitesApi.js', function (err, data) { res.send(data.toString().replace(/\{site\}/g, site).replace(/\{api_url\}/g, '//' + req.headers.host)); }); } if (origin.match(/^(localhost|127.\d+.\d+.\d+)(:\d+)?$/)) { sitesCollection.find({_id: req.query.site}).toArray(function (err, sites) { if (sites.length) { send(req.query.site) } else { res.send('alert("MongoApi: site ' + req.query.site + ' not found");'); } }) } else { sitesCollection.find({names: origin}).toArray(function (err, sites) { if (sites.length) { send(sites[0]._id); } else { res.send('alert("MongoApi error: site not found for domain ' + origin + '")'); } }) } }); app.get('/+mongoSitesApi.angular.js$', function (req, res) { res.contentType('text/javascript'); fs.readFile('./msa-jsapi-layer/mongoSitesApi.angular.js', function (err, data) { res.send(data.toString()); }); }); app.use(express.static(__dirname + '/../')); app.options('/api/:method/:submethod?', function (req, res) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, X-MongoApi-Site '); res.header('Access-Control-Allow-Credentials', 'true'); res.send(); }); app.parser = parser; function parser(data_handle, custom_handle) { return function (req, res) { var data = ''; if (data_handle) { req.setEncoding('utf8'); req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { try { handle(JSON.parse(data)); } catch (e) { res.send([e]); } }); } else { handle(); } function handle(data) { var origin = url.parse(req.headers.referer || 'http://localhost').host.replace(/^\d+\./,''); var isLocalhost = origin.match(/^(localhost|127.\d+.\d+.\d+)(:\d+)?$/); sitesCollection.find(isLocalhost ? {_id: req.headers['x-mongoapi-site']} : {names: origin}).toArray(function (err, sites) { if (!sites.length) { res.status(404); res.send(''); } else { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, X-MongoApi-Site'); res.header('Access-Control-Allow-Credentials', 'true'); try { var site = sites[0]; var auth_data, user; var token = req.query.token || req.cookies[site._id + ':_auth']; if(!token) { if (data_handle) { handleRequest(); } else { custom_handle(req, res, site); } return; } try { auth_data = JSON.parse(utils.decrypt(site.crypto_key, token)); db.collection('site-' + site._id + '-users').find({ _id: auth_data.user, active_sessions: token }).toArray(function (err, users) { if(err) { res.send(['unknown, database error. contact administrator.']); console.error(err, new Error().stack); return } if (!users.length) { auth_data = null } else { user = users[0] } /* Modify User fields before the responce */ FireRequest( Auth_ModifyUserRequest({ user: user }) , function(result) { proceedUser(result.user); } , function() { proceedUser(user); } ); function proceedUser(user) { if(user && (user._id == site.default_admin || user._id == process.env.DEFAULT_ADMIN)) { user.admin = true } if (data_handle) { handleRequest(); } else { custom_handle(req, res, site, user); } } }) } catch (e) { console.error(e, e.stack); if (data_handle) { handleRequest(); } else { custom_handle(req, res, site); } } function handleRequest() { data_handle( site, (function substituteSpecialValues(field, cursor) { switch (true) { case typeof cursor == 'string' && /* field.match(/_id$/) && */ !!String.prototype.match.call(cursor, /^[0-9a-f]{24}$/): return mongodb.ObjectId(cursor); case typeof cursor != 'object' || cursor === null: return cursor; case !!cursor.__function__ : return (new Function('return ' + cursor.__function__))(); case !!cursor._geo_point : return {_geo_point: { lng: parseFloat(cursor._geo_point.lng), lat: parseFloat(cursor._geo_point.lat)} }; default: for (var i in cursor) { if (cursor.hasOwnProperty(i)) { cursor[i] = substituteSpecialValues(i, cursor[i]); } } return cursor } })('', data), function (err, result) { if (isLocalhost || !process.env.PRODUCTION) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify([err, result], null, 4) + "\n"); } else { res.send([err, result]); } }, user, res, req ) } } catch (err) { console.error(err.message ? err.message + "\n" + err.stack : err); res.send([err.message ? 'Server error: ' + err.message : err]); } } }); } } } app.post('/api/_find', parser(function (site, data, cb) { mongodb.Collection.prototype .find .apply(db.collection('site-' + site._id), data).toArray(cb); })); app.post('/api/_findOne', parser(function (site, data, cb) { mongodb.Collection.prototype .findOne .apply(db.collection('site-' + site._id), data).then(function (data) { cb(null, data) }); })); app.post('/api/_aggregate', parser(function (site, data, cb) { mongodb.Collection.prototype .aggregate .call(db.collection('site-' + site._id), data[0], cb); })); app.post('/api/_insert', parser(function (site, data, cb, user) { if (!user) { cb(['Authorization required']); return; } mongodb.Collection.prototype [data[0] instanceof Array ? 'insertMany' : 'insertOne'] .call(db.collection('site-' + site._id), data[0], function(err, res) { io.sockets.in('subscribed:all').emit('Collection_Changed', { collection: 'site-' + site._id }); cb && cb(err, res); }); })); app.post('/api/_update', parser(function (site, data, cb, user) { if (!user) { cb(['Authorization required']); return; } var params = [data[0], data[1]]; if(data[2] && !(data[2] instanceof Function)) { params.push(data[2]); } params.push(function(err, res) { io.sockets.in('subscribed:all').emit('Collection_Changed', { collection: 'site-' + site._id }); cb && cb(err, res); }); mongodb.Collection.prototype .update .apply(db.collection('site-' + site._id), params); })); app.post('/api/_remove', parser(function (site, data, cb, user) { if (!user) { cb(['Authorization required']); return; } mongodb.Collection.prototype .deleteOne .call(db.collection('site-' + site._id), data[0], function(err, res) { io.sockets.in('subscribed:all').emit('Collection_Changed', { collection: 'site-' + site._id }); cb && cb(err, res); }); })); app.post('/api/_mapReduce', parser(function (site, data, cb, user) { data[2] = data[2] || {}; if (data[2].out && !data[2].out.inline) { if (!user) { cb(['Authorization required for write operations']); return; } } data[2].out = {inline: 1}; db.collection('site-' + site._id) .mapReduce(data[0], data[1], data[2], cb); })); app.post('/api/graph_search', parser(function (site, data, cb) { var collection = db.collection('site-' + site._id); var query = data[0]; var source_query = data[0].source || {}; var destination_query = data[0].destination || {}; delete data[0].source; delete data[0].destination; query._type = 'link'; collection.find(query).toArray(function (err, links) { source_query._id = { $in: links.map(function (it) { return it.source_id }) }; collection.find(source_query).toArray(function (err, sources) { var _id2source = {}; sources.map(function (it) { _id2source[it._id] = it }); links = links.filter(function (it) { return _id2source[it.source_id] }); destination_query._id = { $in: links.map(function (it) { return it.destination_id }) }; collection.find(destination_query).toArray(function (err, destinations) { var _id2destination = {}; destinations.map(function (it) { _id2destination[it._id] = it }); links = links.filter(function (it) { return _id2destination[it.destination_id] }); var _id2object = {}; links.map(function (it) { _id2object[it.source_id] = _id2source [it.source_id]; _id2object[it.destination_id] = _id2destination[it.destination_id]; }); cb(null, [links, _id2object]) }); }); }); })); app.get('/', function(req, res) { fs.readFile('./mgosites-admin/index.html', function (err, data) { res.send( data.toString() ); }); }); Core.processNamespace(classes);
extremeprog-com/mongo-sites-api
msa-http-layer/server.js
JavaScript
mit
15,856
import {factory} from 'aurelia-dependency-injection'; export class RepositoryModel { id = -1; name = ''; description = ''; flags = {}; kind = -1; isLoaded = false; children = []; classes = []; properties = []; variables = []; events = []; methods = []; groups = []; constructor(data){ Object.assign(this, data); this.prettyName = prettyName(this.name); } } function prettyName(s) { s = s.replace(/(\-\w)/g, function(m){return m[1].toUpperCase();}); s = s.replace(/([a-z])([A-Z])/g, '$1 $2') return s.charAt(0).toUpperCase() + s.slice(1); } @factory('LocalCache') export class ChildModel { id = -1; kind = -1; kindString = ''; kindName = ''; name = ''; originalName = ''; children = []; classes = []; groups = []; flags = {}; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; this.prettyName = prettyName(this.name); }; } export class GroupModel { id = -1; kind = -1; kindName = ''; title = ''; children = []; constructor(data){ Object.assign(this, data); this.kindName = this.kindName; }; } export class ClassModel { methods = []; groups = []; flags = {}; constructorMethod = {}; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; console.log(this) } } export class MethodModel { signature = {}; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } } export class ConstructorModel { signature = {}; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } } export class InterfaceModel { classes = []; properties = []; variables = []; methods = []; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } } export class PropertyModel { constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } } export class SignatureModel { comment = {}; constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } } export class VariableModel { constructor(data){ Object.assign(this, data); this.kindName = this.kindString; } }
hitesh97/app-documentation
src/models/repository.js
JavaScript
mit
2,217
#!/usr/bin/env node var prebuilt = require("prebuilt"); prebuilt.install(__dirname, "ffi_bindings");
Icenium/node-ffi
build.js
JavaScript
mit
101
'use strict'; var Q = require('q'); function ratelimit(rateInMs) { rateInMs = parseInt(rateInMs); if (rateInMs != rateInMs) // NaN check throw new TypeError('ratelimit needs a single numerical argument'); if (rateInMs < 0) rateInMs = 0; var throttle = function() { var deferred = Q.defer(); throttle.queue.push(deferred); return throttle.check().then(function() { return deferred.promise; }); }; throttle.currentlyActiveCheck = null; throttle.lastExecutionTime = 0; throttle.queue = []; throttle.resolveUniform = function(fnName, v) { throttle.queue.forEach(function(deferred) { return deferred[fnName](v); }); throttle.queue = []; }; throttle.resolveAll = function(v) { return throttle.resolveUniform('resolve', v); }; throttle.rejectAll = function(v) { return throttle.resolveUniform('reject', v); }; throttle.check = function() { if (throttle.currentlyActiveCheck || throttle.queue.length == 0) return throttle.currentlyActiveCheck; var waitingTime = rateInMs - (Date.now() - throttle.lastExecutionTime); return throttle.currentlyActiveCheck = (waitingTime > 0 ? Q.delay(waitingTime) : Q()).then(function() { var now = Date.now(); if (now - throttle.lastExecutionTime >= rateInMs) { throttle.lastExecutionTime = now; throttle.queue.shift().resolve(); } throttle.currentlyActiveCheck = null; throttle.check(); }); }; return throttle; } module.exports = ratelimit;
addaleax/q-ratelimit
index.js
JavaScript
mit
1,482
import Categories from 'forum/collections/categories'; import Threads from 'forum/collections/threads'; import moment from 'moment'; Meteor.methods({ 'fixtures/removeAllUsers': function() { return Meteor.users.remove({}); }, 'fixtures/removeAllCategories': function() { return Categories.remove({}); }, 'fixtures/removeAllThreads': function() { return Threads.remove({}); }, 'fixtures/create_user': function(username) { if (Meteor.users.find({username:username}).count() === 0) { Accounts.createUser({username: username, password: '12345'}); } }, 'fixtures/remove_user': function(username) { const user = Meteor.users.findOne({username: username}); if (user) { return Meteor.users.remove({_id: user._id}); } else { return 1; } }, 'fixtures/create_categories': function() { if (Categories.find().count() === 0) { var categories = [ {name: "General"}, {name: "Places"}, {name: "Jobs"}, {name: "Home"}, {name: "Hangouts"} ]; _.each(categories, function (category) { Categories.insert({ name: category.name }); }); } }, 'fixtures/create_thread': function() { if (Meteor.users.find({username: 'MockUser'}).count() === 0) { Accounts.createUser({username: 'MockUser', password: '12345'}); } if (Categories.find().count() === 0) { var categories = [ {name: "General"}, {name: "Places"}, {name: "Jobs"}, {name: "Home"}, {name: "Hangouts"} ]; _.each(categories, function (category) { Categories.insert({ name: category.name }); }); }; const user = Meteor.users.findOne({username: 'MockUser'}); const category = Categories.findOne({name: "General"}); var params = { category: category._id, user: user, comments: [ { _id: '123', userId: '1', username: 'TestUser', avatar: undefined, text: 'Hello', createdAt: moment.utc().format(), likes: 0, likeIds: [], replies: [ { _id: '321', userId: '1', username: 'TestUser', avatar: undefined, text: 'Yo', createdAt: moment.utc().format(), like: 0, likeIds: [] } ] } ], createdAt: moment.utc().format(), updatedAt: moment.utc().format(), title: 'Mock', description: 'Mock text', tags: ['hi', 'there'], }; return Threads.insert(params); }, 'fixtures/delete_thread': function() { const thread = Threads.findOne({title: 'Mock'}); if (thread) { return Threads.remove({_id: thread._id}); } else { return 1; } } })
DitchCrab/ReactiveForum
modules/forum/server/__tests__/integration/forum-fixtures.js
JavaScript
mit
2,905
"use strict"; var express = require("express"); var path = require("path"); var bodyParser = require("body-parser"); var cookieParser = require("cookie-parser"); var session = require("express-session"); var RedisStore = require("connect-redis")(session); var Logger = require("./inc/Logger"); var app = express(); app.set("views", path.join(__dirname, "views")); app.set("view engine", "jade"); app.use((req, res, next) => { Logger.http(`${req.method} ${req.url}`); next(); }); app.use(express.static("public")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(session({ secret: "secret", resave: false, store: new RedisStore({ client: require("./redis/client"), prefix: "Session." }), saveUninitialized: false })); app.use("/", require("./routes/passport")); app.use("/api/", require("./routes/models")); app.get("/*", (req, res) => { if (req.xhr) { res.status(404).end(); } else { res.render("index"); } }); app.use((err, req, res, next) => { // FIXME manage JSON response Logger.error(err); if (req.xhr) { res.status(500).send({ error: "Something blew up!" }); } else { res.status(500).render("error", { error: err }); } }); var server = app.listen(3000, () => { var host = server.address().address; var port = server.address().port; Logger.info("Listening at http://%s:%s", host, port); });
florentsolt/briefcase
app.js
JavaScript
mit
1,491
/* global define */ define([ 'backbone', 'buses/event-bus', 'models/settings-model', 'behaviors/navigation-behavior', 'templates/header-template' ], function (Backbone, EventBus, Settings) { 'use strict'; var HeaderView = Backbone.Marionette.LayoutView.extend({ template: 'header-template.dust', ui: { navigationLink: 'a.navbar-brand' }, behaviors: { Navigation: {} }, regions: { search: '#search-region', menu: '#menu-region' }, serializeData: function () { return { name: Settings.get('name'), site_url: Settings.get('site_url') }; } }); return HeaderView; });
B3ST/B3
app/scripts/views/header-view.js
JavaScript
mit
682
if ($("#running_times").length > 0) { // ---------------------------------------INCOMING ATTACK (function() { //console.time("info_command-incoming"); try { var link = $("#contentContainer tr:eq(10) a:last"); //<!--@@INCLUDE "page/info_command/incoming.js" INDENT=1 //--> // AUTO OPEN TAGGER if (user_data.incoming.forceOpenTagger || (user_data.incoming.autoOpenTagger && $("#labelText").text() == trans.tw.incoming.defaultCommandName)) { link.click(); } if (user_data.proStyle && user_data.incoming.villageBoxSize != null && user_data.incoming.villageBoxSize != false) { $("table:first", content_value).css("width", user_data.incoming.villageBoxSize); } } catch (e) { handleException(e, "info_command-incoming"); } //console.timeEnd("info_command-incoming"); }()); } else { (function() { //console.time("info_command-command"); try { // Own attack/support/return ---------------------------------------------------------------------------------- Own attack/support/return var infoTable = $("table.vis:first", content_value); var type = $("h2:first", content_value).text(); var catapultTargetActive = infoTable.find("tr:eq(5) td:eq(0)").text() == trans.tw.command.catapultTarget; infoTable.width(600); // Add troop returntime and annulation return time var isSupport = type.indexOf(trans.tw.command.support) == 0; var offset = 5; if (catapultTargetActive) { offset += 1; } var arrivalCell = infoTable.find("tr:eq(" + (offset + 1) + ") td:last"); if (type.indexOf(trans.tw.command.returnText) == -1 && type.indexOf(trans.tw.command.abortedOperation) == -1) { var duration = getTimeFromTW(infoTable.find("tr:eq(" + offset + ") td:last").text()); var imgType = !isSupport ? "attack" : "support"; arrivalCell.prepend("<img src='graphic/command/" + imgType + ".png' title='" + trans.sp.command.arrival + "'>&nbsp; " + trans.tw.all.dateOn + " ").css("font-weight", "bold"); var stillToRun = getTimeFromTW(infoTable.find("tr:eq(" + (offset + 2) + ") td:last").text()); var cancelCell = infoTable.find("tr:last").prev(); var canStillCancel = cancelCell.has("a").length; if (canStillCancel) { cancelCell.find("td:first").attr("colspan", "1").attr("nowrap", "nowrap"); var returnTime = getDateFromTW($("#serverTime").text(), true); returnTime = new Date(returnTime.valueOf() + (duration.totalSecs - stillToRun.totalSecs) * 1000); cancelCell.append("<td>" + trans.sp.command.returnOn + "</td><td id=returnTimer>" + twDateFormat(returnTime, true, true).substr(3) + "</td>"); setInterval(function timeCounter() { var timer = $("#returnTimer"); var newTime = new Date(getDateFromTW(timer.text()).valueOf() + 2000); timer.text(twDateFormat(newTime, true, true).substr(3)); }, 1000); cancelCell = cancelCell.prev(); } if (type.indexOf(trans.tw.command.attack) == 0) { var returnTimeCell = cancelCell.find("td:last"); returnTimeCell.html("<img src='graphic/command/return.png' title='" + cancelCell.find("td:first").text() + "'>&nbsp; <b>" + returnTimeCell.text() + "</b>"); } } else { var imgType = type.indexOf(trans.tw.command.abortedOperation) == 0 ? imgType = "cancel" : "return"; arrivalCell.prepend("<img src='graphic/command/" + imgType + ".png' title='" + trans.sp.command.arrival + "'>&nbsp; " + trans.tw.all.dateOn + " ").css("font-weight", "bold"); } var player = infoTable.find("td:eq(7) a").text(); var village = getVillageFromCoords(infoTable.find("td:eq(9) a").text()); var second = infoTable.find("td:eq(" + (13 + (catapultTargetActive ? 2 : 0)) + ")").text(); var haulDescription = ""; if (type.indexOf(trans.tw.command.returnText) == 0) { infoTable = $("> table.vis:last", content_value); if (infoTable.find("td:first").text() == trans.tw.command.haul) { haulDescription = infoTable.find("td:last").text().match(/\s(\d+)\/(\d+)$/); if (haulDescription) { haulDescription = formatNumber(haulDescription[1]) + " / " + formatNumber(haulDescription[2]); } else { assert(infoTable.find("td:last").text() + " didn't match regexp for tw.command.haul"); } infoTable = infoTable.prev(); } infoTable = infoTable.find("tr:last"); } else { infoTable = $("> table.vis:last", content_value); } var unitsSent = {}; $.each(world_data.units, function (i, val) { unitsSent[val] = parseInt($("td:eq(" + i + ")", infoTable).text(), 10); }); var unitsCalc = calcTroops(unitsSent); unitsCalc.colorIfNotRightAttackType($("h2:first", content_value), !isSupport); if (user_data.attackAutoRename.active) { $.each($('.quickedit'), function(){ var renamed = buildAttackString(village.coord, unitsSent, player, isSupport, 0, haulDescription), commandID = $(this).attr('data-id'); if (server_settings.ajaxAllowed) { executeRename(commandID, renamed); } }); } /*if (server_settings.ajaxAllowed) { ajax("overview", function(overviewtext) { var idnumberlist = []; var index = 0; var links = $(overviewtext).find("#show_outgoing_units").find("table").find("td:first-child").find("a:first-child").find("span"); //^enkel 'find codes, dus alles wegselecteren wat onnodig is. links.each(function(){ var idgetal = $(this).attr('id').match(/\d+/); idnumberlist[index]=idgetal[0]; index++; $.trim(idnumberlist[index]); }); idthisattack= location.href.match(/id=(\d+)/);// deze aanval ophalen var idthisattacktrim = $.trim(idthisattack[1]); //eerste callback: Datgeen tussen haakjes dus. En gelijk maar trimmen, voor het geval dat. var counter=$.inArray(idthisattacktrim, idnumberlist); var arraylength = idnumberlist.length; var arraylengthminusone = arraylength -1; if (counter != arraylengthminusone) { var nextcommandID = idnumberlist[(counter +1)];} if (counter != 0) { var lastcommandID = idnumberlist[(counter - 1)]; } villageid = location.href.match(/village=(\d+)/); //alert(villageid[1]); if (counter != 0) { content_value.find("h2").after('<table><tr><td id="lastattack" style="width:83%"><a href="/game.php?village=' + villageid + '&id=' + lastcommandID + '&type=own&screen=info_command">'+ trans.sp.command.precedingAttack + '</a></td> </tr> </table>'); } else { content_value.find("h2").after('<table><tr><td id="lastattack" style="width:83%"><b> XX</b></td> </tr> </table>'); } if (counter != arraylengthminusone){ $("#lastattack").after('<td id="nextcommand" ><a href="/game.php?village=' + villageid + '&id=' + nextcommandID + '&type=own&screen=info_command">'+ trans.sp.command.nextAttack+ '</a></td>'); } else { $("#lastattack").after('<td id="nextcommand"><b>XX</b></td>'); } //alert("Hoi"); }, {}); }*/ // When sending os, calculate how much population in total is sent if (isSupport) { var totalPop = 0; $.each(world_data.units, function (i, val) { var amount = unitsSent[val]; if (amount != 0) { totalPop += amount * world_data.unitsPositionSize[i]; } }); var unitTable = $("table.vis:last", content_value); unitTable.find("tr:first").append('<th width="50"><span class="icon header population" title="' + trans.sp.all.population + '"></span></th>'); unitTable.find("tr:last").append('<td>' + formatNumber(totalPop) + '</td>'); } } catch (e) { handleException(e, "info_command-command"); } //console.timeEnd("info_command-command"); }()); }
SanguPackage/Script
page/info_command/info_command.js
JavaScript
mit
9,158
module.exports = require("npm:yamljs@0.2.8/lib/Yaml.js");
Imms/imms.github.io
jspm_packages/npm/yamljs@0.2.8.js
JavaScript
mit
57
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, settled } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import moment from 'moment'; module('Integration | Component | recently updated display', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { const lastModified = moment().subtract(5, 'day'); this.set('lastModified', lastModified); await render(hbs`<RecentlyUpdatedDisplay @lastModified={{lastModified}} />`); return settled().then(()=>{ assert.dom('.fa-exclamation-circle').exists({ count: 1 }, 'it renders'); }); }); test('it does not render', async function(assert) { const lastModified = moment().subtract(9, 'day'); this.set('lastModified', lastModified); await render(hbs`<RecentlyUpdatedDisplay />`); return settled().then(()=>{ assert.dom('.fa-exclamation-circle').doesNotExist('it does not renders'); }); }); });
dartajax/frontend
tests/integration/components/recently-updated-display-test.js
JavaScript
mit
1,017
'use strict'; let path = require('path'); let defaultSettings = require('./defaults'); // Additional npm or bower modules to include in builds // Add all foreign plugins you may need into this array // @example: // let npmBase = path.join(__dirname, '../node_modules'); // let additionalPaths = [ path.join(npmBase, 'react-bootstrap') ]; let additionalPaths = []; module.exports = { additionalPaths: additionalPaths, port: defaultSettings.port, debug: true, devtool: 'eval', output: { path: path.join(__dirname, '/../dist/assets'), filename: 'app.js', publicPath: defaultSettings.publicPath }, devServer: { contentBase: './src/', historyApiFallback: true, hot: true, port: defaultSettings.port, publicPath: defaultSettings.publicPath, noInfo: false }, resolve: { extensions: ['', '.js', '.jsx'], alias: { actions: `${defaultSettings.srcPath}/actions/`, components: `${defaultSettings.srcPath}/components/`, sources: `${defaultSettings.srcPath}/sources/`, stores: `${defaultSettings.srcPath}/stores/`, styles: `${defaultSettings.srcPath}/styles/`, config: `${defaultSettings.srcPath}/config/` + process.env.REACT_WEBPACK_ENV // 'react/lib/ReactMount': 'react-dom/lib/ReactMount' } }, module: {} };
Bbottle/react-gallery
cfg/base.js
JavaScript
mit
1,311
// Compiled by ClojureScript 1.9.473 {} goog.provide('tiltontec.model.macros'); goog.require('cljs.core'); goog.require('tiltontec.cell.base'); tiltontec.model.macros.pme = (function tiltontec$model$macros$pme(var_args){ var args__8233__auto__ = []; var len__8226__auto___16722 = arguments.length; var i__8227__auto___16723 = (0); while(true){ if((i__8227__auto___16723 < len__8226__auto___16722)){ args__8233__auto__.push((arguments[i__8227__auto___16723])); var G__16724 = (i__8227__auto___16723 + (1)); i__8227__auto___16723 = G__16724; continue; } else { } break; } var argseq__8234__auto__ = ((((2) < args__8233__auto__.length))?(new cljs.core.IndexedSeq(args__8233__auto__.slice((2)),(0),null)):null); return tiltontec.model.macros.pme.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),argseq__8234__auto__); }); tiltontec.model.macros.pme.cljs$core$IFn$_invoke$arity$variadic = (function (_AMPERSAND_form,_AMPERSAND_env,mas){ return cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("cljs.core","when","cljs.core/when",120293186,null)),cljs.core._conj.call(null,cljs.core.List.EMPTY,true),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("cljs.core","println","cljs.core/println",-331834442,null)),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("tiltontec.cell.base","ia-type","tiltontec.cell.base/ia-type",699012589,null)),cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol(null,"me","me",1501524834,null))))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })(),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Keyword(null,"tag","tag",-1290361223)),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("cljs.core","deref","cljs.core/deref",1901963335,null)),cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol(null,"me","me",1501524834,null))))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })()))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })(),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Keyword(null,"name","name",1843675177)),(function (){var x__7955__auto__ = cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("cljs.core","deref","cljs.core/deref",1901963335,null)),cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol(null,"me","me",1501524834,null))))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })()))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })(),mas))); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7955__auto__); })()))); }); tiltontec.model.macros.pme.cljs$lang$maxFixedArity = (2); tiltontec.model.macros.pme.cljs$lang$applyTo = (function (seq16719){ var G__16720 = cljs.core.first.call(null,seq16719); var seq16719__$1 = cljs.core.next.call(null,seq16719); var G__16721 = cljs.core.first.call(null,seq16719__$1); var seq16719__$2 = cljs.core.next.call(null,seq16719__$1); return tiltontec.model.macros.pme.cljs$core$IFn$_invoke$arity$variadic(G__16720,G__16721,seq16719__$2); }); tiltontec.model.macros.pme.cljs$lang$macro = true; //# sourceMappingURL=macros.js.map
kennytilton/MatrixJS
cljs/archive/todomvc/target/js/main.out/tiltontec/model/macros.js
JavaScript
mit
3,980
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as themes from 'redux-devtools-themes'; import { clearNotification } from '../actions'; class Notification extends Component { static propTypes = { notification: PropTypes.shape({ message: PropTypes.string, type: PropTypes.string }), clearNotification: PropTypes.func.isRequired }; shouldComponentUpdate(nextProps) { return nextProps.notification !== this.props.notification; } render() { if (!this.props.notification) return null; const theme = themes.nicinabox; const buttonStyle = { color: theme.base06, backgroundColor: theme.base00, margin: '0', background: '#DC2424' }; const containerStyle = { color: theme.base06, background: '#FC2424', padding: '5px 10px', minHeight: '20px', display: 'flex' }; return ( <div style={containerStyle}> <div style={{ flex: '1', alignItems: 'center' }}> <p style={{ margin: '0px' }}>{this.props.notification.message}</p> </div> <div style={{ alignItems: 'center' }}> <button onClick={this.props.clearNotification} style={buttonStyle} >&times;</button> </div> </div> ); } } function mapStateToProps(state) { return { notification: state.notification }; } function mapDispatchToProps(dispatch) { return { clearNotification: bindActionCreators(clearNotification, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(Notification);
zalmoxisus/remotedev-app
src/app/components/Notification.js
JavaScript
mit
1,649
/** * @author Oystein Schroder Elvik */ angular.module( 'crm.dashboard', [ 'ui.state' ]) .config(function config( $stateProvider ) { $stateProvider.state( 'dashboard', { url: '/dashboard', views: { "main": { controller: 'DashboardCtrl', templateUrl: 'dashboard/dashboard.tpl.html' } }, data:{ pageTitle: 'Dashboard' } }); }) .controller( 'DashboardCtrl', function DashboardController( $scope ) { }) ;
oeelvik/CRM
src/app/dashboard/dashboard.js
JavaScript
mit
457
const path = require("path"); const BundleEnsureWebpackPlugin = require("../../"); module.exports = { entry: path.resolve(__dirname, "./index.js"), output: { filename: "[name].bundle.js", path: path.resolve(__dirname, "./dist") }, mode: "production", plugins: [ new BundleEnsureWebpackPlugin({ retryTemplate: ";", polyfill: ";(function(){ window.test_output('polyfill excuted!'); })();", minify: false, emitStartup: true }) ] };
mc-zone/bundle-ensure-webpack-plugin
tests/insertPolyfill/webpack.config.js
JavaScript
mit
482
(function(){Registry.require("helper");Registry.require("xmlhttprequest"); var c={};var i=null;var d=Registry.get("helper");var e=function(o){var m=o; var l=Array.prototype.slice.call(arguments,1);if(l.length==1&&d.toType(l[0])==="Array"){l=l[0] }var p=new RegExp("_0[a-zA-Z].*0");for(var n=0;n<l.length; l++){if(m.search(p)==-1){console.log("getMessage(): wrong argument count!!!"); break}m=m.replace(p," "+l[n])}return m.replace(/_/g," ") };var g=function(t,p){var l=t.message;var q=false;if(p.length==1&&d.toType(p[0])==="Array"){p=p[0]; q=true}for(var n in t.placeholders){try{var u=Number(t.placeholders[n].content.replace(/^\$/,""))-1; var s;if(u<p.length){s=q?p:p[u];l=l.replace("$"+n+"$",s) }else{console.log("i18n: invalid argument count on processing '"+l+"' with args "+JSON.stringify(p)) }}catch(r){console.log("i18n: error processing '"+l+"' with args "+JSON.stringify(p)) }}return l};var j=function(l){var m=chrome.i18n.getMessage.apply(this,arguments); if(m){return m}else{return e.apply(this,arguments)}}; var h=function(l){return a.apply(this,arguments)};var a=function(l){if(!i){return j.apply(this,arguments) }else{var m=c[l];if(m){return g(m,Array.prototype.slice.call(arguments,1)) }else{return e.apply(this,arguments)}}};var b=function(){return i };var f=function(m){if(m==="null"){m=null}if(i==m){return true }if(m){var l="_locales/"+m+"/messages.json";var o=Registry.getRaw(l); if(o){try{c=JSON.parse(o);i=m;return true}catch(n){console.log("i18n: parsing locale "+m+" failed!") }}else{console.log("i18n: retrieving locale "+m+" failed!") }return false}else{c={};i=null;return true}};var k=function(l){var m=function(n){if(l){l(n.i18n) }};chrome.extension.sendMessage({method:"getLocale"},m) };Registry.register("i18n",{getMessage:h,getOriginalMessage:j,askForLocale:k,getLocale:b,setLocale:f}) })();
gingerbeardman/Piyo
Piyo.app/Contents/Profile/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/3.1.3440_0/i18n.js
JavaScript
mit
1,825
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: './public/index.html', filename: 'index.html', inject: 'body' }); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const extractSass = new ExtractTextPlugin({ filename: 'styles.css', disable: false }); module.exports = { entry: './public/main.js', output: { path: path.resolve('dist'), filename: 'main_bundle.js' }, module: { rules: [ {test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/}, {test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/}, { test: /\.scss$/, use: extractSass.extract({ use: [{ loader: "css-loader" }, { loader: "sass-loader" }], // use style-loader in development fallback: "style-loader" }) } ] }, devServer: { contentBase: path.join(__dirname, 'dist'), historyApiFallback: true } , plugins: [ HtmlWebpackPluginConfig, extractSass ] };
seanzx85/gym-utilities
webpack.config.js
JavaScript
mit
1,323
module.exports = { "ahj": { "rules": { "permitOfficeRequirements": { "name": "Permit Office Requirements", "statements": [ { "value": "DWG Properties: Change \"CANTILEVER\" to \"12\" instead of \"L/3\" DWG Properties: Change \"MaxSpacing\" to be \"48\"", "onConflict": "union", "source": { "id": "29691c3d-df4f-49e6-9b42-c3b933a293f4", "name": "Prince George's County", "type": "County" } }, { "value": "Default to attic runs, unless not possible. Be sure that the attic runs are shown on the site plan and the 1-line. (Custom 1-line needed if 2017 NEC)", "onConflict": "union", "source": { "id": "94348f35-8978-4e0f-8fa0-63a2a2c432b8", "name": "MD-01 DC North Solar", "type": "ROC" } }, { "value": "Site Plan: Check O-page for HOA, If HOA is Tide Water add the property line. Conduit attic runs on special request only. Requires an EE support.", "onConflict": "union", "source": { "id": "718a6340-a7b0-408e-a5a9-12b946a7f84b", "name": "Maryland", "type": "State" } } ], "id": "permitOfficeRequirements", "source": { "id": "29691c3d-df4f-49e6-9b42-c3b933a293f4", "name": "Prince George's County", "type": "County" }, "timeStamp": "2019-05-20T18:36:18.031Z" } } }, "definitions": { "rules": { "permitOfficeRequirements":{ "allowableConditions": "none", "description": "Permit Office Requirements", "id": "permitOfficeRequirements", "name": "Permit Office Requirements", "rule": true, "tags": [ "design", "permitDesignRuleGroup", "permitDesignView", "proposalView", "electricalView", "structuralView", "surveyor", "permitRole" ], "template": { "dataType": "string", "onConflict": "union" } } }, "conditions": {} } };
kennethchatfield/rule-evaluator
test/AppliedRule/union/associationObject.js
JavaScript
mit
2,894
import crel from "crel"; import { isUndefined } from "lodash"; export default function LogItem({ message, filePath, fileName, lineNumber, amount, type = "log" } = {}) { // figure out type if (type === "error") type = "error"; else if (typeof message === "string") type = "string"; else if (typeof message === "number") type = "number"; else if (typeof message === "boolean") type = "boolean"; else if (typeof message === "object") type = "object"; else if (Array.isArray(message)) type = "array"; else if (message === null) type = "null"; else if (typeof message === "undefined") type = "undefined"; // prepare message if (type === "null" || type === "undefined") message = type; else if (type === "object" || type === "array") message = JSON.stringify(message, undefined, 2); else if (type === "number" || type === "boolean") message = message.toString(); // line location const lineLoc = fileName + ":" + lineNumber; // prepare amount amount = isUndefined(amount) ? 1 : amount; // Prepare LogItem parts const LogAmount = crel("div", { class: "mde-log-amount" }, amount === 1 ? "" : amount); const LogMessage = crel("div", { class: "mde-log-message" }, message); const LogTrace = crel("a", { class: "mde-log-trace", href: filePath, target: "_blank" }, lineLoc); const LogMessageFull = crel("pre", { class: "mde-log-message-full" }, message); // Build LogItem let LogItem = crel( "div", { class: "mde-log", "data-type": type }, LogAmount, LogMessage, LogTrace, LogMessageFull ); // Listen for toggling full message LogMessage.addEventListener("click", () => LogItem.classList.toggle("mde-log-open")); return LogItem; }
prjctnxt/MobileDevEnvironment
src/features/tray/log-item.js
JavaScript
mit
1,719
/*!-------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ define("vs/workbench/parts/debug/node/telemetryApp.nls.it", { "vs/base/common/errors": [ "{0}. Codice errore: {1}", "Autorizzazione negata (HTTP {0})", "Autorizzazione negata", "{0} (HTTP {1}: {2})", "{0} (HTTP {1})", "Errore di connessione sconosciuto ({0})", "Si è verificato un errore di connessione sconosciuto. La connessione a Internet è stata interrotta oppure il server al quale si è connessi è offline.", "{0}: {1}", "Si è verificato un errore sconosciuto. Per altri dettagli, vedere il log.", "Si è verificato un errore di sistema ({0})", "Si è verificato un errore sconosciuto. Per altri dettagli, vedere il log.", "{0} ({1} errori in totale)", "Si è verificato un errore sconosciuto. Per altri dettagli, vedere il log.", "Non implementato", "Argomento non valido: {0}", "Argomento non valido", "Stato non valido: {0}", "Stato non valido", "Non è stato possibile caricare un file obbligatorio. Non si è più connessi a Internet oppure il server a cui si è connessi è offline. Per riprovare, aggiornare il browser.", "Non è stato possibile caricare un file obbligatorio. Riavviare l\'applicazione e riprovare. Dettagli: {0}", ] });
KTXSoftware/KodeStudio-linux32
resources/app/out/vs/workbench/parts/debug/node/telemetryApp.nls.it.js
JavaScript
mit
1,378
version https://git-lfs.github.com/spec/v1 oid sha256:6fba55d2d2ab6272aca104bc578763c436ce0b81c09960840872996653fb0fcc size 1696
yogeshsaroya/new-cdnjs
ajax/libs/angular-strap/2.1.5/modules/popover.min.js
JavaScript
mit
129
import React from "react" import Layout from "../components/layout" const projectsLayout = () => ( <Layout title="Projects"> Here you'll see a list of projects I helped to develop. </Layout> ); export default projectsLayout;
Austinate/austinate.github.io
src/pages/projects.js
JavaScript
mit
234
// flow-typed signature: ce9e1a70186cc36ed652df0d283a8c6d // flow-typed version: <<STUB>>/react-progressive-bg-image_v3.0.0/flow_v0.67.1 /** * This is an autogenerated libdef stub for: * * 'react-progressive-bg-image' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'react-progressive-bg-image' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'react-progressive-bg-image/lib/Img' { declare module.exports: any; } declare module 'react-progressive-bg-image/lib/index' { declare module.exports: any; } declare module 'react-progressive-bg-image/lib/loadImage' { declare module.exports: any; } declare module 'react-progressive-bg-image/lib/ProgressiveImage' { declare module.exports: any; } // Filename aliases declare module 'react-progressive-bg-image/lib/Img.js' { declare module.exports: $Exports<'react-progressive-bg-image/lib/Img'>; } declare module 'react-progressive-bg-image/lib/index.js' { declare module.exports: $Exports<'react-progressive-bg-image/lib/index'>; } declare module 'react-progressive-bg-image/lib/loadImage.js' { declare module.exports: $Exports<'react-progressive-bg-image/lib/loadImage'>; } declare module 'react-progressive-bg-image/lib/ProgressiveImage.js' { declare module.exports: $Exports< 'react-progressive-bg-image/lib/ProgressiveImage', >; }
MCS-Lite/mcs-lite
flow-typed/npm/react-progressive-bg-image_vx.x.x.js
JavaScript
mit
1,669
'use strict'; module.exports = function(karma) { karma.set({ frameworks: [ 'jasmine' ], files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/simplewebrtc/simplewebrtc.bundle.js', 'tests/simplewebrtcMock.js', 'src/**/*.js', 'tests/**/*Spec.js' ], reporters: [ 'dots' ], browsers: [ 'Chrome' ], logLevel: 'LOG_DEBUG', singleRun: false, autoWatch: true, }); };
mdamt/angular-simple-webrtc
karma.conf.js
JavaScript
mit
490
import CounterRoute from 'routes/Counter'; describe('(Route) Counter', () => { let _route; beforeEach(() => { _route = CounterRoute({}); }); it('Should return a route configuration object', () => { expect(typeof (_route)).to.equal('object'); }); it('Configuration should contain path `counter`', () => { expect(_route.path).to.equal('counter'); }); });
rebiz/requests
frontend/tests/routes/Counter/index.spec.js
JavaScript
mit
383
import _sanitizeXss from 'xss'; const ASIS = 'asis'; const sanitizeXss = (input, options) => { const defaultAllowedIframeSrc = /^(https:){0,1}\/\/.*?(youtube|vimeo|dailymotion|youku)/i; const allowedIframeSrcRegex = (function() { let reg = defaultAllowedIframeSrc; const SAFE_IFRAME_SRC_PATTERN = Meteor.settings.public.SAFE_IFRAME_SRC_PATTERN; try { if (SAFE_IFRAME_SRC_PATTERN !== undefined) { reg = new RegExp(SAFE_IFRAME_SRC_PATTERN, 'i'); } } catch (e) { /*eslint no-console: ["error", { allow: ["warn", "error"] }] */ console.error('Wrong pattern specified', SAFE_IFRAM_SRC_PATTERN, e); } return reg; })(); const targetWindow = '_blank'; const getHtmlDOM = html => { const i = document.createElement('i'); i.innerHTML = html; return i.firstChild; }; options = { onTag(tag, html, options) { const htmlDOM = getHtmlDOM(html); const getAttr = attr => { return htmlDOM && attr && htmlDOM.getAttribute(attr); }; if (tag === 'iframe') { const clipCls = 'note-vide-clip'; if (!options.isClosing) { const iframeCls = getAttr('class'); let safe = iframeCls.indexOf(clipCls) > -1; const src = getAttr('src'); if (allowedIframeSrcRegex.exec(src)) { safe = true; } if (safe) return `<iframe src='${src}' class="${clipCls}" width=100% height=auto allowfullscreen></iframe>`; } else { // remove </iframe> tag return ''; } } else if (tag === 'a') { if (!options.isClosing) { if (getAttr(ASIS) === 'true') { // if has a ASIS attribute, don't do anything, it's a member id return html; } else { const href = getAttr('href'); if (href.match(/^((http(s){0,1}:){0,1}\/\/|\/)/)) { // a valid url return `<a href=${href} target=${targetWindow}>`; } } } } else if (tag === 'img') { if (!options.isClosing) { const src = getAttr('src'); if (src) { return `<a href='${src}' class='swipebox'><img src='${src}' class="attachment-image-preview mCS_img_loaded"></a>`; } } } return undefined; }, onTagAttr(tag, name, value) { if (tag === 'img' && name === 'src') { if (value && value.substr(0, 5) === 'data:') { // allow image with dataURI src return `${name}='${value}'`; } } else if (tag === 'a' && name === 'target') { return `${name}='${targetWindow}'`; // always change a href target to a new window } return undefined; }, ...options, }; return _sanitizeXss(input, options); }; Template.editor.onRendered(() => { const textareaSelector = 'textarea'; const mentions = [ // User mentions { match: /\B@([\w.]*)$/, search(term, callback) { const currentBoard = Boards.findOne(Session.get('currentBoard')); callback( currentBoard .activeMembers() .map(member => { const username = Users.findOne(member.userId).username; return username.includes(term) ? username : null; }) .filter(Boolean), ); }, template(value) { return value; }, replace(username) { return `@${username} `; }, index: 1, }, ]; const enableTextarea = function() { const $textarea = this.$(textareaSelector); autosize($textarea); $textarea.escapeableTextComplete(mentions); }; if (Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false) { const isSmall = Utils.isMiniScreen(); const toolbar = isSmall ? [ ['view', ['fullscreen']], ['table', ['table']], ['font', ['bold', 'underline']], //['fontsize', ['fontsize']], ['color', ['color']], ] : [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontsize', ['fontsize']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], // iframe tag will be sanitized TODO if iframe[class=note-video-clip] can be added into safe list, insert video can be enabled //['insert', ['link', 'picture']], // modal popup has issue somehow :( ['view', ['fullscreen', 'help']], ]; const cleanPastedHTML = sanitizeXss; const editor = '.editor'; const selectors = [ `.js-new-comment-form ${editor}`, `.js-edit-comment ${editor}`, ].join(','); // only new comment and edit comment const inputs = $(selectors); if (inputs.length === 0) { // only enable richereditor to new comment or edit comment no others enableTextarea(); } else { const placeholder = inputs.attr('placeholder') || ''; const mSummernotes = []; const getSummernote = function(input) { const idx = inputs.index(input); if (idx > -1) { return mSummernotes[idx]; } return undefined; }; inputs.each(function(idx, input) { mSummernotes[idx] = $(input).summernote({ placeholder, callbacks: { onInit(object) { const originalInput = this; $(originalInput).on('submitted', function() { // resetCommentInput has been called if (!this.value) { const sn = getSummernote(this); sn && sn.summernote('reset'); object && object.editingArea.find('.note-placeholder').show(); } }); const jEditor = object && object.editable; const toolbar = object && object.toolbar; if (jEditor !== undefined) { jEditor.escapeableTextComplete(mentions); } if (toolbar !== undefined) { const fBtn = toolbar.find('.btn-fullscreen'); fBtn.on('click', function() { const $this = $(this), isActive = $this.hasClass('active'); $('.minicards,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually }); } }, onImageUpload(files) { const $summernote = getSummernote(this); if (files && files.length > 0) { const image = files[0]; const currentCard = Cards.findOne(Session.get('currentCard')); const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL; const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO; const insertImage = src => { const img = document.createElement('img'); img.src = src; img.setAttribute('width', '100%'); $summernote.summernote('insertNode', img); }; const processData = function(fileObj) { Utils.processUploadedAttachment( currentCard, fileObj, attachment => { if ( attachment && attachment._id && attachment.isImage() ) { attachment.one('uploaded', function() { const maxTry = 3; const checkItvl = 500; let retry = 0; const checkUrl = function() { // even though uploaded event fired, attachment.url() is still null somehow //TODO const url = attachment.url(); if (url) { insertImage( `${location.protocol}//${location.host}${url}`, ); } else { retry++; if (retry < maxTry) { setTimeout(checkUrl, checkItvl); } } }; checkUrl(); }); } }, ); }; if (MAX_IMAGE_PIXEL) { const reader = new FileReader(); reader.onload = function(e) { const dataurl = e && e.target && e.target.result; if (dataurl !== undefined) { // need to shrink image Utils.shrinkImage({ dataurl, maxSize: MAX_IMAGE_PIXEL, ratio: COMPRESS_RATIO, toBlob: true, callback(blob) { if (blob !== false) { blob.name = image.name; processData(blob); } }, }); } }; reader.readAsDataURL(image); } else { processData(image); } } }, onPaste() { // clear up unwanted tag info when user pasted in text const thisNote = this; const updatePastedText = function(object) { const someNote = getSummernote(object); const original = someNote.summernote('code'); const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML. someNote.summernote('reset'); //clear original someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code. }; setTimeout(function() { //this kinda sucks, but if you don't do a setTimeout, //the function is called before the text is really pasted. updatePastedText(thisNote); }, 10); }, }, dialogsInBody: true, disableDragAndDrop: true, toolbar, popover: { image: [ [ 'image', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'], ], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']], ], table: [ ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']], ], air: [ ['color', ['color']], ['font', ['bold', 'underline', 'clear']], ], }, height: 200, }); }); } } else { enableTextarea(); } }); // XXX I believe we should compute a HTML rendered field on the server that // would handle markdown and user mentions. We can simply have two // fields, one source, and one compiled version (in HTML) and send only the // compiled version to most users -- who don't need to edit. // In the meantime, all the transformation are done on the client using the // Blaze API. const at = HTML.CharRef({ html: '&commat;', str: '@' }); Blaze.Template.registerHelper( 'mentions', new Template('mentions', function() { const view = this; let content = Blaze.toHTML(view.templateContentBlock); const currentBoard = Boards.findOne(Session.get('currentBoard')); if (!currentBoard) return HTML.Raw(sanitizeXss(content)); const knowedUsers = currentBoard.members.map(member => { const u = Users.findOne(member.userId); if (u) { member.username = u.username; } return member; }); const mentionRegex = /\B@([\w.]*)/gi; let currentMention; while ((currentMention = mentionRegex.exec(content)) !== null) { const [fullMention, username] = currentMention; const knowedUser = _.findWhere(knowedUsers, { username }); if (!knowedUser) { continue; } const linkValue = [' ', at, knowedUser.username]; let linkClass = 'atMention js-open-member'; if (knowedUser.userId === Meteor.userId()) { linkClass += ' me'; } const link = HTML.A( { class: linkClass, // XXX Hack. Since we stringify this render function result below with // `Blaze.toHTML` we can't rely on blaze data contexts to pass the // `userId` to the popup as usual, and we need to store it in the DOM // using a data attribute. 'data-userId': knowedUser.userId, [ASIS]: 'true', }, linkValue, ); content = content.replace(fullMention, Blaze.toHTML(link)); } return HTML.Raw(sanitizeXss(content)); }), ); Template.viewer.events({ // Viewer sometimes have click-able wrapper around them (for instance to edit // the corresponding text). Clicking a link shouldn't fire these actions, stop // we stop these event at the viewer component level. 'click a'(event, templateInstance) { let prevent = true; const userId = event.currentTarget.dataset.userid; if (userId) { Popup.open('member').call({ userId }, event, templateInstance); } else { const href = event.currentTarget.href; const child = event.currentTarget.firstElementChild; if (child && child.tagName === 'IMG') { prevent = false; } else if (href) { window.open(href, '_blank'); } } if (prevent) { event.stopPropagation(); // XXX We hijack the build-in browser action because we currently don't have // `_blank` attributes in viewer links, and the transformer function is // handled by a third party package that we can't configure easily. Fix that // by using directly `_blank` attribute in the rendered HTML. event.preventDefault(); } }, });
GhassenRjab/wekan
client/components/main/editor.js
JavaScript
mit
14,543
import React, { Component } from 'react'; import { Form, Grid, Input, Item, Select, Header, Image, Segment } from 'semantic-ui-react'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Sector, Cell, Bar, BarChart } from 'recharts'; import axios from 'axios'; const styles = { column: { paddingTop: '.5rem', paddingBottom: '.5rem' }, row: { paddingTop: 0, paddingBottom: 0 } }; const data = [ {name: 'Page A', uv: 4000, pv: 2400, amt: 2400}, {name: 'Page B', uv: 3000, pv: 1398, amt: 2210}, {name: 'Page C', uv: 2000, pv: 9800, amt: 2290}, {name: 'Page D', uv: 2780, pv: 3908, amt: 2000}, {name: 'Page E', uv: 1890, pv: 4800, amt: 2181}, {name: 'Page F', uv: 2390, pv: 3800, amt: 2500}, {name: 'Page G', uv: 3490, pv: 4300, amt: 2100}, ]; const ages = [ {name: 17, value: 1}, {name: 18, value: 1}, {name: 19, value: 1}, // {name: '20', value: 19}, // {name: '21', value: 14}, // {name: '22', value: 17}, // {name: '23', value: 24}, // {name: '24', value: 26}, // {name: '25', value: 29}, // {name: '26', value: 21}, ]; const gender = [ {name: 'Male', value: 40}, {name: 'Female', value: 40}, {name: 'Other', value: 10}, ]; const hometowns = [ {name: 'Adjuntas', value: 20}, {name: 'Aguada', value: 21}, {name: 'Aguadilla', value: 30}, {name: 'Aguas Buenas', value: 50}, {name: 'Aibonito', value: 20}, {name: 'Añasco', value: 20}, {name: 'Arecibo', value: 20}, // {name: 'Arroyo', value: 20}, // {name: 'Barceloneta', value: 20}, // {name: 'Barranquitas', value: 20}, // {name: 'Bayamón', value: 20}, // {name: 'Cabo Rojo', value: 20}, // {name: 'Caguas', value: 20}, // {name: 'Camuy', value: 20}, // {name: 'Carolina', value: 20}, // {name: 'Cataño', value: 20}, // {name: 'Cayey', value: 20}, // {name: 'Ceiba', value: 20}, // {name: 'Ciales', value: 20}, // {name: 'Cidra', value: 20}, // {name: 'Coamo', value: 20}, // {name: 'Comerío', value: 20}, // {name: 'Corozal', value: 20}, // {name: 'Culebra', value: 20}, // {name: 'Dorado', value: 20}, // {name: 'Fajardo', value: 20}, // {name: 'Florida', value: 20}, // {name: 'Guánica', value: 20}, // {name: 'Guayama', value: 20}, // {name: 'Guayanilla', value: 20}, // {name: 'Guaynabo', value: 20}, // {name: 'Gurabo', value: 20}, // {name: 'Hatillo', value: 20}, // {name: 'Hormigueros', value: 20}, // {name: 'Humacao', value: 20}, // {name: 'Isabela', value: 20}, // {name: 'Jayuya', value: 20}, // {name: 'Juana Díaz', value: 20}, // {name: 'Juncos', value: 20}, // {name: 'Lajas', value: 20}, // {name: 'Lares', value: 20}, // {name: 'Las Marías', value: 20}, // {name: 'Las Piedras', value: 20}, // {name: 'Loiza', value: 20}, // {name: 'Luquillo', value: 20}, // {name: 'Manatí', value: 20}, // {name: 'Maricao', value: 20}, // {name: 'Maunabo', value: 20}, // {name: 'Mayagüez', value: 20}, // {name: 'Moca', value: 20}, // {name: 'Morovis', value: 20}, // {name: 'Naguabo', value: 20}, // {name: 'Naranjito', value: 20}, // {name: 'Orocovis', value: 20}, // {name: 'Patillas', value: 20}, // {name: 'Peñuelas', value: 20}, // {name: 'Ponce', value: 20}, // {name: 'Quebradillas', value: 20}, // {name: 'Rincón', value: 20}, // {name: 'Rio Grande', value: 20}, // {name: 'Sabana Grande', value: 20}, // {name: 'Salinas', value: 20}, // {name: 'San Germán', value: 20}, // {name: 'San Juan', value: 20}, // {name: 'San Lorenzo', value: 20}, // {name: 'San Sebastián', value: 20}, // {name: 'Santa Isabel', value: 20}, // {name: 'Toa Alta', value: 20}, // {name: 'Toa Baja', value: 20}, // {name: 'Trujillo Alto', value: 20}, // {name: 'Utuado', value: 20}, // {name: 'Vega Alta', value: 20}, // {name: 'Vega Baja', value: 20}, // {name: 'Vieques', value: 20}, // {name: 'Villalba', value: 20}, // {name: 'Yabucoa', value: 20}, // {name: 'Yauco', value: 20}, ]; const colleges = [ {name: 'University of Puerto Rico, Arecibo', students: 20}, {name: 'University of Puerto Rico, Aguadilla', students: 3}, {name: 'University of Puerto Rico, Bayamon', students: 15}, {name: 'University of Puerto Rico, Carolina', students: 30}, {name: 'University of Puerto Rico, Cayey', students: 22}, {name: 'University of Puerto Rico, Ciencias Medicas', students: 27}, {name: 'University of Puerto Rico, Humacao', students: 18}, {name: 'University of Puerto Rico, Mayaguez', students: 13}, {name: 'University of Puerto Rico, Rio Piedras', students: 40}, {name: 'University of Puerto Rico, Ponce', students: 17}, {name: 'University of Puerto Rico, Utuado', students: 15}, ]; const majors = [ {name: 'ICOM', students: 10}, {name: 'INEL', students: 20}, {name: 'INQU', students: 26}, {name: 'INCI', students: 13}, {name: 'INME', students: 30}, {name: 'ININ', students: 20}, {name: 'OTHER', students: 23}, ]; const hack = ` .recharts-wrapper { height: auto !important; width: auto !important; }`; const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#408042', '#6FF0F2', '#6F0042']; const RADIAN = Math.PI / 180; const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index }) => { const radius = innerRadius + (outerRadius - innerRadius) * 0.80; const x = cx + radius * Math.cos(-midAngle * RADIAN); const y = cy + radius * Math.sin(-midAngle * RADIAN); return ( <text x={x} y={y} fill="white" textAnchor={'middle'} dominantBaseline="central"> {`${(percent * 100).toFixed(0)}%`} </text> ); }; export default class EventStats extends Component { constructor () { super(); this.state = {stats: {}}; } componentWillMount() { const tick = this; // Get Events Data to render axios.get('/api/event/stats/' + this.props.params.eventID) .then(function (response) { console.log(response); tick.setState({stats: response.data}) }) .catch(function (error) { console.log(error); }); } render() { if(!this.state.stats.general) return null; return ( <Grid padded> <style type="text/css"> {hack} </style> <Header as='h1' style={{marginTop: 10}}> <Image shape='rounded' size='medium' src={this.state.stats.general.image_path}/> {' '}{this.state.stats.general.event_name} </Header> <Grid.Row style={styles.row} centered> <Grid.Column computer={5} tablet={5} mobile={16} style={styles.column}> <Header as='h2' attached='top' inverted> Gender </Header> <Segment attached> <ResponsiveContainer aspect={1} > <PieChart > <Pie data={this.state.stats.genders} nameKey='gender' valueKey='count' fill="#8884d8" labelLine={false} label={renderCustomizedLabel}> {data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)} </Pie> <Tooltip/> <Legend wrapperStyle={{position: 'relative'}}/> </PieChart> </ResponsiveContainer> </Segment> </Grid.Column> <Grid.Column computer={5} tablet={5} mobile={16} style={styles.column}> <Header as='h2' attached='top' inverted> Ages </Header> <Segment attached > <ResponsiveContainer aspect={1} > <PieChart > <Pie data={this.state.stats.ages} nameKey='age' valueKey='count' fill="#8884d8" labelLine={false} label={renderCustomizedLabel}> {data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)} </Pie> <Tooltip/> <Legend wrapperStyle={{position: 'relative'}}/> </PieChart> </ResponsiveContainer> </Segment> </Grid.Column> <Grid.Column computer={5} tablet={5} mobile={16} style={styles.column}> <Header as='h2' attached='top' inverted> Hometowns </Header> <Segment attached > <ResponsiveContainer aspect={1} > <PieChart > <Pie data={this.state.stats.hometowns} nameKey='hometown' valueKey='count' fill="#8884d8" labelLine={false} label={renderCustomizedLabel}> {data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)} </Pie> <Tooltip/> <Legend wrapperStyle={{position: 'relative'}}/> </PieChart> </ResponsiveContainer> </Segment> </Grid.Column> </Grid.Row > <Grid.Row stretched style={styles.row}> <Grid.Column stretched computer={8} tablet={8} mobile={16} style={styles.column}> <Header as='h2' attached='top' inverted> Colleges </Header> <Segment attached> <ResponsiveContainer aspect={2} > <BarChart data={this.state.stats.colleges}> <XAxis label="Height" dataKey="college" /> <YAxis label="Student count"/> <CartesianGrid strokeDasharray="3 3"/> <Tooltip/> <Bar dataKey="count" fill="#82ca9d" /> </BarChart> </ResponsiveContainer> </Segment> </Grid.Column> <Grid.Column stretched computer={8} tablet={8} mobile={16} style={styles.column}> <Header as='h2' attached='top' inverted> Majors </Header> <Segment attached> <ResponsiveContainer aspect={2} > <BarChart data={this.state.stats.majors}> <XAxis label="Height" dataKey="major" /> <YAxis label="Student count"/> <CartesianGrid strokeDasharray="3 3"/> <Tooltip/> <Bar dataKey="count" fill="#82ca9d" /> </BarChart> </ResponsiveContainer> </Segment> </Grid.Column> </Grid.Row> </Grid> ); } }
mario2904/ICOM5016-Project
app/components/event-stats.js
JavaScript
mit
10,728
'use strict'; const util = require('util'); /** * @class Message * This is a test */ class Message { constructor(type) { this._state = { type: type }; } /** * See https://dev.kik.com/#/docs/messaging#text * @return {Message} */ static text(text) { return new Message('text').setBody(text); } /** * See https://dev.kik.com/#/docs/messaging#link * @return {Message} */ static link(link) { return new Message('link').setUrl(link); } /** * See https://dev.kik.com/#/docs/messaging#picture * @return {Message} */ static picture(picUrl) { return new Message('picture').setPicUrl(picUrl); } /** * See https://dev.kik.com/#/docs/messaging#video * @return {Message} */ static video(videoUrl) { return new Message('video').setVideoUrl(videoUrl); } /** * See https://dev.kik.com/#/docs/messaging#is-typing * @return {Message} */ static isTyping(typing) { return new Message('is-typing').setIsTyping(typing); } /** * See https://dev.kik.com/#/docs/messaging#receipts * @return {Message} */ static readReceipt(messageIds) { return new Message('read-receipt').setMessageIds(messageIds); } /** * See https://dev.kik.com/#/docs/messaging#text * @return {boolean} */ isTextMessage() { return this.type === 'text'; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {boolean} */ isLinkMessage() { return this.type === 'link'; } /** * See https://dev.kik.com/#/docs/messaging#picture * @return {boolean} */ isPictureMessage() { return this.type === 'picture'; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {boolean} */ isVideoMessage() { return this.type === 'video'; } /** * See https://dev.kik.com/#/docs/messaging#start-chatting * @return {boolean} */ isStartChattingMessage() { return this.type === 'start-chatting'; } /** * See https://dev.kik.com/#/docs/messaging#scan-data * @return {boolean} */ isScanDataMessage() { return this.type === 'scan-data'; } /** * See https://dev.kik.com/#/docs/messaging#sticker * @return {boolean} */ isStickerMessage() { return this.type === 'sticker'; } /** * See https://dev.kik.com/#/docs/messaging#is-typing * @return {boolean} */ isIsTypingMessage() { return this.type === 'is-typing'; } /** * See https://dev.kik.com/#/docs/messaging#receipts * @return {boolean} */ isDeliveryReceiptMessage() { return this.type === 'delivery-receipt'; } /** * See https://dev.kik.com/#/docs/messaging#receipts * @return {boolean} */ isReadReceiptMessage() { return this.type === 'read-receipt'; } /** * See https://dev.kik.com/#/docs/messaging#mentions * @return {boolean} */ isMention() { return !!this.mention; } /** * Constructs a JSON payload ready to be sent to the * bot messaging API * @return {object} */ toJSON() { let json; const state = this._state; if (state.type === 'text') { json = { type: 'text', body: '' + state.body }; } else if (state.type === 'is-typing') { json = { type: 'is-typing', isTyping: !!state.isTyping }; } else if (state.type === 'read-receipt') { json = { type: 'read-receipt', messageIds: state.messageIds }; } else { if (state.type === 'picture') { json = { type: 'picture', picUrl: '' + state.picUrl }; if (!util.isUndefined(state.attribution)) { json.attribution = { name: '' + state.attribution.name, iconUrl: '' + state.attribution.iconUrl }; } } else if (state.type === 'link') { json = { type: 'link', url: '' + state.url }; if (!util.isUndefined(state.attribution)) { json.attribution = { name: '' + state.attribution.name, iconUrl: '' + state.attribution.iconUrl }; } } else if (state.type === 'video') { json = { type: 'video', videoUrl: '' + state.videoUrl, }; if (!util.isUndefined(state.attribution)) { json.attribution = { name: '' + state.attribution.name, iconUrl: '' + state.attribution.iconUrl }; } if (!util.isUndefined(state.loop)) { json.loop = !!state.loop; } if (!util.isUndefined(state.muted)) { json.muted = !!state.muted; } if (!util.isUndefined(state.autoplay)) { json.autoplay = !!state.autoplay; } } if (util.isString(state.picUrl)) { json.picUrl = '' + state.picUrl; } if (util.isString(state.title)) { json.title = '' + state.title; } if (util.isString(state.text)) { json.text = '' + state.text; } if (!util.isUndefined(state.noSave)) { json.noSave = !!state.noSave; } if (!util.isUndefined(state.kikJsData)) { json.kikJsData = state.kikJsData; } if (!util.isUndefined(state.noForward)) { json.noForward = !!state.noForward; } } if (!util.isUndefined(state.typeTime)) { json.typeTime = +state.typeTime; } if (!util.isUndefined(state.delay)) { json.delay = +state.delay; } if (state.keyboards && state.keyboards.length !== 0) { json.keyboards = state.keyboards; } return json; } parse(json) { Object.keys(json).forEach((key) => { this._state[key] = json[key]; }); return this; } /** * Constructs a new {Message} object from a JSON-encoded payload * See https://dev.kik.com/#/docs * @param {object} json * @return {Message} */ static fromJSON(json) { let msg = new Message(json.type); return msg.parse(json); } /** * See https://dev.kik.com/#/docs/messaging#keyboards * @param {string} text * @return {Message} */ addTextResponse(text) { if (util.isArray(text)) { text.forEach((response) => { this.addTextResponse(response); }); return this; } let keyboards = this._state.keyboards || []; let responses = []; let updateExistingKeyboard = false; // add to an existing keyboard if all properties match keyboards.forEach((keyboard) => { if (util.isUndefined(keyboard.to) && util.isUndefined(keyboard.hidden)) { responses = keyboard.responses; updateExistingKeyboard = true; } }); for (let i = 0, l = arguments.length; i < l; ++i) { responses.push({ type: 'text', body: '' + arguments[i] }); } if (!updateExistingKeyboard) { keyboards.push({ type: 'suggested', responses: responses }); } this._state.keyboards = keyboards; return this; } /** * See https://dev.kik.com/#/docs/messaging#keyboards * @param {array} suggestions * @param {boolean} [isHidden] * @param {string} [user] * @return {Message} */ addResponseKeyboard(suggestions, isHidden, user) { let keyboards = this._state.keyboards || []; let responses = []; let updateExistingKeyboard = false; if (!util.isArray(suggestions)) { suggestions = [suggestions]; } // add to an existing keyboard if all properties match keyboards.forEach((keyboard) => { if (keyboard.to === user && keyboard.hidden === isHidden) { responses = keyboard.responses; updateExistingKeyboard = true; } }); suggestions.forEach((text) => { responses.push({ type: 'text', body: '' + text }); }); if (!updateExistingKeyboard) { let keyboard = { type: 'suggested', responses: responses }; if (!util.isUndefined(isHidden)) { keyboard.hidden = !!isHidden; } if (!util.isUndefined(user)) { keyboard.to = '' + user; } keyboards.push(keyboard); } this._state.keyboards = keyboards; return this; } /** * See https://dev.kik.com/#/docs/messaging#receiving-messages * @return {string} */ get from() { return this._state.from; } /** * See https://dev.kik.com/#/docs/messaging#receiving-messages * @return {string} */ get id() { return this._state.id; } /** * See https://dev.kik.com/#/docs/messaging#receiving-messages * @return {string} */ get chatId() { return this._state.chatId; } /** * See https://dev.kik.com/#/docs/messaging#receipts * @return {array} */ get messageIds() { return this._state.messageIds; } /** * See https://dev.kik.com/#/docs/messaging#receipts * @return {boolean} */ get readReceiptRequested() { return this._state.readReceiptRequested; } /** * See https://dev.kik.com/#/docs/messaging#sticker * @return {string} */ get stickerPackId() { return this._state.stickerPackId; } /** * See https://dev.kik.com/#/docs/messaging#kik-codes-api * @return {string} */ get scanData() { return this._state.data; } /** * See https://dev.kik.com/#/docs/messaging#sticker * @return {string} */ get stickerUrl() { return this._state.stickerUrl; } /** * See https://dev.kik.com/#/docs/messaging#common-fields * @return {number} */ get timestamp() { return this._state.timestamp; } /** * See https://dev.kik.com/#/docs/messaging#message-formats * @return {string} */ get type() { return this._state.type; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {object} */ get kikJsData() { return this._state.kikJsData; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {string} */ get picUrl() { return this._state.picUrl; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {boolean} */ get noForward() { return this._state.noForward; } /** * See https://dev.kik.com/#/docs/messaging#is-typing * @return {boolean} */ get isTyping() { return this._state.isTyping; } /** * See https://dev.kik.com/#/docs/messaging#text * @return {string} */ get body() { return this._state.body; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {string} */ get text() { return this._state.text; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {string} */ get title() { return this._state.title; } /** * See https://dev.kik.com/#/docs/messaging#link * @return {string} */ get url() { return this._state.url; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {string} */ get videoUrl() { return this._state.videoUrl; } /** * See https://dev.kik.com/#/docs/messaging#common-fields * @return {number} */ get delay() { return this._state.delay; } /** * See https://dev.kik.com/#/docs/messaging#text * @return {number} */ get typeTime() { return this._state.typeTime; } /** * See https://dev.kik.com/#/docs/messaging#attribution * @return {string} */ get attributionName() { return this._state.attribution ? this._state.attribution.name : undefined; } /** * See https://dev.kik.com/#/docs/messaging#attribution * @return {string} */ get attributionIcon() { return this._state.attribution ? this._state.attribution.iconUrl : undefined; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {boolean} */ get loop() { return this._state.loop; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {boolean} */ get muted() { return this._state.muted; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {boolean} */ get autoplay() { return this._state.autoplay; } /** * See https://dev.kik.com/#/docs/messaging#video * @return {boolean} */ get noSave() { return this._state.noSave; } /** * See https://dev.kik.com/#/docs/messaging#participants * @return {array} */ get participants() { return this._state.participants; } /** * See https://dev.kik.com/#/docs/messaging#mention * @return {string} */ get mention() { return this._state.mention; } /** * @param {object} kikJsData * @return {Message} */ setKikJsData(kikJsData) { this._state.kikJsData = kikJsData; return this; } /** * @param {string} picUrl * @return {Message} */ setPicUrl(picUrl) { this._state.picUrl = picUrl; return this; } /** * @param {boolean} noForward * @return {Message} */ setNoForward(noForward) { this._state.noForward = noForward; return this; } /** * @param {boolean} isTyping * @return {Message} */ setIsTyping(isTyping) { this._state.isTyping = isTyping; return this; } /** * @param {array} messageIds * @return {Message} */ setMessageIds(messageIds) { this._state.messageIds = messageIds; return this; } /** * @param {string} body * @return {Message} */ setBody(body) { this._state.body = body; return this; } /** * @param {string} text * @return {Message} */ setText(text) { this._state.text = text; return this; } /** * @param {string} title * @return {Message} */ setTitle(title) { this._state.title = title; return this; } /** * @param {string} url * @return {Message} */ setUrl(url) { this._state.url = url; return this; } /** * @param {string} videoUrl * @return {Message} */ setVideoUrl(videoUrl) { this._state.videoUrl = videoUrl; return this; } /** * @param {number} delay * @return {Message} */ setDelay(delay) { this._state.delay = delay; return this; } /** * @param {number} typeTime * @return {Message} */ setTypeTime(typeTime) { this._state.typeTime = typeTime; return this; } /** * @param {string} attributionName * @return {Message} */ setAttributionName(attributionName) { this._state.attribution = this._state.attribution || {}; this._state.attribution.name = attributionName; return this; } /** * @param {string} attributionIcon * @return {Message} */ setAttributionIcon(attributionIcon) { this._state.attribution = this._state.attribution || {}; this._state.attribution.iconUrl = attributionIcon; return this; } /** * @param {boolean} loop * @return {Message} */ setLoop(loop) { this._state.loop = loop; return this; } /** * @param {boolean} muted * @return {Message} */ setMuted(muted) { this._state.muted = muted; return this; } /** * @param {boolean} autoplay * @return {Message} */ setAutoplay(autoplay) { this._state.autoplay = autoplay; return this; } /** * @param {boolean} noSave * @return {Message} */ setNoSave(noSave) { this._state.noSave = noSave; return this; } } module.exports = Message;
TheKillaTV/test2
lib/message.js
JavaScript
mit
17,704
'use strict'; const _ = require('lodash'), chalk = require('chalk'), npm = require.main.require('./core/Npm'); class DependencyInstaller { constructor(evermore) { this._evermore = evermore; this._pending = evermore._dependencies; this._installed = []; } install() { if (this._isDoneInstalling()) { return this._evermore; } return this._npmInstall(this._pending.pop()) .then(_ => this.install()); } _npmInstall(dependency) { say(`Installing ${chalk.blue(dependency.toString())}...`); return npm.install(dependency) .then(_ => { affirm(`*${dependency.toString()}* has been installed successfully!`); this._installed.push(dependency); }); } _isDoneInstalling() { return _.isEmpty(this._pending); } } module.exports = DependencyInstaller;
luminol-io/evermore-installer
dependencies/DependencyInstaller.js
JavaScript
mit
936
import WORLD from 'constants/world' import Base from './Base' import { describe, glow } from 'mixins' @describe('x', 'y') export class Shape extends Base { constructor(x, y) { super(x, y) this.x = x this.y = y } describe() { let desc = { type: this.constructor.name, data: {} } this._describe.forEach(key => (desc.data[key] = this[key] instanceof Shape ? this[key].describe() : this.scale(key)) ) return desc } scale(key) { return ( this._scale && key in this._scale ) >= 0 ? this[key] * WORLD.r : this[key] } } /* Rectangle */ @describe('x', 'y', 'r', 'sides', 'color', 'rotation') export class Polygon extends Shape { constructor(x, y, r, sides, color) { super(x, y) if (sides < 3) throw new Error('Invalid Polygon') this.x = x this.y = y this.r = r this.sides = sides this.color = color } draw(ctx, params) { if (params.sides < 3) return var a = (Math.PI * 2)/params.sides ctx.save() ctx.translate(params.x, params.y) ctx.rotate(params.rotation) ctx.beginPath() ctx.moveTo(params.r,0) for (var i = 1; i < params.sides; i++) { ctx.lineTo(params.r*Math.cos(a*i),params.r*Math.sin(a*i)) } ctx.closePath() ctx.lineWidth = 1 ctx.fill() ctx.restore() } } /* Triangle */ @describe('x', 'y', 'color') export class Triangle extends Polygon { constructor(x, y, color) { super([[x, y],[x + 50, y],[x + 25, y - 50]], color) } } /* Rectangle */ @describe('x', 'y', 'width', 'height', 'color') export class Rectangle extends Shape { constructor(x, y, width, height, color) { super(x, y) this.width = width this.height = height this.color = color } draw(ctx, params) { ctx.beginPath() ctx.rect(params.x, params.y, params.width, params.height) ctx.fillStyle = params.color ctx.fill() ctx.closePath() } } @glow('white', 2) @describe('x', 'y', 'r', 'color') export class Arc { constructor(x, y, r, startAngle, endAngle, color) { this.x = x this.y = y this.r = r this.color = color this.startAngle = startAngle this.endAngle = endAngle } draw(ctx, params) { ctx.save() ctx.translate(params.x, params.y) ctx.rotate(params.rotation) ctx.beginPath() ctx.arc(0, 0, params.r, params.startAngle * Math.PI, (params.startAngle + params.endAngle) * Math.PI) ctx.strokeStyle = params.color ctx.lineWidth = 3.5 ctx.stroke() ctx.restore() } } /* Circle */ @describe('x', 'y', 'r', 'rotation', 'color') export class Circle extends Shape { constructor(x, y, r, color) { super(x, y) this.r = r this.color = color } draw(ctx, params) { ctx.save() ctx.translate(params.x, params.y) ctx.rotate(params.rotation) // Ball ctx.beginPath() ctx.arc(0, 0, params.r, 0, 2*Math.PI) ctx.fillStyle = params.color ctx.fill() ctx.stroke() ctx.restore() } }
BarakChamo/mobileShooter
app/components/Shapes.js
JavaScript
mit
3,022
'use strict'; angular.module( 'websiteCategories', [] ) .provider( '$websiteCategories', function() { this.$get = function() { return {}; }; } ) .config( [ '$mmApiProvider', function($mmApiProvider) { $mmApiProvider.addRoute( 'website', 'productCategories', '/Website/Categories' ); }, ] ) .run( [ function() { }, ] ) .directive( 'websiteCategory', [ 'websiteCategories', 'api', function(websiteCategories, api) { return { scope : {model: '='}, template: [ '<ol id="singleSelection" class="nya-bs-select form-control" ng-model="model">', '<li nya-bs-option="c in categories group by c.category_id" value="c.id" class="nya-bs-option" deep-watch="true">', '<span class="dropdown-header">{{getHeaderName($group)}}</span> ', '<a>{{c.name}}</a>', '</li>', '</ol>', ].join( '\n' ), link : function(scope, element, attr) { websiteCategories.get().then( function(response) { scope.categories = response; } ); scope.getHeaderName = function($id) { var header = ''; angular.forEach( scope.categories, function(v, k) { if (v.id === $id) { header = v.name; } } ); return header; }; }, }; }, ] ) .service( 'websiteCategories', [ '$q', 'api', function($q, api) { var self = this; self.$construct = function() {self.categories = [];}; self.get = function() { if (empty( self.categories )) { var deferred = $q.defer(); api.get( 'website', 'productCategories', {flat: true} ).then( function(result) { deferred.resolve( result.webCategories.categories ); } ).catch( angular.noop ); self.categories = deferred.promise; } return $q.when( self.categories ); }; self.refresh = function() { self.$construct(); return self.get(); }; self.save = function(category) { var deferred = $q.defer(); api.save( 'website', 'productCategories', category ).then( function(result) { deferred.resolve( result.webCategories.categories ); } ); self.categories = deferred.promise; return $q.when( self.categories ); }; self.delete = function(category) { var deferred = $q.defer(); api.delete( 'website', 'productCategories', category ).then( function(result) { deferred.resolve( result.webCategories.categories ); } ); self.categories = deferred.promise; return $q.when( self.categories ); }; self.$restore = function() { self.refresh(); }; self.$save = function() { self.categories.then( function(categories) { self.save( categories ); } ); }; self.$destroy = function() {}; }, ] );
JakeAi/Dashboard
public/assets/js/ng/Modules/WebsiteModules/categories/_webCategories.js
JavaScript
mit
2,680
var quoteresult = []; var symbol = ''; stockquoteapp.controller('stockquoteController', function ($scope, StockQuoteService, $filter) { StockQuoteService.stockSymbol = "GHL"; StockQuoteService.GetStockPrice(function (results) { console.log(results); $scope.quoteresult = results.query.results.quote; console.log($scope.quoteresult); }); $scope.stockQuoteClass = function (scores) { if (scores != null) { var stockChange = scores.split(" - ")[0]; var stockChangeDirection = stockChange.charAt(0); return stockChangeDirection == '+' ? 'companyStockUp' : 'companyStockDown'; } } StockQuoteService.GetDateFormat(function (results) { console.log(results); $scope.dateFormat = results.d.results[0].DateFormat; }); $scope.convertStringToDate = function (datevalue) { if (datevalue != null) { return new Date(datevalue); } } });
athrayee/StockQuoteWebpart
js/stockquotecontroller.js
JavaScript
mit
1,007
'use strict'; /* @flow */ /* globals Map: false */ /** * The [mode](http://bit.ly/W5K4Yt) is the number that appears in a list the highest number of times. * There can be multiple modes in a list: in the event of a tie, this * algorithm will return the most recently seen mode. * * modeFast uses a Map object to keep track of the mode, instead of the approach * used with `mode`, a sorted array. As a result, it is faster * than `mode` and supports any data type that can be compared with `==`. * It also requires a * [JavaScript environment with support for Map](https://kangax.github.io/compat-table/es6/#test-Map), * and will throw an error if Map is not available. * * This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency): * a method of finding a typical or central value of a set of numbers. * * @param {Array<*>} x a sample of one or more data points * @returns {?*} mode * @throws {ReferenceError} if the JavaScript environment doesn't support Map * @throws {Error} if x is empty * @example * modeFast(['rabbits', 'rabbits', 'squirrels']); // => 'rabbits' */ function modeFast/*::<T>*/(x /*: Array<T> */)/*: ?T */ { // This index will reflect the incidence of different values, indexing // them like // { value: count } var index = new Map(); // A running `mode` and the number of times it has been encountered. var mode; var modeCount = 0; for (var i = 0; i < x.length; i++) { var newCount = index.get(x[i]); if (newCount === undefined) { newCount = 1; } else { newCount++; } if (newCount > modeCount) { mode = x[i]; modeCount = newCount; } index.set(x[i], newCount); } if (modeCount === 0) { throw new Error('mode requires at last one data point'); } return mode; } module.exports = modeFast;
kevinmcdonald19/greenr
node_modules/simple-statistics/src/mode_fast.js
JavaScript
mit
1,925
// this was simply a test to manually create a sine wave, without // the oscillator class function manualPlaySineWave(frequency) { var context = new webkitAudioContext(); var bufferSize = 1024; var buffer = context.createBuffer(1, bufferSize, context.sampleRate); var bufferSource = context.createBufferSource(); bufferSource.buffer = buffer; var bufferData = buffer.getChannelData(0); for (var i = 0; i < bufferData.length; i++) { // 1 sine wave in buffer bufferData[i] = Math.sin((i/bufferSize)*(2*Math.PI)); } bufferSource.loop = true; // calculate the frequency we want bufferSource.playbackRate.value = frequency / (context.sampleRate / bufferSize); bufferSource.connect(context.destination); bufferSource.noteOn(0); }
achalddave/Audio-API-Frequency-Generator
manualSineWave.js
JavaScript
mit
762
(function () { console.log("I'm a git commit"); consolg.lof("I'm also a git commit"); var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var baltimore = require('./baltimore'); var _ = require('lodash'); app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE'); res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); if ('OPTIONS' == req.method) { return res.sendStatus(200); } next(); }); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var router = require('express').Router(); var port = process.env.PORT || 8080; router.use(function (req, res, next) { //do logging console.log('Something is happening.'); next(); //ensure that the router doesn't halt here }); router.route('/').get(function (req, res, next) { var jobTitleList = []; var annualSalaryList = []; var departmentList = []; var aggregateList = []; baltimore.data.forEach(function (entry) { jobTitleList.push(entry[9]) }); baltimore.data.forEach(function (entry) { annualSalaryList.push(entry[13]) }); baltimore.data.forEach(function (entry) { departmentList.push(entry[11]) }); var salaryList = baltimore.data.filter(function(person){ return parseInt(person[13]) >= 100000; }); var unique = _.uniq(departmentList); console.log(unique); //console.log(jobTitleList.length + "job titles"); //console.log(annualSalaryList.length + "annual salaries"); //console.log(departmentList.length + "departments"); //console.log(unique.length); //var thing = []; //for ( x in unique){ // if(baltimore.data.forEach(entry[11]) === x){ // thing.push({x: entry[13]}) // } //} //console.log(thing); //var comboObject = _.sortBy(annualSalaryList.map(Number)); res.send(salaryList); next(); }); //router.get('/', function(req, res){ // res.json({message: 'hooray, welcome to our api!'}); //}); app.use('/', router); app.listen(port); console.log('Magic happens on port ' + port); }());
craigclemons/BaltimoreData
app.js
JavaScript
mit
2,639
$(function () { var all_classes = ""; var timer = undefined; $.each($('li', '.social-class'), function (index, element) { all_classes += " btn-" + $(element).data("code"); }); $('li', '.social-class').mouseenter(function () { var icon_name = $(this).data("code"); if ($(this).data("icon")) { icon_name = $(this).data("icon"); } var icon = "<i class='fa fa-" + icon_name + "'></i>"; $('.btn-social', '.social-sizes').html(icon + "Sign in with " + $(this).data("name")); $('.btn-social-icon', '.social-sizes').html(icon); $('.btn', '.social-sizes').removeClass(all_classes); $('.btn', '.social-sizes').addClass("btn-" + $(this).data('code')); }); $($('li', '.social-class')[Math.floor($('li', '.social-class').length * Math.random())]).mouseenter(); }); $(function () { var all_classes = ""; var timer = undefined; $.each($('li', '.social-class'), function (index, element) { var icon_type = $(element).data("code"); // var tokens = icon_type.split('-'); // var icon_name = tokens.slice(0, tokens.length-1).join('-'); all_classes += " btn-" + icon_type; all_classes += " btn-" + icon_type + "-transparent"; all_classes += " btn-" + icon_type + "-half-transparent"; // all_classes += " btn-" + icon_name; }); $('li', '.social-class-alternate').mouseenter(function () { var icon_type = $(this).data("code"); var tokens = icon_type.split('-'); var icon_name = ""; if (tokens[tokens.length-2] == "half") icon_name = tokens.slice(0, tokens.length-2).join('-'); else icon_name = tokens.slice(0, tokens.length-1).join('-'); var icon = "<i class='fa fa-" + icon_name + "'></i>"; $('.btn-social', '.social-sizes-alternate').html(icon + "Sign in with " + $(this).data("name")); $('.btn-social-icon', '.social-sizes-alternate').html(icon); $('.btn', '.social-sizes-alternate').removeClass(all_classes); // console.log(all_classes.toString()); $('.btn', '.social-sizes-alternate').addClass("btn-" + icon_name); $('.btn', '.social-sizes-alternate').addClass("btn-" + icon_type); }); $($('li', '.social-class-alternate')[Math.floor($('li', '.social-class-alternate').length * Math.random())]).mouseenter(); }); function adjustBlur() { // Get scroll position var s = $(window).scrollTop(), // scroll value and opacity opacityVal = (s / $(document).height()); // opacity value 0% to 100% $('#background-blur').css('opacity', opacityVal); } $(window).scroll(function() { adjustBlur(); }); $(document).ready(function() { adjustBlur(); });
radzinzki/bootstrap-social
assets/js/docs.js
JavaScript
mit
2,601
const assert = require('assert') const Coordinate = require('../lib/coordinate') describe('Coordinate', () => { it("should calculate the distance from itself", () => { const a = new Coordinate(0, 0) assert.strictEqual(a.distanceFrom(a), 0) }) it("should calculate the distance from another coordinate along X axis", ()=>{ const a = new Coordinate(0, 0) const b = new Coordinate(600, 0) assert.strictEqual(a.distanceFrom(b), 600) }) // it("should calculate the distance from another coordinate", ()=>{ // const a = new Coordinate(0, 0) // const b = new Coordinate(300, 400) // // assert.strictEqual(a.distanceFrom(b), 500) // }) })
cucumber-ltd/shouty.js
test/coordinate.test.js
JavaScript
mit
682
'use strict'; import Model from './Model.js'; import Utils from '../utils/Utils.js'; export default class MessagesSet extends Model { /** * This class represents a JMAP [MessagesSet]{@link http://jmap.io/spec.html#setmessages}. * * @constructor * @extends Model * * @param jmap {Client} The {@link Client} instance that created this _MessagesSet_. * @param [opts] {Object} The optional properties of this _MessagesSet_. * @param [opts.accountId=''] {String} The id of the {@link Account} used in the request that originated this _MessagesSet_. * @param [opts.created=Object] {Object} A map of the creation id to an object containing the id, blobId, threadId, * and size properties for each successfully created message. * @param [opts.updated=[]] {String[]} A list of Message ids for Messages that were successfully updated. * @param [opts.destroyed=[]] {String[]} A list of Message ids for Messages that were successfully destroyed. * @param [opts.notCreated=Object] {Object} A map of Message id to an error for each Message that failed to be created. * @param [opts.notUpdated=Object] {Object} A map of Message id to an error for each Message that failed to be updated. * @param [opts.notDestroyed=Object] {Object} A map of Message id to an error for each Message that failed to be destroyed. * * @see Model */ constructor(jmap, opts) { super(jmap); opts = opts || {}; this.accountId = opts.accountId || ''; this.created = opts.created || {}; this.updated = opts.updated || []; this.destroyed = opts.destroyed || []; this.notCreated = opts.notCreated || {}; this.notUpdated = opts.notUpdated || {}; this.notDestroyed = opts.notDestroyed || {}; } /** * Creates a _MessagesSet_ from its JSON representation. * * @param jmap {Client} The {@link Client} instance passed to the _MessagesSet_ constructor. * @param object {Object} The JSON representation of the _MessagesSet_, as a Javascript object. * * @return {MessagesSet} */ static fromJSONObject(jmap, object) { Utils.assertRequiredParameterIsPresent(object, 'object'); return new MessagesSet(jmap, object); } }
thomascube/jmap-client
lib/models/MessagesSet.js
JavaScript
mit
2,204
var injector = angular.injector(['ng', 'phonecatApp']); var scope = injector.get('$rootScope').$new(); var controller = injector.get('$controller');
funambol/bugfreeexample
src/test/angular/fake.js
JavaScript
mit
148
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var mongoosePaginate = require('mongoose-paginate'); var userSchema = mongoose.Schema({ email : String, password : String, scanner_uuid : {type: String, default: ""}, first_name : String, last_name : String, balance: {type: Number, default: 0}, roles: {type: Array, default: new Array('guest')}, status: {type: String, default: "active"}, created : {type: Date, default: Date.now} }); userSchema.methods.hasRole = function(role) { if(this.roles.indexOf(role) != -1) { return true; } else { return false; } }; userSchema.methods.increaseBalance = function(paymentAmount) { this.balance = this.balance + paymentAmount; }; userSchema.methods.decreaseBalance = function(purchaseAmount) { this.balance = this.balance - purchaseAmount; }; userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.password); }; userSchema.statics.findWithNegativeBalance = function(callback) { this.where('balance').lt(0).exec(callback); }; userSchema.statics.getUsersWithRole = function(role) { return this.find({'roles': role }).exec(); }; userSchema.statics.getTotalOutstandingBalance = function() { return this.aggregate([ { $project: { outstandingBalance: {$cond: [{$lt: ['$balance', 0]}, '$balance', 0]}, totalLiabilities: {$cond: [{$gt: ['$balance', 0]}, '$balance', 0]}, balance: 1 } }, { $group: { _id: null, totalOutstandingBalance: {$sum: '$outstandingBalance'}, totalLiabilities: {$sum: '$totalLiabilities'}, totalBalance: {$sum: '$balance'}, userCount: {$sum: 1} } } ]).exec(); }; userSchema.plugin(mongoosePaginate); module.exports = mongoose.model('User', userSchema);
chuckdrew/theofficekeg
models/user.js
JavaScript
mit
2,113
Titanium.UI.setBackgroundColor('#000'); var win = Ti.UI.createWindow(); /* * Message Webview and container to kill horizontal scrolling */ var container = Ti.UI.createView({ top:0, left:0, width:320, height:420, touchEnabled:true }); var webview = Ti.UI.createWebView({ url:'webview.html', top:0, left:0, width:'100%', }); container.add(webview); win.add(container); /* * Input Toolbar */ var flexSpace = Titanium.UI.createButton({ systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); var textfield = Titanium.UI.createTextField({ height:32, backgroundImage:'images/inputfield.png', width:200, font: { fontSize:13 }, color:'#777', paddingLeft:10, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE, returnKeyType:Titanium.UI.RETURNKEY_SEND }); var sendButton = Titanium.UI.createButton({ backgroundImage:'images/send.png', backgroundSelectedImage:'images/send_selected.png', width:67, height:32 }); var toolbar = Titanium.UI.createToolbar({ items:[flexSpace,textfield,flexSpace, sendButton,flexSpace], bottom:0, borderTop:true, borderBottom:false, translucent:true, barColor:'#999' }); win.add(toolbar); toolbar.hide(); /* * Event Listeners */ sendButton.addEventListener('click', function() { Ti.App.fireEvent('message:out', { message:textfield.value }); textfield.value = ''; }); textfield.addEventListener('return', function () { Ti.App.fireEvent('message:out', { message:textfield.value }); textfield.value = ''; }); textfield.addEventListener('focus', function () { container.height = 200; toolbar.bottom = 216; }); textfield.addEventListener('blur', function () { container.height = 420; toolbar.bottom = 0; }); Ti.App.addEventListener('nickname:get', function() { Ti.API.info('fired -> nickname:get'); toolbar.hide(); var popup = Ti.UI.createView({ borderColor:'#999999', borderRadius:20, borderWidth:2, top:20, opacity:0.5, height:80, width:250, backgroundColor:'#000000' }); var label = Ti.UI.createLabel({ text:'Enter Your Nickname', color:'#ffffff', opacity:1, top:10, height:'auto', width:'auto' }); popup.add(label); var input = Ti.UI.createTextField({ bottom:10, width: 150, height: 30, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Titanium.UI.RETURNKEY_DONE }); popup.add(input); win.add(popup); input.addEventListener('return', function () { if(input.value !== '') { Ti.App.fireEvent('nickname:set', { user:input.value }); popup.hide(); toolbar.show(); } }) }); win.open();
euforic/ChatSocks
Resources/app.js
JavaScript
mit
2,659
module.exports = function() { this.onSetup = function(entity) { entity.addComponent("2D, Canvas, Mouse, playerSprite0") .attr({ x: 50, y: 50, z: 10, w: 100, h: 100 }) .bind("Click", function(sender, e) { sender.alert("Welcome Boss says: 'Hey, welcome to JSWorlds and stuff.'"); }); }; };
JesseDunlap/jsworlds
app/public/assets/scripts/WelcomeBoss.js
JavaScript
mit
474
var path = require('path'); var url = require('url'); var express = require('express'); var fs = require('fs'); var https = require('https'); var http = require('http'); var path = require('path'); var bcrypt = require('bcrypt-nodejs'); var CONFIG = require('./config.js') var favicon = require('serve-favicon'); var db = require('./db/config'); var Users = require('./db/collections/users'); var User = require('./db/models/user'); var Artists = require('./db/collections/artists'); var Artist = require('./db/models/artist'); var Tags = require('./db/collections/tags'); var Tag = require('./db/models/tag'); var Performances = require('./db/collections/performances'); var Performance = require('./db/models/performance'); var Artist_User = require('./db/models/artist_user') var options = { key: fs.readFileSync('keys/server.key'), cert: fs.readFileSync('keys/server.crt') }; var app = express(); var port = 1338; var server = https.createServer(options, app) var io= require('socket.io').listen(server); server.listen(port, function() { console.log(`Running on port: ${port}`); }); app.get('/populateDatabase', function(req, res) { var testUser = new User({ username: 'Jane Bond', admin: true }); var testPerf = new Performance({ room: 'Jim Bob Burshea', title: 'Jimbo sings the blues', short_description: 'My blues are outta control' }); var testTag = new Tag({ tagname: 'doo wop' }); // change testPerf to whatever database table you want to add a row to each time you go to /populateDatabase testPerf.save() .then(function(newEntry) { // change Performances to the table you want to populate Performances.add(newEntry); res.status(200).send(newEntry); }) .catch(function(err) { console.error(err); }); } ); ///////////////////////////////////////////////\ var jwt = require('jsonwebtoken'); var expressJWT = require('express-jwt') var bodyParser = require('body-parser'); var passport = require('passport') , FacebookStrategy = require('passport-facebook').Strategy , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; app.use(favicon(__dirname + '/client/public/img/favicon.png')); app.use(bodyParser.json({limit: '50mb'})); app.use(bodyParser.urlencoded({limit: '50mb', extended: true})); app.use('/',express.static(path.join(__dirname, 'client'))); app.use(expressJWT({secret : CONFIG.JWT_SECRET}).unless({path : ['/',/^\/auth\/.*/,'/authenticateFacebook','/about', /^\/api\/.*/, /^\/api\/messages\/.*/,/^\/activeStream\/.*/, /^\/public\/.*/, /^\/router\/.*/]})); app.post('/auth/signIn/', (req, res) => { new Artist({user_name: req.body.user_name}).fetch().then(function(found){ if(found){ var check = bcrypt.compareSync(req.body.password, found.get('password')) if (check){ var myToken = jwt.sign({user_name:found.get('email_id')},CONFIG.JWT_SECRET) res.status(200).json({token: myToken, artist_details : found}); } else { res.sendStatus(403).json({status : 'Incorrect password'}); } } else { res.sendStatus(403).json({status : 'User does not exist, please sign up'}); } }); }); app.post('/auth/signUp/', (req, res) => { new Artist({user_name: req.body.user_name, password: req.body.password}).fetch().then(function (found) { if (found) { console.log("APPARENTLY FOUND",found) res.status(403); } else { var newArtist = new Artist({ user_name: req.body.user_name, password: req.body.password, email_id: req.body.email_id, brief_description: req.body.brief_description, user_image: req.body.user_image, display_name: req.body.display_name, genre: req.body.genre }); console.log("NEW ARTIST BEING SAVED",newArtist) newArtist.save().then(function (artist) { Artists.add(artist); var myToken = jwt.sign({user_name: req.body.email_id}, CONFIG.JWT_SECRET) res.status(200).json({token: myToken, artist_details: artist}); }) } }); new Performance({active: false, room: req.body.user_name}) .save() }); app.get('/getData/', (req, res) => { res.status(200) .json({data: 'Valid JWT found! This protected data was fetched from the server.'}); }) passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); passport.use(new FacebookStrategy({ clientID: CONFIG.FB_CLIENT_ID, clientSecret: CONFIG.FB_APP_SECRET, callbackURL: CONFIG.FB_CALL_BACK, profileFields: ['id','email', 'displayName', 'photos'] }, function(accessToken, refreshToken, profile, done) { new User({facebook_id : profile.id}).fetch().then(function(response){ console.log("FB RESPONSE",response) console.log("FB PROFILE",profile) if(response){ return done(null,response.attributes) } else{ var facebookUser = new User({ facebook_id : profile.id, email_id : profile.emails[0].value ? profile.emails[0].value : profile.displayName, display_name : profile.displayName, user_image : profile.photos[0].value }) facebookUser.save().then(function(newFacebookUser) { Users.add(newFacebookUser); return done(null,newFacebookUser) }); } }); } )); passport.use(new GoogleStrategy({ clientID: CONFIG.G_CLIENT_ID, clientSecret: CONFIG.G_APP_SECRET, callbackURL: CONFIG.G_CALL_BACK }, function(accessToken, refreshToken, profile, done) { new User({google_id : profile.id}).fetch().then(function(response){ if(response){ console.log("GOOGLE RESPONSE",response) console.log("GOOGLE PROFILE",profile) return done(null,response.attributes) } else{ var googleUser = new User({ google_id : profile.id, email_id : profile.emails[0].value ? profile.emails[0].value : profile.displayName , display_name : profile.displayName, user_image : profile.photos[0].value }) googleUser.save().then(function(newGoogleUser) { Users.add(newGoogleUser); return done(null,newGoogleUser) }); } }); } )); app.use(passport.initialize()); app.get('/auth/facebook/', passport.authenticate('facebook',{scope : 'email'})); var current_token; var current_user; app.get('/auth/facebook/callback/', passport.authenticate('facebook', { failureRedirect: '/' }), function(req, res) { console.log("RESPONSE IN CALLBACK facebook",req.user); current_user = req.user; current_token = jwt.sign({user_name: (req.user.email_id ) },CONFIG.JWT_SECRET); res.redirect('/router/socialLogin') } ); app.get('/auth/google/', passport.authenticate('google',{scope : 'email'})); app.get('/auth/google/callback/', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) { console.log("response for Google in callback",req.user); current_user = req.user; current_token = jwt.sign({user_name: (req.user.email_id ) },CONFIG.JWT_SECRET); res.redirect('/router/socialLogin') } ); app.get('/auth/validateSocialToken',(req, res) => { res.json({token: current_token, user_details : current_user}); }); /////////////////ACTIVE STREAM////////// app.put('/api/describe/', (req, res) => { console.log(req.body, '<---- req.body in api/describe'); Performance.where({ room: req.body.room }).fetch().then(function(updatedPerf){ updatedPerf.save({ long_description: req.body.long_description, performance_image: req.body.performance_image, rated_r: JSON.parse(req.body.rated_r), short_description: req.body.short_description, title: req.body.title }, {patch: true}) .then(function(perf) { console.log('Just updated this performance ---> ', perf); Performances.add(perf); var responseObject = { title: perf.get('title'), short_description: perf.get('short_description'), long_description: perf.get('long_description'), performance_image: perf.get('performance_image') }; res.status(200).json(responseObject); // this object is returned to the client }); }); }); app.put('/api/activeStreams', function(req, res){ Performance.where({ room: req.body.room }).fetch() .then(performance => { performance.save({active: req.body.active}, {patch: true}); res.json({active : req.body.active}) }) }); app.get('/api/activeStreams', function(req, res) { Performances // .query({where: {active: true}}) .fetch({withRelated:['tags']}).then(function (performances) { console.log('active streams with tags from db: ', performances.models); res.status(200).send(performances.models); }); }); app.get('/api/allStreams', function(req, res) { Performances .fetch().then(function (performances) { res.status(200).send(performances.models); }); }); app.put('/api/updatePerformanceViewCount', function(req, res) { Performance.forge({room: req.body.room}) .fetch({require: true}) .then((performance)=>{ performance.save({ number_of_viewers : performance.get('number_of_viewers') + 1 }) res.json({views : (performance.get('number_of_viewers') + 1)}) }) }); app.get('/api/currentViewers', function(req, res) { Performances.query({where: {room: req.body.room}}).fetch().then(function (performance) { res.status(200).json({views : performance.get('number_of_viewers')}); }); }); //*********Tags app.post('/api/addTag', function (req,res){ console.log('/api/addTag route called: ',req.body); var tagName= req.body.tagname; var userId= req.body.user_Id; var performanceId= req.body.performanceId; Tag.where({ tagname: tagName }).fetch() .then(tag => { if(tag) { console.log('tag exists in db'); Performance.where({id: performanceId}).fetch() .then(performance => { performance.tags().attach(tag.id); res.status(200).send({tagname: null, performanceId: performanceId}); //return nothing if tag is already in db console.log('tag attached to performance'); }) } else { console.log('adding tag to db'); var newTag= new Tag({ tagname: tagName, user_id: userId }) newTag.save().then (function (tag){ console.log('tagname: ', tag.attributes.tagname); console.log('tag sucessfuly saved', tag.id); Tags.add(tag); Performance.where({id: performanceId}).fetch() .then(performance => { performance.tags().attach(tag.id); console.log('tag attached to performance', tag); console.log('send back this obj: ', {tagId: tag.id, tagname: tag.attributes.tagname, performanceId: performanceId}) // console.log('response pending', res); res.status(200).send({tagId: tag.id, tagname: tag.attributes.tagname, performanceId: performanceId}); //return the performance with updated tags }) }) } }) // res.status(200).send(req.body); }); //**********RETOKENIZE LOGIN app.get('/auth/getTokenizedUserDetails',(req,res)=>{ console.log("RETOKENIZE",req.query) Artist.query({where: {email_id: req.query.email}}).fetch().then(function(found){ if(found){ console.log("RETOKEN IZE ARTIST",found) var myToken = jwt.sign({user_name:found.get('email_id')},CONFIG.JWT_SECRET) res.status(200).json({token: myToken, artist_details : found}); } else { User.query({where: {email_id: req.query.email}}).fetch().then(function(response){ if(response){ console.log("FB PRFILE RETOKEN",response) res.status(200).json({token: myToken, artist_details : response}); } else{ res.status(404).json({status : 'User does not exist, please sign up'}); } }); } }); }) //**************UPLOAD IMAGE************************ var cloudinary = require('cloudinary'); cloudinary.config({ cloud_name: CONFIG.CLOUD_NAME, api_key: CONFIG.CLOUD_API_KEY, api_secret: CONFIG.CLOUD_API_SECRET }); app.post('/api/uploadImage',function(req,res){ console.log("IMAGE TO SERVER",req.body) cloudinary.uploader.upload(req.body.image,{tags:'basic_sample'}) .then(function(image){ console.log("OPEN IMAGE",image) res.json({url : image.url}) }) }); //********* Fetch all registered users app.get('/api/allRegisteredArtists',function(req,res){ new Artist().fetchAll().then((allArtists)=>{ res.status(302).json({registeredArtists : allArtists.models}) }) }) //***************** Create Artist User Relation app.post('/api/subscribeToArtist',function(req,res){ console.log("SUBSCRIBE CALLED",req.body) var data = req.body; new Artist_User({ artist_id: data.artist_id, user_id: data.user_id }) .save() .then(function(data){ console.log("RELATIONSHIP MADE",data) res.json({data : 'Subscribed successfully'}); }) }) //************** Get all artist subscribers app.get('/api/emailAllSubscribers',function(req,res){ var data = [] Artist_User.query({where: {artist_id :req.query.artist_id }}).fetchAll().then(function(emails){ emails.models.map(function(user_id){ User.query({where : {id : user_id.attributes.user_id}}).fetch().then(function(model){ sendEmailTo(model.get('email_id'),req.query.artist_name,req,res) }) }) }); res.json("EMAIL SENDING") }); //************NODE EMAIL var emailJS = require('emailjs/email') var sendmail = emailJS.server.connect({ user: CONFIG.G_MAIL_ADDRESS, password: CONFIG.G_PASSWORD, host: "smtp.gmail.com", ssl: true }); function sendEmailTo (email_id,artist_name,req,res){ console.log("SEND EMAIL TO CALLED WITH " + email_id + " and " + artist_name) var message = { from: "GIGG.TV <teamdreamstream4@gmail.com>", to: "User <" + email_id + ">", subject: artist_name + " IS LIVE NOW!", text: "Click on gigg.tv/router/activeStream/" + artist_name + " . Join in for a good time" }; sendmail.send(message, function (err, message) { var body = null; if (err) { body = err.toString(); console.log("ERROR IN SENDING EMAIL",body) } else { console.log("EMAIL SENT IN SERVER") } }); } //******* Test Chat ************** //set env vars // var mongoose= require('mongoose'); // process.env.MONGOLAB_URI = process.env.MONGOLAB_URI || 'mongodb://localhost/chat_dev'; // process.env.PORT = process.env.PORT || 3000; // connect our DB // mongoose.connect(process.env.MONGOLAB_URI); //load routers var messageRouter = express.Router(); require('./server/routes/message_routes.js')(messageRouter); app.use('/api', messageRouter); var socketioJwt= require('socketio-jwt'); io.set('transports', ["websocket", "polling"]); io.on('connection', function (socket){ console.log('a user connected'); socket.join('Lobby'); socket.on('chat mounted', function(user) { console.log('socket heard: chat mounted...user is: ', user); // TODO: Does the server need to know the user? socket.emit('receive socket', socket.id) }) socket.on('leave channel', function(channel) { socket.leave(channel) }) socket.on('join channel', function(channel) { socket.join(channel.name) }) socket.on('new message', function(msg) { socket.broadcast.to(msg.channelID).emit('new bc message', msg); }); socket.on('new channel', function(channel) { socket.broadcast.emit('new channel', channel) }); socket.on('typing', function (data) { socket.broadcast.to(data.channel).emit('typing bc', data.user); }); socket.on('stop typing', function (data) { socket.broadcast.to(data.channel).emit('stop typing bc', data.user); }); }); //********* End Test Chat ********** app.get('*', function (request, response){ response.sendFile(path.resolve(__dirname, 'client', 'index.html')) }) module.exports.server = server;
AuggieH/GigRTC
server.js
JavaScript
mit
17,392
/* * grunt-github-changes * https://github.com/streetlight/grunt-github-changes * * Copyright (c) 2014 Nick Weingartner * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { // load all npm grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js' ], options: { jshintrc: '.jshintrc' } }, // Configuration to be run (and then tested). githubChanges: { dist: { options: { owner : 'streetlight', repository : 'grunt-github-changes', file : 'CHANGELOG.md', useCommitBody : true } } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['githubChanges']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
JSMike/grunt-github-changes
Gruntfile.js
JavaScript
mit
1,107
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Klassificerat skjutreglage f\u00f6r f\u00e4rg"});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/smartMapping/ClassedColorSlider/nls/sv/ClassedColorSlider.js
JavaScript
mit
227
import { setupRenderingTest } from 'ember-qunit'; import { module, test } from 'qunit'; import { hbs } from 'ember-cli-htmlbars'; import { click, render, settled } from '@ember/test-helpers'; module('Integration | Component | bs-alert', (hooks) => { setupRenderingTest(hooks); test('check has button', async function(assert) { this.set('dismissible', true); await render(hbs`<Bs::Alert @dismissible={{this.dismissible}}/>`); assert.equal(this.element.querySelector('a') !== null, true, 'no close button'); assert.equal(this.element.querySelector('div.alert.in') !== null, true, 'alert is showing'); this.set('dismissible', false); assert.equal(this.element.querySelector('a') , null, 'dismiss is false and close button is not displayed'); }); test('trigger close action', async function(assert) { this.set('dismissed', (actual) => { assert.ok(true, 'external Action was called!'); }); await render(hbs`<Bs::Alert @dismissible={{true}} @onDismiss={{fn this.dismissed}} />`); await click('a.close'); assert.equal(this.element.querySelector('div.alert.in'), null, 'alert should not show'); }); test('auto dismiss', async function(assert) { await render(hbs`<Bs::Alert @dismissAfter={{0.1}} />`); assert.ok(this.element.querySelector('div.alert.in') === null, 'alert should not show'); }); });
patricklx/ember-cli-bscomponents
tests/integration/components/bs-alert-test.js
JavaScript
mit
1,373
import all from './all'; import loadCss from './loadCss'; import loadScript from './loadScript'; const dt = 'https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js'; export default function loadDataTables() { return all([loadScript(dt), loadCss(defineDataTablesPath)]); // eslint-disable-line no-undef }
fallenswordhelper/fallenswordhelper
src/modules/common/loadDataTables.js
JavaScript
mit
316
import Ember from 'ember'; export default Ember.TextArea.extend({ keyDown: function(event) { if (event.which === 13 && ! event.shiftKey) { // Don't insert newlines when submitting with enter event.preventDefault(); } }, // This next bit lets you add newlines with shift+enter without submitting insertNewline: function(event) { if (! event.shiftKey) { // Do not trigger the "submit on enter" action if the user presses // SHIFT+ENTER, because that should just insert a new line this._super(event); } }, });
kaelig/wordset-ui
app/components/multi-box.js
JavaScript
mit
623
const http = window.http; const handlebars = window.handlebars || window.Handlebars; ((scope) => { scope.templates = { getByUrl(url) { return http.get(url) .then((templateHtml) => { const templateFunc = handlebars.compile(templateHtml); return templateFunc; }); }, get(name) { const url = `/public/templates/${name}.hbs`; return this.getByUrl(url); }, getModal(type) { const url = `/public/modals/${type}.hbs`; return this.getByUrl(url); }, getPage(name) { const url = `/public/pages/${name}/${name}.hbs`; return this.getByUrl(url); } }; })(window);
VenelinGP/Gemstones
src/public/js/utils/templates.js
JavaScript
mit
779
/** * @internalapi * @module params */ /** for typedoc */ import { extend, filter, map, applyPairs, allTrueR } from "../common/common"; import { prop, propEq } from "../common/hof"; import { isInjectable, isDefined, isString, isArray } from "../common/predicates"; import { services } from "../common/coreservices"; import { ParamType } from "./paramType"; var hasOwn = Object.prototype.hasOwnProperty; var isShorthand = function (cfg) { return ["value", "type", "squash", "array", "dynamic"].filter(hasOwn.bind(cfg || {})).length === 0; }; export var DefType; (function (DefType) { DefType[DefType["PATH"] = 0] = "PATH"; DefType[DefType["SEARCH"] = 1] = "SEARCH"; DefType[DefType["CONFIG"] = 2] = "CONFIG"; })(DefType || (DefType = {})); function unwrapShorthand(cfg) { cfg = isShorthand(cfg) && { value: cfg } || cfg; return extend(cfg, { $$fn: isInjectable(cfg.value) ? cfg.value : function () { return cfg.value; } }); } function getType(cfg, urlType, location, id, paramTypes) { if (cfg.type && urlType && urlType.name !== 'string') throw new Error("Param '" + id + "' has two type configurations."); if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type)) return paramTypes.type(cfg.type); if (urlType) return urlType; if (!cfg.type) { var type = location === DefType.CONFIG ? "any" : location === DefType.PATH ? "path" : location === DefType.SEARCH ? "query" : "string"; return paramTypes.type(type); } return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type); } /** * returns false, true, or the squash value to indicate the "default parameter url squash policy". */ function getSquashPolicy(config, isOptional, defaultPolicy) { var squash = config.squash; if (!isOptional || squash === false) return false; if (!isDefined(squash) || squash == null) return defaultPolicy; if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); } function getReplace(config, arrayMode, isOptional, squash) { var replace, configuredKeys, defaultPolicy = [ { from: "", to: (isOptional || arrayMode ? undefined : "") }, { from: null, to: (isOptional || arrayMode ? undefined : "") } ]; replace = isArray(config.replace) ? config.replace : []; if (isString(squash)) replace.push({ from: squash, to: undefined }); configuredKeys = map(replace, prop("from")); return filter(defaultPolicy, function (item) { return configuredKeys.indexOf(item.from) === -1; }).concat(replace); } var Param = (function () { function Param(id, type, config, location, urlMatcherFactory) { config = unwrapShorthand(config); type = getType(config, type, location, id, urlMatcherFactory.paramTypes); var arrayMode = getArrayMode(); type = arrayMode ? type.$asArray(arrayMode, location === DefType.SEARCH) : type; var isOptional = config.value !== undefined || location === DefType.SEARCH; var dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic; var raw = isDefined(config.raw) ? !!config.raw : !!type.raw; var squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy()); var replace = getReplace(config, arrayMode, isOptional, squash); var inherit = isDefined(config.inherit) ? !!config.inherit : !!type.inherit; // array config: param name (param[]) overrides default settings. explicit config overrides param name. function getArrayMode() { var arrayDefaults = { array: (location === DefType.SEARCH ? "auto" : false) }; var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; return extend(arrayDefaults, arrayParamNomenclature, config).array; } extend(this, { id: id, type: type, location: location, isOptional: isOptional, dynamic: dynamic, raw: raw, squash: squash, replace: replace, inherit: inherit, array: arrayMode, config: config, }); } Param.prototype.isDefaultValue = function (value) { return this.isOptional && this.type.equals(this.value(), value); }; /** * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the * default value, which may be the result of an injectable function. */ Param.prototype.value = function (value) { var _this = this; /** * [Internal] Get the default value of a parameter, which may be an injectable function. */ var $$getDefaultValue = function () { if (!services.$injector) throw new Error("Injectable functions cannot be called at configuration time"); var defaultValue = services.$injector.invoke(_this.config.$$fn); if (defaultValue !== null && defaultValue !== undefined && !_this.type.is(defaultValue)) throw new Error("Default value (" + defaultValue + ") for parameter '" + _this.id + "' is not an instance of ParamType (" + _this.type.name + ")"); return defaultValue; }; var $replace = function (val) { var replacement = map(filter(_this.replace, propEq('from', val)), prop("to")); return replacement.length ? replacement[0] : val; }; value = $replace(value); return !isDefined(value) ? $$getDefaultValue() : this.type.$normalize(value); }; Param.prototype.isSearch = function () { return this.location === DefType.SEARCH; }; Param.prototype.validates = function (value) { // There was no parameter value, but the param is optional if ((!isDefined(value) || value === null) && this.isOptional) return true; // The value was not of the correct ParamType, and could not be decoded to the correct ParamType var normalized = this.type.$normalize(value); if (!this.type.is(normalized)) return false; // The value was of the correct type, but when encoded, did not match the ParamType's regexp var encoded = this.type.encode(normalized); return !(isString(encoded) && !this.type.pattern.exec(encoded)); }; Param.prototype.toString = function () { return "{Param:" + this.id + " " + this.type + " squash: '" + this.squash + "' optional: " + this.isOptional + "}"; }; Param.values = function (params, values) { if (values === void 0) { values = {}; } return params.map(function (param) { return [param.id, param.value(values[param.id])]; }).reduce(applyPairs, {}); }; /** * Finds [[Param]] objects which have different param values * * Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects * * @param params: The list of Param objects to filter * @param values1: The first set of parameter values * @param values2: the second set of parameter values * * @returns any Param objects whose values were different between values1 and values2 */ Param.changed = function (params, values1, values2) { if (values1 === void 0) { values1 = {}; } if (values2 === void 0) { values2 = {}; } return params.filter(function (param) { return !param.type.equals(values1[param.id], values2[param.id]); }); }; /** * Checks if two param value objects are equal (for a set of [[Param]] objects) * * @param params The list of [[Param]] objects to check * @param values1 The first set of param values * @param values2 The second set of param values * * @returns true if the param values in values1 and values2 are equal */ Param.equals = function (params, values1, values2) { if (values1 === void 0) { values1 = {}; } if (values2 === void 0) { values2 = {}; } return Param.changed(params, values1, values2).length === 0; }; /** Returns true if a the parameter values are valid, according to the Param definitions */ Param.validates = function (params, values) { if (values === void 0) { values = {}; } return params.map(function (param) { return param.validates(values[param.id]); }).reduce(allTrueR, true); }; return Param; }()); export { Param }; //# sourceMappingURL=param.js.map
suryagangula/empower
node_modules/ui-router-visualizer/node_modules/ui-router-core/lib-esm/params/param.js
JavaScript
mit
8,540
var app = angular.module('xapp', []); app.controller('xctrl', function ($scope){ $scope.operate = function (code){ var a = +$scope.obj1; var b = +$scope.obj2; switch (code){ case 1: $scope.operation = "ADD"; $scope.result = a + b; break; case 2: $scope.operation = "SUBSTRATION"; $scope.result = a - b; break; case 3: $scope.operation = "MULTIPLY"; $scope.result = a * b; break; case 4: $scope.operation = "DIVIDE"; $scope.result = a / b; break; } }; });
windupurnomo/AngularJS-Lab
calculator/app.js
JavaScript
mit
533
// flow-typed signature: dec19d167515fb1b5b5d33fcce0c7446 // flow-typed version: <<STUB>>/react-timer-mixin_v^0.13.3/flow_v0.45.0 /** * This is an autogenerated libdef stub for: * * 'react-timer-mixin' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'react-timer-mixin' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'react-timer-mixin/__tests__/TimerMixin-test' { declare module.exports: any; } declare module 'react-timer-mixin/TimerMixin' { declare module.exports: any; } // Filename aliases declare module 'react-timer-mixin/__tests__/TimerMixin-test.js' { declare module.exports: $Exports<'react-timer-mixin/__tests__/TimerMixin-test'>; } declare module 'react-timer-mixin/TimerMixin.js' { declare module.exports: $Exports<'react-timer-mixin/TimerMixin'>; }
olinlibrary/signage
flow-typed/npm/react-timer-mixin_vx.x.x.js
JavaScript
mit
1,139
const GameObject = require('./GameObject'); const GameObjects = require('./'); const GameError = require('../Errors').GameError; const GameState = require('./GameState'); const ObjectStore = require('./ObjectStore'); const Promise = require('bluebird'); const chance = new (require('chance'))(); const PLAYERS_LOWER_LIMIT = 3; /** * Class representing a single instance of the game * @extends {GameObject} */ class Game extends GameObject { /** * Construct a Game * @param {object} opts The options to use when creating this game. * @param {string} opts.name The name of this game. * @param {Player} opts.owner The player who created this game. * @param {ObjectStore} opts.store The ObjectStore we should use. */ constructor(opts) { super(opts); this.name = opts.name; this.owner = opts.owner; this.store = opts.store; // initialize players as an array with the owner of the game in it. this._players = [this.owner]; // initialize cardPacks as an empty array, to be filled later. this._cardPacks = []; this._state = GameState.INITIALIZING; this._currentCzar = null; } /** * The name of this game. * @type {string} */ get name() { return this._name; } // eslint-disable-next-line require-jsdoc set name(value) { if(!value) { throw new GameError(this.__('errors.general.no-name'), this.uuid); } this._name = value; } /** * The GameState this game is currently in. * @return {GameState} */ get state() { return this._state; } // eslint-disable-next-line require-jsdoc set state(value) { if(!(value || value === 0)) { throw new GameError(this.__('errors.game.no-state')); } if(value <= this.state || value > GameState.FINISHED) { throw new GameError(this.__('errors.game.invalid-state-change')); } this._state = value; } /** * The player who owns this game. Normally the player who created the game, * but ownership is passed to another player if the current owner leaves the * game. * @return {Player} */ get owner() { return this._owner; } // eslint-disable-next-line require-jsdoc set owner(value) { if(!value) { throw new GameError(this.__('errors.game.no-owner'), this.uuid); } if(!(value instanceof GameObjects.Player)) { throw new GameError(this.__('errors.game.non-player'), this.uuid); } this._owner = value; } /** * The <tt>ObjectStore</tt> that this game has access to. * @return {ObjectStore} */ get store() { return this._store; } // eslint-disable-next-line require-jsdoc set store(value) { if(!value) { throw new GameError(this.__('errors.game.no-object-store'), this.uuid); } if(!(value instanceof ObjectStore)) { throw new GameError(this.__('errors.game.non-object-store'), this.uuid); } this._store = value; } /** * The players who have joined this game. * @return {Player[]} */ get players() { return this._players; } /** * Add a player to this game. Can only be done when the game is not in the * <tt>FINISHED</tt> state. * @param {string} plrUUID The UUID of the player to add. */ addPlayer(plrUUID) { if(!(this.isValidState('changePlayers'))) { throw new GameError(this.__('errors.game.player-add'), this.uuid); } let plr = this.store.getObject(plrUUID); if(!plr) { throw new GameError(this.__('errors.game.no-object'), this.uuid); } if(!(plr instanceof GameObjects.Player)) { throw new GameError(this.__('errors.game.uuid-not-player'), this.uuid); } if(!this._players.includes(plr)) { this._players.push(plr); } } /** * Remove a player from this game. Can only be done when the game is not in * the <tt>FINISHED</tt> state. * @param {string} plrUUID The UUID of the player to remove. */ removePlayer(plrUUID) { if(!(this.isValidState('changePlayers'))) { throw new GameError(this.__('errors.game.player-rm'), this.uuid); } for (let i = this._players.length - 1; i >= 0; i--) { if(this._players[i].uuid === plrUUID) { this._players.splice(i, 1); } } if(this.owner.uuid === plrUUID) { if(!this.players.length) { this.state = GameState.FINISHED; return; } this.owner = chance.pickone(this.players); } } /** * The card packs that are included in this game. * @return {CardPack[]} */ get cardPacks() { return this._cardPacks; } /** * Add a card pack to this game. Can only be done when the game is in the * <tt>INITIALIZING</tt> or <tt>WAITING_FOR_PLAYERS</tt> states. * @param {string} packUUID The UUID of the pack to add. */ addCardPack(packUUID) { if(!this.isValidState('changeCardPack')) { throw new GameError(this.__('errors.game.change-pack'), this.uuid); } let pack = this.store.getObject(packUUID); if(!pack) { throw new GameError(this.__('errors.game.no-object'), this.uuid); } if(!(pack instanceof GameObjects.CardPack)) { throw new GameError(this.__('errors.game.uuid-not-pack'), this.uuid); } if(!this._cardPacks.includes(pack)) { this._cardPacks.push(pack); } } /** * Remove a card pack from this game. Can only be done when the game is in the * <tt>INITIALIZING</tt> or <tt>WAITING_FOR_PLAYERS</tt> states. * @param {CardPack} packUUID The UUID of the pack to remove. */ removeCardPack(packUUID) { if(!this.isValidState('changeCardPack')) { throw new GameError(this.__('errors.game.change-pack'), this.uuid); } for (let i = this._cardPacks.length - 1; i >= 0; i--) { if(this._cardPacks[i].uuid === packUUID) { this._cardPacks.splice(i, 1); } } } /** * Decides whether or not the game is in a valid state for particular action. * @param {string} action The action to be checked. * @return {Boolean} */ isValidState(action) { let actions = { 'changeCardPack': [ GameState.INITIALIZING, GameState.WAITING_FOR_PLAYERS ], 'changePlayers': [ GameState.INITIALIZING, GameState.WAITING_FOR_PLAYERS, GameState.STARTING, GameState.IN_GAME ], 'startGame': [ GameState.WAITING_FOR_PLAYERS ] }; if(!action || !actions[action]) { return false; } return actions[action].includes(this.state); } /** * Starts the game. */ start() { if(!this.isValidState('startGame')) { throw new GameError(this.__('errors.game.no-start.invalid-state'), this.uuid); } if(this.players.length < PLAYERS_LOWER_LIMIT) { throw new GameError(this.__('errors.game.no-start.not-enough-players'), this.uuid); } this.state = GameState.STARTING; } /** * Called by the server once all players are connected and we're ready to * start playing the game. This method is in charge of updating all * game-related values during the game. * @return {Promise} */ playGame() { // eslint-disable-next-line promise/avoid-new return new Promise((resolve, reject) => { this.state = GameState.IN_GAME; this._currentCzar = chance.pickone(this.players); resolve(); }); } } module.exports = Game;
CodeAgainstAManatee/Server
lib/GameObjects/Game.js
JavaScript
mit
7,429
'use strict'; /* @flow */ /** * The Root Mean Square (RMS) is * a mean function used as a measure of the magnitude of a set * of numbers, regardless of their sign. * This is the square root of the mean of the squares of the * input numbers. * This runs on `O(n)`, linear time in respect to the array * * @param {Array<number>} x a sample of one or more data points * @returns {number} root mean square * @throws {Error} if x is empty * @example * rootMeanSquare([-1, 1, -1, 1]); // => 1 */ function rootMeanSquare(x /*: Array<number> */)/*:number*/ { if (x.length === 0) { throw new Error('rootMeanSquare requires at least one data point'); } var sumOfSquares = 0; for (var i = 0; i < x.length; i++) { sumOfSquares += Math.pow(x[i], 2); } return Math.sqrt(sumOfSquares / x.length); } module.exports = rootMeanSquare;
kevinmcdonald19/greenr
node_modules/simple-statistics/src/root_mean_square.js
JavaScript
mit
874
var path = require('path'), utils = require('../../lib/utils.js'), promise = require('../../lib/tiny-promise'); /** * Utility methods for working with remote hosts. */ /** * Copies required files for a test run to the designated server location * @param config */ function copyFilesToRemote(config) { // var source = config.localTempFilesPath + '/*'; var source = config.localTempFilesPath; var destination = config.remoteHost + ':' + path.resolve(config.remoteTempFilesPath, '..'); return utils.executeCommand({ cmd: 'scp', args: ['-r', source, destination], isShowingOutput: true }); } function createRemoteTempFolder(config) { return utils.executeCommand({ cmd: 'ssh', args: [config.remoteHost, 'mkdir -p ' + config.remoteTempFilesPath], isShowingOutput: true }); } function launchTestRunner(config) { var launchArg = config.mode === 'remoteContainer' ? 'loadContainer' : ''; return utils.executeCommand({ cmd: 'ssh', args: [config.remoteHost, getTestRunnerPath(config) + ' ' + launchArg], isShowingOutput: true }); } function executeTests(config) { console.log('Copying files to remote'); createRemoteTempFolder(config) .then(function () { copyFilesToRemote(config) .then(function () { //scp files to remote location console.log('Executing remote runner'); launchTestRunner(config); }); }); } function getTestRunnerPath(config) { return path.resolve(config.remoteTempFilesPath, 'test-runner.js'); } module.exports = { executeTests: executeTests };
georgejecook/mocha-ide-runner
mocha-proxy/bin/remote-utils.js
JavaScript
mit
1,530