text
stringlengths 2
6.14k
|
|---|
'use strict';
/**
* Removes server error when user updates input
*/
angular.module('assassinsApp')
.directive('mongooseError', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
element.on('keydown', function() {
return ngModel.$setValidity('mongoose', true);
});
}
};
});
|
'use strict'
module.exports = function fooPost(req, res, next) {
res.header('name', 'foo');
res.header('method', 'post');
res.send(200);
next();
};
|
/*global document, describe, it, expect, require, window, afterEach */
const jQuery = require('jquery');
require('../../src/browser/place-caret-at-end');
describe('placeCaretAtEnd', () => {
'use strict';
let underTest;
afterEach(() => {
underTest.remove();
});
it('works on contenteditable divs', () => {
underTest = jQuery('<span>').html('some text').appendTo('body');
underTest.placeCaretAtEnd();
const selection = window.getSelection(),
range = selection.getRangeAt(0);
expect(selection.type).toEqual('Caret');
expect(selection.rangeCount).toEqual(1);
range.surroundContents(document.createElement('i'));
expect(underTest.html()).toEqual('some text<i></i>');
});
});
|
import store from '../store'
import { mapState } from 'vuex'
import { Scroller, Example } from 'components'
export default {
name: 'Main',
store,
computed: mapState({
name: state => state.name
}),
render() {
const { name } = this
return (
<Scroller>
<Example name={ name } />
</Scroller>
)
}
}
|
export { default as invocationsRoute } from './invocations/index.js'
export { default as invokeAsyncRoute } from './invoke-async/index.js'
|
const {capitalize} = require('../capitalize');
const {expect} = require('chai');
describe('capitalize() Capitalizes the first letter of a string', function() {
it('should capitalize the first letter of a string', function(){
expect(capitalize("github")).to.equal("Github")
})
})
|
/**
* @file Defines the on-render callback and the event handler for MD Tabs.
* @author Derek Gransaull <derek@dgtlife.com>
* @copyright DGTLife, LLC 2017
*/
import { Template } from 'meteor/templating';
import {
currentTab,
initializeTabGroup,
handleClickOnTab
} from '../../api/md-tabs-api.js';
import './md-tabs.jade';
// On-render callback for MD Tabs.
Template.md_tabs.onRendered(
function onRenderedTabs() {
/*
* Initialize the tab group based on its template configuration, if it has
* not already been initialized (e.g. by restoreTabs)
*/
if (!currentTab.get(this.data.id)) {
initializeTabGroup(this.firstNode);
}
}
);
// Event handler for MD Tabs.
Template.md_tabs.events({
'click .md-tab'(event) {
handleClickOnTab(event.currentTarget);
}
});
|
/*
* Copyright (c) 2013-2016 Chukong Technologies Inc.
*
* 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.
*/
'use strict';
/**
* @type {Object}
* @name jsb.AssetsManager
* jsb.AssetsManager is the native AssetsManager for your game resources or scripts.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.AssetsManager = cc.AssetsManager;
/**
* @type {Object}
* @name jsb.Manifest
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.Manifest = cc.Manifest;
/**
* @type {Object}
* @name jsb.EventListenerAssetsManager
* jsb.EventListenerAssetsManager is the native event listener for AssetsManager.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager;
/**
* @type {Object}
* @name jsb.EventAssetsManager
* jsb.EventAssetsManager is the native event for AssetsManager.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.EventAssetsManager = cc.EventAssetsManager;
jsb.AssetsManager.State = {
UNINITED : 0,
UNCHECKED : 1,
PREDOWNLOAD_VERSION : 2,
DOWNLOADING_VERSION : 3,
VERSION_LOADED : 4,
PREDOWNLOAD_MANIFEST : 5,
DOWNLOADING_MANIFEST : 6,
MANIFEST_LOADED : 7,
NEED_UPDATE : 8,
READY_TO_UPDATE : 9,
UPDATING : 10,
UNZIPPING : 11,
UP_TO_DATE : 12,
FAIL_TO_UPDATE : 13
}
jsb.EventListenerAssetsManager.prototype._ctor = function(assetsManager, callback) {
callback !== undefined && this.init(assetsManager, callback);
};
jsb.Manifest.DownloadState = {
UNSTARTED: 0,
DOWNLOADING: 1,
SUCCESSED: 2,
UNMARKED: 3
};
jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
jsb.EventAssetsManager.ASSET_UPDATED = 6;
jsb.EventAssetsManager.ERROR_UPDATING = 7;
jsb.EventAssetsManager.UPDATE_FINISHED = 8;
jsb.EventAssetsManager.UPDATE_FAILED = 9;
jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_DEFAULT = 0;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_DONE = 1;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_SEND = 2;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_SEARCH = 3;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_GO = 4;
/**
* The EditBox::InputMode defines the type of text that the user is allowed * to enter.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_ANY = 0;
/**
* The user is allowed to enter an e-mail address.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_EMAILADDR = 1;
/**
* The user is allowed to enter an integer value.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_NUMERIC = 2;
/**
* The user is allowed to enter a phone number.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3;
/**
* The user is allowed to enter a URL.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_URL = 4;
/**
* The user is allowed to enter a real number value.
* This extends kEditBoxInputModeNumeric by allowing a decimal point.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_DECIMAL = 5;
/**
* The user is allowed to enter any text, except for line breaks.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_SINGLELINE = 6;
/**
* Indicates that the text entered is confidential data that should be
* obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_PASSWORD = 0;
/**
* Indicates that the text entered is sensitive data that the
* implementation must never store into a dictionary or table for use
* in predictive, auto-completing, or other accelerated input schemes.
* A credit card number is an example of sensitive data.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each word should be capitalized.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each sentence should be capitalized.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3;
/**
* Capitalize all characters automatically.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4;
|
/**
* This file is part of the Unit.js testing framework.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code
* or visit {@link http://unitjs.com|Unit.js}.
*
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
'use strict';
var
RawCommonApi = require('../common_api'), // constructor
rawAssertions = require('../assertions'), // object
_ = require('noder.io')._
;
/**
* Expose all assertions
* @type {function}
* @param {mixed} actual Actual value tested
* @return {Object} The current asserter
*/
module.exports = function BoolAsserter(actual) {
// actual value tested
this.actual = actual;
// assertions with the current context
var assertions = rawAssertions.call(this, actual);
// Build the common API with the current context
var CommonApi = RawCommonApi.bind(this);
var commonApi = new CommonApi();
// provides the common API in the current asserter
for (var method in commonApi) {
this[method] = commonApi[method];
}
// assert the type
assertions.isBool(this.actual);
// provides the assertions to the current asserter
var useAssertions = ['isTrue', 'isNotTrue', 'isFalse', 'isNotFalse'];
var asserterAssertions = _.pick(assertions, useAssertions);
for (var method in asserterAssertions) {
this[method] = asserterAssertions[method];
}
// return this asserter
return this;
};
|
"use strict";
var React = require("react");
var MainView = require("../views/MainView");
var MainElement = document.getElementById("main");
var socket = require("socket.io-client")();
var Store = require("../views/Store");
var omit = require("lodash/object/omit");
socket.on("initialize", function (data) {
Store.league = data.league;
Store.adp = data.adp;
var i = 0,
players = data.players,
total = players.length;
for (; i < total; ++i) {
Store.players[players[i].id] = omit(players[i], ["_id", "id"]);
}
var franchises = data.league.franchises.franchise;
total = franchises.length;
i = 0;
for (; i < total; ++i) {
Store.franchises[franchises[i].id] = omit(franchises[i], ["_id", "id"]);
}
var handleClick = function handleClick(event, callback) {
console.log("deeper click");
var typeStr = event.target.getAttribute("data-target");
socket.emit("client-pull", typeStr, callback);
};
React.render(React.createElement(MainView, { onClick: handleClick }), MainElement);
});
socket.on("data-change", function (data) {
console.log("data-change:", data);
});
|
'use strict';
module.exports = {
name: 'base',
configure: function(config) {
config.addCommand(require('./SwitchTextTypeCommand'));
config.addCommand(require('./UndoCommand'));
config.addCommand(require('./RedoCommand'));
config.addTool(require('./UndoTool'));
config.addTool(require('./RedoTool'));
config.addTool(require('./SwitchTextTypeTool'));
// Icons
config.addIcon('undo', { 'fontawesome': 'fa-undo' });
config.addIcon('redo', { 'fontawesome': 'fa-repeat' });
config.addIcon('edit', { 'fontawesome': 'fa-cog' });
config.addIcon('delete', { 'fontawesome': 'fa-times' });
config.addIcon('expand', { 'fontawesome': 'fa-arrows-h' });
config.addIcon('truncate', { 'fontawesome': 'fa-arrows-h' });
// Labels
config.addLabel('undo', {
en: 'Undo',
de: 'Rückgängig'
});
config.addLabel('redo', {
en: 'Redo',
de: 'Wiederherstellen'
});
config.addLabel('container-selection', {
en: 'Container',
de: 'Container'
});
config.addLabel('container', {
en: 'Container',
de: 'Container'
});
config.addLabel('insert-container', {
en: 'Insert Container',
de: 'Container einfügen'
});
}
};
|
'use strict';
angular.module('core').controller('ShortBreakController', ['$scope', '$interval', 'timer', function ($scope, $interval, timer) {
var initialTime = 300000;
$scope.currentTime = initialTime;
$scope.startTimer = function() {
timer.start($scope);
};
$scope.stopTimer = function() {
timer.stop($scope);
};
$scope.resetTimer = function() {
timer.reset($scope, initialTime);
};
$scope.returnToWorkMessage = function() {
return 1 === 1;
};
}
]);
|
var dest = './public';
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest
},
open: false,
https: false
},
sass: {
src: [
src + '/assets/css/*.{sass,scss}',
src + '/assets/css/**/*.{sass,scss}',
src + '/assets/css/**/**/*.{sass,scss}'
],
dest: dest + '/css',
settings: {
// indentedSyntax: true, // Enable .sass syntax!
imagePath: 'images' // Used by the image-url helper
}
},
browserify: {
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [/*{
entries: src + '/javascript/global.coffee',
dest: dest,
outputName: 'global.js',
// Additional file extentions to make optional
extensions: ['.coffee', '.hbs'],
// list of modules to make require-able externally
require: [ 'jquery', 'backbone/node_modules/underscore' ]
// See https://github.com/greypants/gulp-starter/issues/87 for note about
// why this is 'backbone/node_modules/underscore' and not 'underscore'
}, */{
entries: [ src + '/app/app.module.js' ],
dest: dest + '/js',
outputName: 'app.js',
// list of externally available modules to exclude from the bundle
external: [ 'jquery', 'underscore' ]
}]
},
moveAssets: {
src: [
src + '/*.html',
src + '/app/**/**/*.html',
src + '/assets/libs/*'
],
dest: dest
},
templateCache: {
src: src,
dest: dest
},
jshint: {
src: [
src + '/app/*.js',
src + '/app/**/*.js',
src + '/app/**/**/*.js',
src + '/app/**/**/**/*.js'
]
}
};
|
/*jslint browser: true */
/*global require, app: true, $, Backbone, window, document */
require([
'router'
], function () {
'use strict';
});
|
// run `node syncSchemaDocs.js` from the lib folder to update/add the schema docs that we specify here
// note the relative path to nano module from where this doc is stored.
// currently this script requires the context docs to already exist in couchdb
// if creating/defining a brand new schema doc - use futon or curl to create an otherwise empty doc with the needed "_id" first.
var nano = require('../node_modules/nano')('http://127.0.0.1:5984');
var db = nano.use('patterns');
// specifies the blank json to be sent when GETing /patterns/new
var newPatternSchema = {
"_id": "patternSchema",
"doctype": "schema",
"int_id": null,
"name": "",
"pic": {"b64encoding": "",
"filename": ""
},
"author": [{
"ORCID": "",
"name": ""
}],
"context": "",
"problem": "",
"force": [{
"name": "",
"description": "",
"pic": {
"b64encoding": "",
"filename": ""
}
}
],
"solution": "",
"rationale": "",
"diagram": {
"b64encoding": "",
"filename": ""
},
"evidence": [ {}
],
};
var alpaca = {
"_id": "alpaca",
"schema": {
"title": "Create a new Pattern!",
"type": "object",
"properties": {
"title": {
"type": "string",
"title": "Title"
},
"image": {
"type": "string",
"title": "Select an image to upload..."
}
}
}
};
//schema for vaidating POST to new or PUT to /prototype
var validationSchema = {
"_id": "newPatternValidationSchema",
"doctype": "schema",
"$schema": "http://json-schema.org/schema#",
"title": "New pattern validation schema",
"type": "object",
"items": {
"type": "object",
"properties": {
"doctype":{
"type": "string"
},
"name": {
"type": "string"
},
"pic": {
"type": "object"
},
"author": {
"type": "array"
},
"context": {
"type": "string"
},
"problem": {
"type": "string"
},
"force": {
"type": "array"
},
"solution": {
"type": "string"
},
"rationale": {
"type": "string"
},
"diagram": {
"type": "object"
},
"evidence": {
"type": "array"
}
},
"required": ["doctype", "name", "pic", "author", "context", "problem", "force", "solution", "rationale", "diagram", "evidence"]
}
};
var schemaDocs = [newPatternSchema, validationSchema, alpaca];
//note this function uses an Immediately Invoked Function expression to
// allow async call-back funtions to close properly within the
// for loop. see
// http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/19323214#19323214
// http://learn.jquery.com/javascript-101/functions/#immediately-invoked-function-expression-iife
// http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
function syncDocs() {
for (var x = 0; x < schemaDocs.length; x++) {
//IIFE - anon function will be called on each iteration of the for loop
// we pass in the value of for loop x as index within the anon funct
(function(index){
//we copy the contents of the JSON objects specified above into the temp var doc here
var doc = JSON.parse(JSON.stringify(schemaDocs[index]));
//retreive the doc from couch db
db.get(doc['_id'], function(err, body){
if(!err){
//if OK, set/create temp doc "_rev" field to match current db rev
doc['_rev'] = body['_rev'];
//write the doc
db.insert(doc, function(err, body){
console.log(body);
})
}
else{
// if the db.get fails
console.log(err);
}
//console.log("doc id is "+doc['_id']+" and doc rev is set to "+doc['_rev']);
})
})(x); // we send the for loop iterator x to the (IIFE) anon function above, where it is defined as 'index'
// see IIFE links above
}
}
syncDocs();
|
const ESCAPES = {
u: (flags) => {
flags.lowercaseNext = false
flags.uppercaseNext = true
},
l: (flags) => {
flags.uppercaseNext = false
flags.lowercaseNext = true
},
U: (flags) => {
flags.lowercaseAll = false
flags.uppercaseAll = true
},
L: (flags) => {
flags.uppercaseAll = false
flags.lowercaseAll = true
},
E: (flags) => {
flags.uppercaseAll = false
flags.lowercaseAll = false
},
r: (flags, result) => {
result.push('\\r')
},
n: (flags, result) => {
result.push('\\n')
},
$: (flags, result) => {
result.push('$')
}
}
function transformText (str, flags) {
if (flags.uppercaseAll) {
return str.toUpperCase()
} else if (flags.lowercaseAll) {
return str.toLowerCase()
} else if (flags.uppercaseNext) {
flags.uppercaseNext = false
return str.replace(/^./, s => s.toUpperCase())
} else if (flags.lowercaseNext) {
return str.replace(/^./, s => s.toLowerCase())
}
return str
}
class Insertion {
constructor ({ range, substitution, references }) {
this.range = range
this.substitution = substitution
this.references = references
if (substitution) {
if (substitution.replace === undefined) {
substitution.replace = ''
}
this.replacer = this.makeReplacer(substitution.replace)
}
}
isTransformation () {
return !!this.substitution
}
makeReplacer (replace) {
return function replacer (...match) {
let flags = {
uppercaseAll: false,
lowercaseAll: false,
uppercaseNext: false,
lowercaseNext: false
}
replace = [...replace]
let result = []
replace.forEach(token => {
if (typeof token === 'string') {
result.push(transformText(token, flags))
} else if (token.escape) {
ESCAPES[token.escape](flags, result)
} else if (token.backreference) {
let transformed = transformText(match[token.backreference], flags)
result.push(transformed)
}
})
return result.join('')
}
}
transform (input) {
let { substitution } = this
if (!substitution) { return input }
return input.replace(substitution.find, this.replacer)
}
}
module.exports = Insertion
|
// @ag-grid-community/react v25.1.0
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=interfaces.js.map
|
/*
Copyright (c) 2009-2011, Dan "Ducky" Little & GeoMOOSE.org
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.
*/
dojo.require('dojo.fx');
dojo.require('dijit.layout.BorderContainer');
dojo.require('dijit.layout.TabContainer');
dojo.require('dojox.widget.Standby');
dojo.registerModulePath('GeoMOOSE', '../../../geomoose/GeoMOOSE');
dojo.require('GeoMOOSE.Popup');
dojo.require('GeoMOOSE.Application');
dojo.require('GeoMOOSE.Handler.Box');
dojo.require('GeoMOOSE.Handler.MeasurePath');
dojo.require('GeoMOOSE.Control.Measure');
dojo.require('GeoMOOSE.Control.DeleteFeature');
dojo.require('GeoMOOSE.Dialog.AttributeEditor');
dojo.require('GeoMOOSE.Dialog.Download');
dojo.require('GeoMOOSE.MapSource');
dojo.require('GeoMOOSE.MapSource.Vector');
dojo.require('GeoMOOSE.MapSource.Vector.WFS');
dojo.require('GeoMOOSE.MapSource.WMS');
dojo.require('GeoMOOSE.MapSource.MapServer');
dojo.require('GeoMOOSE.MapSource.TMS');
dojo.require('GeoMOOSE.MapSource.XYZ');
dojo.require('GeoMOOSE.MapSource.Google');
dojo.require('GeoMOOSE.MapSource.AGS');
dojo.require('GeoMOOSE.Tab');
dojo.require('GeoMOOSE.Tab.Service');
dojo.require('GeoMOOSE.Tab.Catalog');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Activate');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Popups');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Up');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Fade');
dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Legend');
dojo.require('GeoMOOSE.ServiceManager');
dojo.require('GeoMOOSE.UI.Toolbar');
dojo.require('GeoMOOSE.Layout.Default');
dojo.require('GeoMOOSE.UI.CoordinateDisplay');
dojo.require('GeoMOOSE.UI.ScaleJumper');
dojo.require('GeoMOOSE.UI.ZoomTo');
dojo.require('GeoMOOSE.UI.LinksBar');
dojo.require('GeoMOOSE.Tool.MeasureArea');
|
angular
.module('platoon.event', [])
.controller('EventController', ['$scope', '$location', '$filter',
function($scope, $location, $filter)
{
$scope.eventTypes = [{
label: 'Private',
type: 'private'
},{
label: 'Company',
type: 'company'
},{
label: 'Wedding',
type: 'wedding'
},{
label: 'Student',
type: 'student'
}
];
$scope.add = {};
$scope.add.djs = {
djs: [],
add: function(dj) {
$scope.$evalAsync(function() {
$scope.add.djs.djs.push(dj);
$scope.add.djs.current = '';
}.bind(this));
},
remove: function(event) {
var target = $(event.target).find(':selected');
if (target.length > 0 && event.which === 8 || event.which === 46) {
event.preventDefault();
event.stopPropagation();
var dj = target.html();
for (var i = 0; i < this.djs.length; i++) {
if (this.djs[i] == dj) {
this.djs.splice(i, 1);
break;
}
}
}
},
engine: {
name: 'djs',
source: new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
local: ['Max', 'Arvid', 'Roshan', 'Amanda', 'Robin']
})
}
};
$scope.add.type = $scope.eventTypes[0].type;
$scope.add.phone = '';
$scope.add.layout = 'standard';
$scope.$watch(function() {
return $scope.add.phone;
}, function(val) {
if (val != null) $scope.add.phone = $filter('phoneNumber')(val);
});
}]);
|
/*
© Copyright Adam Aharony (a.k.a. Cringy Adam)
All rights reserved
Twitter: @AdamAharony, Discord: @Cringy Adam#4611
*/
exports.run = (client, message, args) => {
message.delete();
message.channel.send('', {
embed: {
author: {
name: client.user.username
},
color: 0x008AF3,
title: "CringyBot Selfbot edition info:",
description: 'This selfbot is made by Adam Aharony (bot origionally from @XeliteXirish (a.k.a. Cringy Adam).\n(Twitter: @AdamAharony)\nAiming to make the discord experience much better.\nSpecial thanks to Jayden#5395 for helping me with some commands.',
timestamp: new Date(),
footer: {
text: 'CringyBot Selfbot edition',
icon_url: client.user.avatarURL
}
}
});
};
|
'use strict';
/**
* This contains a promisified confirmation question
*/
module.exports = function(kbox) {
// Npm modules
var inquirer = require('inquirer');
// Kbox modules
var Promise = require('bluebird');
/*
* Make sure the user wants to proceed with the install/update
*/
return function(state) {
// Set up our confirmation question
var confirm = {
type: 'confirm',
name: 'doit',
message: 'Install all the magic and get this party started?',
when: function(answers) {
return !state.nonInteractive;
}
};
// Kick off a promise for this
return new Promise(function(resolve) {
return inquirer.prompt([confirm], function(answers) {
// Log our answers
state.log.debug('USER INPUT => ' + JSON.stringify(answers));
// Return our answers
return resolve(answers);
});
});
};
};
|
/**
* butterItemFilterField is a jQuery plugin that filters html element with the css class <code>filterable-item</code>.
* It is applied to the search field.<br/>
* If no filter text is entered, then all filterable-items are displayed. Else the search field value is matched against <b>all</b> text contained by a filterable-item.
*
* How to use:
* jQuery("#someInputSelector").butterItemFilterField();
*
* Author: Yann Massard
*/
(function ($) {
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
// extend jQuery --------------------------------------------------------------------
$.fn.butterItemFilterField = function (filterableItemContainerSelector) {
return this.each(function () {
var $this = $(this);
$this.keyup(function () {
delay(function () {
var filterValue = $this.val();
// find container again every time, because it could have been rerendered.
var $filterableItemContainer;
if (filterableItemContainerSelector) {
$filterableItemContainer = $(filterableItemContainerSelector);
} else {
var containerSelector = $this.attr('data-filterable-item-container');
$filterableItemContainer = $(containerSelector);
}
var filterableItems = $filterableItemContainer.find('.filterable-item');
filterableItems.each(function (i, elem) {
var $filterableItem = $(elem);
if ($filterableItem.is(':containsIgnoreCase(' + filterValue + ')')) {
$filterableItem.removeAttr("hidden");
$filterableItem.highlight(filterValue);
} else {
$filterableItem.attr("hidden", "hidden");
}
});
}, 300);
});
});
};
}(jQuery));
(function ($) {
$.expr[":"].containsIgnoreCase = $.expr.createPseudo(function (arg) {
return function (elem) {
return !arg || $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
}(jQuery));
|
var translations = {
'Mostri spaziali': {
en: 'Space monsters',
},
'Dettagli': {
en: 'Details',
},
'Testa': {
en: 'Head',
},
'Occhi': {
en: 'Eyes',
},
'Naso': {
en: 'Nose',
},
'Bocca': {
en: 'Mouth',
},
'Orecchie': {
en: 'Ears',
},
'Fantasmatico': {
en: 'InHideum',
},
'Allegro': {
en: 'Happy',
},
'Orribile': {
en: 'Franken',
},
'Schifoso': {
en: 'Zombus',
},
'Bizzarro': {
en: 'Wackus',
},
'Smorfioso': {
en: 'Vegitas',
},
'Spiritato': {
en: 'Spritem',
},
'Crea un mostro a caso': {
en: 'Create a random monster',
},
'Come si chiama?': {
en: 'What\'s his name?',
},
'Mostro numero': {
en: 'Monster number',
},
'Stampa per giocare': {
en: 'Print to play',
},
'Maggiori info su code.org': {
en: 'More info on code.org',
},
'Lingua': {
en: 'Language',
}
};
|
// Fuzzy utility
'use strict';
var filter = require('array-filter');
var fuzzy = function(items, key) {
return function (query) {
query = query.toLowerCase();
var re = new RegExp(query, 'i');
return filter(items, function(item) {
return re.test(item[key]);
});
};
};
module.exports = fuzzy;
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var AssistantList = require('./understand/assistant').AssistantList;
var Version = require('../../base/Version'); /* jshint ignore:line */
/* jshint ignore:start */
/**
* Initialize the Understand version of Preview
*
* @constructor Twilio.Preview.Understand
*
* @property {Twilio.Preview.Understand.AssistantList} assistants -
* assistants resource
*
* @param {Twilio.Preview} domain - The twilio domain
*/
/* jshint ignore:end */
function Understand(domain) {
Version.prototype.constructor.call(this, domain, 'understand');
// Resources
this._assistants = undefined;
}
_.extend(Understand.prototype, Version.prototype);
Understand.prototype.constructor = Understand;
Object.defineProperty(Understand.prototype,
'assistants', {
get: function() {
this._assistants = this._assistants || new AssistantList(this);
return this._assistants;
}
});
module.exports = Understand;
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'font', 'sv', {
fontSize: {
label: 'Storlek',
voiceLabel: 'Teckenstorlek',
panelTitle: 'Teckenstorlek'
},
label: 'Typsnitt',
panelTitle: 'Typsnitt',
voiceLabel: 'Typsnitt'
} );
|
function ConnectionList(){
this.client = {};
this.add = function(id, value){
if( id )
this.client[id] = value;
else
throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;";
}
this.remove = function(id){
delete this.client[id];
}
this.clear = function(){
delete this.client;
this.client = {};
}
this.length = function(){
return Object.keys( this.client ).length;
}
this.get = function(id){
return this.client[id];
}
this.find = function(id){
if (this.client[id] == undefined)
return false
else
return true;
}
this.getAll = function(){
return Object.values(this.client);
}
this.broadcast = function(evt, msg){
for (var key in this.client) {
this.client[key].socket.emit(evt, msg);
}
}
this.getData = function(id){
return this.client[id].data;
}
this.getAllData = function(evt, msg){
var array = [];
for (var key in this.client) {
array.push( this.client[key].data );
}
return array;
}
this.getAllDataObj = function(evt, msg){
var obj = {};
for (var key in this.client) {
obj[key] = this.client[key].data;
}
return obj;
}
this.clone = function(){
var list = new ConnectionList();
for (var key in this.client) {
list.add( key, this.client[key] );
}
return list;
}
}
module.exports = ConnectionList;
|
import React from 'react';
const Footer = () => (
<div className="col s12 home-inner footer" >
<div className="inner-content center m-auto">
<p> Copyright © 2017 Andela24 News - All rights reserved </p>
</div>
</div>
);
export default Footer;
|
import chai, { expect } from 'chai'
import chaiHttp from 'chai-http'
import server from '../src/index'
import Query from '../src/query'
import { url } from '../src/resources'
chai.use(chaiHttp)
export default (done) =>
{
Query.create({title: 'Task', completed: true})
.then((task) => {
task.title = 'Tarefa Alterada'
chai.request(server.info.uri)
.put(url)
.send(task)
.end((err, res) => {
expect(res).to.have.status(200)
expect(res.body).to.not.be.null
expect(res.body).to.have.property('title')
expect(res.body.title).to.equal('Tarefa Alterada')
done()
})
})
.error((err) => { done(err) })
}
|
/**
@module ember
@submodule ember-htmlbars
*/
/**
An HTMLBars AST transformation that replaces all instances of
```handlebars
{{#with foo.bar as bar}}
{{/with}}
```
with
```handlebars
{{#with foo.bar keywordName="bar"}}
{{/with}}
```
@private
@class TransformWithAsToHash
*/
function TransformWithAsToHash() {
// set later within HTMLBars to the syntax package
this.syntax = null;
}
/**
@private
@method transform
@param {AST} The AST to be transformed.
*/
TransformWithAsToHash.prototype.transform = function TransformWithAsToHash_transform(ast) {
var pluginContext = this;
var walker = new pluginContext.syntax.Walker();
var b = pluginContext.syntax.builders;
walker.visit(ast, function(node) {
if (pluginContext.validate(node)) {
var removedParams = node.sexpr.params.splice(1, 2);
var keyword = removedParams[1].original;
// TODO: This may not be necessary.
if (!node.sexpr.hash) {
node.sexpr.hash = b.hash();
}
node.sexpr.hash.pairs.push(b.pair(
'keywordName',
b.string(keyword)
));
}
});
return ast;
};
TransformWithAsToHash.prototype.validate = function TransformWithAsToHash_validate(node) {
return node.type === 'BlockStatement' &&
node.sexpr.path.original === 'with' &&
node.sexpr.params.length === 3 &&
node.sexpr.params[1].type === 'PathExpression' &&
node.sexpr.params[1].original === 'as';
};
export default TransformWithAsToHash;
|
var clientElasticsearch = require("../../../Elasticsearch/ElasticsearchClient");
var ElasticsearchParser = require("../../../Elasticsearch/ElasticsearchParser");
var Q = require('q');
var getSuggestions=function(){
return clientElasticsearch.search({
"index":"source",
"type":"zabbix_host",
"body":{
"query" : {
"term": { "haveMapping" : false}
},
"fields" : ["id","hostname"]
},
"from":0,
"size":999999999,
"scroll" : "1m"
}).then(function(body){
// Récuparation de la recherche en liste
return ElasticsearchParser.loadFromBodyFields(body);
}).then(function(results){
var retour=[];
results.forEach(function(host){
retour.push({
"response_id" : host.id,
"response_label" : host.hostname,
"target": [
{
"label" : host.hostname
}
]
});
});
return retour;
});
}
module.exports = getSuggestions;
|
var app = app || {};
$(function() { //when DOM is ready...
if ( app.user_session ) {
console.log( "%csession" , "font-size: 2em; color: rgba(100,100,200,1.0);" );
} else {
console.log( "%cno session" , "font-size: 2em; color: rgba(200,100,100,1.0);" );
}
app.profile_content = new ProfileCollection();
app.project_content = new ProjectCollection();
app.router = new App.Router({
user_session: app.user_session ,
logged_user: app.logged_user,
logged_user_key: app.logged_user_key,
profiles: app.profile_content ,
projects: app.project_content
});
//This sets up routes with hashtags. Like /#blog , /#products , /#users
Backbone.history.start();
//This sets up routes with hashtags. Like /blog , /products , /users
//Backbone.history.start({ pushState: true });
});
|
/**
* @module components
*
*/
import $ from 'jquery';
import { assert } from '@ember/debug';
import { dasherize } from '@ember/string';
import EmberObject, { get, set } from '@ember/object';
import { isNone, isEmpty } from '@ember/utils';
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import layout from '../templates/components/bc-tabs';
import parse from '../utils/parse';
/***/
const TAB_CONTENT = '.--bc-tabs-content';
function getQueryParams() {
// get url search params
let search = window.location.search.slice(1);
// parse params to an object
let params = {};
if (!isEmpty(search)) {
params = parse(search);
}
// return params
return params;
}
function getTabFromQueryParams(params=null) {
// get params if none are passed in
if (params === null) {
params = getQueryParams();
}
// get tab if the tab is not an emptry string or array and
// the tab is not null or undefined
// otherwise return '' (empty string)
if (!isEmpty(get(params, 'bc_tab'))) {
return dasherize(get(params, 'bc_tab'));
}
return null;
}
/**
* `Component/BCTabs`
*
* @class BCTabs Component
* @extends Ember.Component
*/
export default Component.extend({
layout: layout,
classNames: ['--bc-tabs'],
router: service(),
useRouter: true,
/**
* variable for tracking tabNames, is an array
*
* @property model
* @type object[]
*/
model: null,
defaultTab: '',
currentTab: '',
hashName: '',
firstRender: false,
init() {
this._super();
this.handleHash();
},
didRender() {
this._super();
if (!get(this, 'firstRender')) {
set(this, 'firstRender', true);
let model = this.buildTabData();
if (!isEmpty(model)) {
if (isEmpty(get(this, 'defaultTab'))) {
let ftab = model.filterBy('isViewable', true).get('firstObject');
set(this, 'defaultTab', get(ftab, 'id'));
}
let activeTab;
if (!isEmpty(get(this, 'hashName'))) {
activeTab = model.findBy('id', get(this, 'hashName'));
}
if (isNone(activeTab) && !isEmpty(get(this, 'defaultTab'))) {
activeTab = model.findBy('id', get(this, 'defaultTab'));
if (isNone(activeTab)) {
activeTab = model.filterBy('isViewable', true).get('firstObject');
set(this, 'defaultTab', get(activeTab, 'id'));
}
}
this.openTab(activeTab);
}
}
},
buildTabData() {
assert('buildTabData must be called after render', this.$().length > 0);
let model = [];
this.$(TAB_CONTENT).children().each((index, el) => {
let elData = $(el).data();
let data = EmberObject.create({
el, id: elData.id,
active: false,
tabName: elData.tabName,
tabIndex: elData.tabIndex,
isViewable: elData.isViewable,
showBadge: elData.showBadge,
badgeContent: elData.badgeContent,
badgeColor: elData.badgeColor,
showTab() {
set(this, 'active', true);
elData.showTab();
},
hideTab() {
set(this, 'active', false);
elData.hideTab();
},
on: elData.on,
});
// register for child events
data.on('change', () => {
this.buildTabData();
});
model.push(data);
});
if (get(model, 'length') > 0) {
// sort models by tabIndex
model = model.sortBy('tabIndex');
}
set(this, 'model', model);
return model;
},
handleHash() {
const hash = window.location.hash;
if (!isEmpty(hash) && hash.search(/^#tab-/) !== -1) {
const name = dasherize(hash.replace(/^#tab-/, '').trim());
set(this, 'hashName', name);
} else {
set(this, 'hashName', getTabFromQueryParams());
}
},
openTab(tab) {
if (this.$().length > 0) {
// hide all other tabs
get(this, 'model').forEach(item => item.hideTab());
// show the new tab
tab.showTab();
let tabname = get(tab, 'id');
const params = getQueryParams();
const curTab = getTabFromQueryParams(params);
if (isEmpty(tabname) || tabname === get(this, 'defaultTab')) {
tabname = null;
}
if (curTab !== tabname) {
set(this, 'hashName', tabname);
if (get(this, 'useRouter') && !isNone(get(this, 'router'))) {
set(params, 'bc_tab', tabname);
get(this, 'router').replaceWith(get(this, 'router.currentRouteName'), { queryParams: params });
} else {
if (!isNone(tabname)) {
window.history.replaceState('', document.title, `${window.location.pathname}#tab-${tabname}`);
} else {
window.history.replaceState('', document.title, window.location.pathname);
}
}
}
set(this, 'currentTab', tab);
}
},
triggerTabChange() {
this.handleHash();
let id = get(this, 'hashName') || get(this, 'defaultTab');
let tab = get(this, 'model').findBy('id', id);
if (tab && tab.id !== get(this, 'currentTab.id')) {
this.openTab(tab);
}
},
didInsertElement() {
this._super(...arguments);
// setup router didTransition
const router = get(this, 'router._router');
if (router && router.on) {
router.on('didTransition', this, this.triggerTabChange);
}
},
willDestroyElement() {
this._super(...arguments);
const router = get(this, 'router._router');
if (router && router.off) {
router.off('didTransition', this, this.triggerTabChange);
}
},
actions: {
changeTab(tab) {
this.openTab(tab);
}
}
});
|
import getElement from './-get-element';
import isFormControl from './-is-form-control';
import { __focus__ } from './focus';
import settled from '../settled';
import fireEvent from './fire-event';
import { nextTickPromise } from '../-utils';
/**
Fill the provided text into the `value` property (or set `.innerHTML` when
the target is a content editable element) then trigger `change` and `input`
events on the specified target.
@public
@param {string|Element} target the element or selector to enter text into
@param {string} text the text to fill into the target element
@return {Promise<void>} resolves when the application is settled
*/
export default function fillIn(target, text) {
return nextTickPromise().then(() => {
if (!target) {
throw new Error('Must pass an element or selector to `fillIn`.');
}
let element = getElement(target);
if (!element) {
throw new Error(`Element not found when calling \`fillIn('${target}')\`.`);
}
let isControl = isFormControl(element);
if (!isControl && !element.isContentEditable) {
throw new Error('`fillIn` is only usable on form controls or contenteditable elements.');
}
if (typeof text === 'undefined' || text === null) {
throw new Error('Must provide `text` when calling `fillIn`.');
}
__focus__(element);
if (isControl) {
element.value = text;
} else {
element.innerHTML = text;
}
fireEvent(element, 'input');
fireEvent(element, 'change');
return settled();
});
}
|
/**
* @module lib/tool/native
*/
import Tool from 'lib/tool/base';
import os from 'os';
/**
* @class
* @extends Tool
*/
class Native extends Tool {
/**
* Creates a native tool
*/
constructor() {
super();
this.command = 'echo';
}
/**
* Generates a native command given a string array
* @param {string[]} command
*/
set nativeCommand(command) {
this.command = command[0];
this.native = command.slice(1);
this.initialized = true;
}
/**
* Get the tool name
* @return {string}
*/
get toolName() {
return 'native';
}
/**
* Get the specialized strings
* @return {{universal: string, specific: string}}
* @private
*/
static get _specialized() {
let universal = 'native';
switch (os.platform()) {
case "darwin":
case "freebsd":
case "linux":
case "openbsd":
universal = 'native-nix';
break;
case 'win32':
universal = 'native-win';
break;
}
return {
universal: universal,
specific: `native-${os.platform()}`
};
}
/**
* Describes what this tool knows
* @return {string[]}
*/
static get knows() {
const completely = [];
const special = this._specialized;
completely.push(special.universal);
completely.push(special.specific);
if (special.universal !== 'native') completely.push('native');
return completely;
}
getConfig() {
return this.config;
}
/**
* Builds from a task
* @param {Task} step
* @return {boolean}
*/
buildFromStep(step) {
let universal = 'native';
if (step.exec) {
switch (os.platform()) {
case "darwin":
case "freebsd":
case "linux":
case "openbsd":
universal = 'native-nix';
break;
case 'win32':
universal = 'native-win';
break;
}
const native = step.exec[`native-${os.platform()}`];
const psuedo = step.exec[universal];
const notNativeButNative = step.exec.native;
if (!(native || psuedo || notNativeButNative)) {
return false;
}
const runStep = (native || psuedo || notNativeButNative);
let working = process.cwd();
if (runStep.working) {
working = runStep.working;
}
if (runStep.acceptsArgs) {
runStep.command.push(...process.argv);
}
this.nativeCommand = runStep.command;
this.config = {
cwd: working
};
}
return true;
}
}
export default Native;
|
var gulp = require('gulp'),
config = require('../config'),
mergeStream = require('merge-stream'),
mainBowerFiles = require('main-bower-files'),
flatten = require('gulp-flatten'),
rename = require("gulp-rename"),
bowerRequireJS = require('bower-requirejs'),
wiredep = require('wiredep').stream;
gulp.task('bower:styles', function() {
return gulp.src(config.sass.src)
.pipe(wiredep({
exclude: ['jquery'],
}))
.pipe(gulp.dest(config.sass.srcPath))
});
gulp.task('bower:scripts', function(cb) {
var options = {
baseURL: config.scripts.srcPath,
config: config.scripts.src,
exclude: ['jquery'],
transitive: true
};
bowerRequireJS(options, function (rjsConfigFromBower) {
console.info('------> Updated paths config in '+options.config);
cb();
})
});
|
/*
* Module : FacebookConnect.js
*
* Setups up the basic code to connect to the facebook JS api.
*
* Requires Config:
* - app.config.facebook.appId
*/
(function(app)
{
var module = app.module("facebookConnect", {
requires : [
"jquery-1.9.1.min"
],
init : function()
{
this.is_loaded = false;
//loading facebook all.js after we've added the fb-root div to avoid fb warning
$('body').prepend('<div id="fb-root"></div>');
app.getScript("//connect.facebook.net/en_US/all.js");
},
scrollTop : function()
{
if( this.is_loaded )
FB.Canvas.scrollTo(0, 0);
}
});
//add listener to window object
window.fbAsyncInit = function ()
{
module.is_loaded = true;
// init the FB JS SDK
FB.init({
appId : app.config.facebook.appId,
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : false // parse XFBML tags on this page?
});
// Grow the canvas to the correct size
FB.Canvas.scrollTo(0, 0);
FB.Canvas.setSize({ height: $('body').height()-100});
setTimeout("FB.Canvas.setAutoGrow()", 500);
//dispact event
$(document).trigger('facebookConnected');
//fix scroll bars
if (self !== top)
{
$("body").css("overflow", "hidden");
}
};
}(app));
|
/**
* @license Highstock JS v9.0.0 (2021-02-02)
* @module highcharts/modules/full-screen
* @requires highcharts
*
* Advanced Highstock tools
*
* (c) 2010-2019 Highsoft AS
* Author: Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Extensions/FullScreen.js';
|
// this will only run locally to test the connection to foursquare
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import FoursquareConnection from './connect';
import config from 'config';
import nock from 'nock';
chai.should();
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('Live Connection create', () => {
it('should contain empty array', () => {
const connect = new FoursquareConnection();
expect(connect.requests).to.be.array;
expect(connect.requests).to.have.length(0);
});
it('should correctly add url', () => {
const connect = new FoursquareConnection('https://test');
expect(connect.apiUrl).to.equal('https://test');
});
it('should correctly add auth token', () => {
const connect = new FoursquareConnection('https://test', '1234');
expect(connect.accessToken).to.equal('1234');
});
it('should correctly add client keys', () => {
const connect = new FoursquareConnection('https://test', {clientId: 1, clientSecret: 'xyz'});
expect(connect.clientId).to.equal(1);
expect(connect.clientSecret).to.equal('xyz');
});
});
describe('Live Connection post', () => {
it('should error as not implemented', () => {
expect(new FoursquareConnection().post).to.throw('Not implemented yet!');
});
});
describe('Live Connection get venue', () => {
it('should return venue information', (done) => {
const connect = new FoursquareConnection(config.get('venues.api.foursquare.url'), {clientId: config.get('venues.api.foursquare.clientId'), clientSecret: config.get('venues.api.foursquare.clientSecret')}, config.get('venues.api.foursquare.version'));
connect.get('venues/4b474e04f964a520782e26e3');
connect.start().then((data) => {
expect(data).to.have.property('venue');
expect(connect.requests).to.have.length(1);
done();
});
});
it('should fail with bad request', () => {
const connect = new FoursquareConnection(config.get('venues.api.foursquare.url'), {clientId: config.get('venues.api.foursquare.clientId'), clientSecret: config.get('venues.api.foursquare.clientSecret')}, config.get('venues.api.foursquare.version'));
connect.get('venues/balls');
return connect.start().should.eventually.to.be.rejectedWith();
});
it('should reset after start', (done) => {
const connect = new FoursquareConnection(config.get('venues.api.foursquare.url'), {clientId: config.get('venues.api.foursquare.clientId'), clientSecret: config.get('venues.api.foursquare.clientSecret')}, config.get('venues.api.foursquare.version'));
connect.get('venues/4b474e04f964a520782e26e3');
connect.start(true).then(() => {
expect(connect.requests).to.have.length(0);
done();
});
});
});
describe('Live Connection get venues', () => {
it('should venues given lat lng', (done) => {
const connect = new FoursquareConnection(config.get('venues.api.foursquare.url'), {clientId: config.get('venues.api.foursquare.clientId'), clientSecret: config.get('venues.api.foursquare.clientSecret')}, config.get('venues.api.foursquare.version'));
connect.get('venues/search', {
lat: 40.7,
lng: -74,
radius: 16000,
intent: 'browse'
});
connect.start().then((data) => {
expect(data).to.have.property('venues').with.length;
done();
}).catch((error) => {
});
});
});
|
// @flow
//
// Copyright (c) 2018 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
import highland from "highland";
import angular from "angular";
import { querySelector } from "./dom-utils.js";
import type { HighlandStreamT } from "highland";
type stateServiceT = {
go: (name: string) => void
};
type cacheT = {
$state?: stateServiceT
};
const cache: cacheT = {};
type servicesT = "$state";
type methodsT = "go";
export default <R>(service: servicesT, method: methodsT, ...args: any[]): HighlandStreamT<R> => {
const s: HighlandStreamT<R> = highland();
const inj = angular.element(querySelector(document, "body")).injector();
function loop() {
if (cache[service]) {
const fn: Function = cache[service][method];
s.write(fn(...args));
s.end();
} else if (inj.has(service)) {
const svc = inj.get(service);
const fn: Function = svc[method];
cache[service] = svc;
s.write(fn(...args));
s.end();
} else {
setTimeout(loop, 0);
}
}
loop();
return s;
};
|
'use strict';
angular.module('wsapp')
.controller('KnowledgeAddController', function ($scope, knowledgeService, $location, $state) {
$scope.data={};
$scope.program = function(){
alertify.success("Test");
}
$scope.know = function(){
console.log($scope.data);
knowledgeService.insertKnowledge($scope.data,
function(response){
console.log(response.data);
//if(response.data.success==true){
alertify.success("SUCCESS");
$state.go('home');
//}else{
//alertify.error("ERROR");
//}
}
,function(response){
console.log(response);
alertify.error("ERROR");
});
}
});
|
(function () {
angular.module('app').controller('app.views.tenants.index', [
'$scope', '$uibModal', 'abp.services.app.tenant',
function ($scope, $uibModal, tenantService) {
var vm = this;
vm.tenants = [];
function getTenants() {
tenantService.getAll({}).then(function (result) {
vm.tenants = result.data.items;
});
}
vm.openTenantCreationModal = function () {
var modalInstance = $uibModal.open({
templateUrl: '/App/Main/views/tenants/createModal.cshtml',
controller: 'app.views.tenants.createModal as vm',
backdrop: 'static'
});
modalInstance.rendered.then(function () {
$.AdminBSB.input.activate();
});
modalInstance.result.then(function () {
getTenants();
});
};
vm.openTenantEditModal = function (tenant) {
var modalInstance = $uibModal.open({
templateUrl: '/App/Main/views/tenants/editModal.cshtml',
controller: 'app.views.tenants.editModal as vm',
backdrop: 'static',
resolve: {
id: function () {
return tenant.id;
}
}
});
modalInstance.rendered.then(function () {
$.AdminBSB.input.activate();
});
modalInstance.result.then(function () {
getTenants();
});
}
vm.delete = function (tenant) {
abp.message.confirm(
"Delete tenant '" + tenant.name + "'?",
"Delete",
function (result) {
if (result) {
tenantService.delete({ id: tenant.id })
.then(function () {
abp.notify.info("Deleted tenant: " + tenant.name);
getTenants();
});
}
});
}
vm.refresh = function() {
getTenants();
};
getTenants();
}
]);
})();
|
import Ember from 'ember';
export default Ember.View.extend({
classNames: 'weather-view dashboard-item'
});
|
// Dependencies
const queryValidation = require('./libs/query-validation.js');
const utils = require('./libs/utilities');
/**
* Create an instance of Behance
* @param {string} token - authentication for Behance API
* @public
*/
const Behance = function behance(token) {
this.clientId = token;
// Throw an error if Auth Key is not specified
if (this.clientId === undefined) {
throw Error('Please supply an authorization token for new Behance().');
}
};
// Endpoints that only support Options
const endpointWithOptionOnly = [{
name: 'projects',
path: 'projects',
queries: queryValidation.projects
}, {
name: 'creativesToFollow',
path: 'creativestofollow',
queries: queryValidation.creativesToFollow
}, {
name: 'users',
path: 'users',
queries: queryValidation.users
}, {
name: 'teams',
path: 'teams',
queries: queryValidation.teams
}, {
name: 'collections',
path: 'collections',
queries: queryValidation.collections
}];
endpointWithOptionOnly.forEach(function iterate(def) {
/**
* Get a list of projects/creatives/users/collections
* @param {object} opts - queries
* @param {function} cb - callback
* @return {object} - response from Behance API
* @public
*/
Behance.prototype[def.name] = function assign(opts, cb) {
if (Object.keys(opts).length === 0 || utils.compareKeys(opts, def.queries, def.name)) {
utils.requestHandler(utils.requestUrl(def.path, this.clientId, opts), cb);
}
};
});
/**
* Endpoints that require an ID with no Options
*/
const endpointWithOnlyAnId = [{
name: 'project',
pathprefix: 'projects/'
}, {
name: 'user',
pathprefix: 'users/'
}, {
name: 'team',
pathprefix: 'teams/'
}, {
name: 'userStats',
pathprefix: 'users/',
pathsuffix: '/stats'
}, {
name: 'userWorkExperience',
pathprefix: 'users/',
pathsuffix: '/work_experience'
}, {
name: 'collection',
path: 'collection'
}];
endpointWithOnlyAnId.forEach(function iterate(def) {
/**
* Get info about a project/user/collection
* @param {string} id - identifier
* @param {function} cb - callback
* @return {object} - response from Behance API
* @public
*/
Behance.prototype[def.name] = function assign(id, cb) {
const endpoint = def.pathprefix + id + (def.pathsuffix ? def.pathsuffix : '');
if (arguments.length !== 2) {
throw Error(`.${def.name} requires both an id and a callback function.`);
}
utils.requestHandler(utils.requestUrl(endpoint, this.clientId), cb);
};
});
/**
* Endpoints that require an ID and support Options
*/
const endpointWithIdAndOptions = [{
name: 'projectComments',
pathprefix: 'projects/',
pathsuffix: '/comments',
queries: queryValidation.projectComments
}, {
name: 'userProjects',
pathprefix: 'users/',
pathsuffix: '/projects',
queries: queryValidation.userProjects
}, {
name: 'userWips',
pathprefix: 'users/',
pathsuffix: '/wips',
queries: queryValidation.userWips
}, {
name: 'teamProjects',
pathprefix: 'teams/',
pathsuffix: '/projects',
queries: queryValidation.teamsProjects
}, {
name: 'userAppreciations',
pathprefix: 'users/',
pathsuffix: '/appreciations',
queries: queryValidation.userAppreciations
}, {
name: 'userCollections',
pathprefix: 'users/',
pathsuffix: '/collections',
queries: queryValidation.userCollections
}, {
name: 'userFollowers',
pathprefix: 'users/',
pathsuffix: '/followers',
queries: queryValidation.userFollowers
}, {
name: 'userFollowing',
pathprefix: 'users/',
pathsuffix: '/following',
queries: queryValidation.userFollowing
}, {
name: 'collectionProjects',
pathprefix: 'collections/',
pathsuffix: '/projects',
queries: queryValidation.collectionProjects
}];
endpointWithIdAndOptions.forEach(function iterate(def) {
/**
* Get a list of comments/projects/wips/appreciations/collections/followers
* @param {string} id - identifier
* @param {object} opts - queries
* @param {function} cb - callback
* @return {object} - response from Behance API
* @public
*/
Behance.prototype[def.name] = function assign(id, opts, cb) {
const endpoint = def.pathprefix + id + (def.pathsuffix ? def.pathsuffix : '');
let newCb;
let newOpts;
// Update Params order if options aren't supplied
if (arguments.length === 2) {
newCb = opts;
newOpts = {};
}
if (id === '' || typeof id === 'object') {
throw Error(`.${def.name} requires at least an id and a callback function.`);
}
if (Object.keys(opts).length === 0 || utils.compareKeys(opts, def.queries, def.name)) {
utils.requestHandler(utils.requestUrl(endpoint, this.clientId, newOpts || opts), newCb || cb);
}
};
});
/**
* Get Creative Fields
* @param {function} cb - callback
* @return {object} - response from Behance API
* @public
*/
Behance.prototype.fields = function assign(cb) {
utils.requestHandler(utils.requestUrl('fields', this.clientId), cb);
};
module.exports = Behance;
|
angular.module('mean.system').controller('HeaderController', ['$scope', 'Global', function ($scope, Global) {
$scope.global = Global;
$scope.menu = [
{
"title": "buckets",
"link": "buckets"
},
{
"title": "users",
"link": "musers"
},
{
"title": "logs",
"link": "logs"
}
];
$scope.isCollapsed = false;
}]);
|
var img = NotReact.createElement( 'img', { src: "foo.gif" });
|
import { createStore, compose, applyMiddleware } from "redux";
import { routerMiddleware } from "react-router-redux";
import createSagaMiddleware from "redux-saga";
import createLogger from "redux-logger";
import rootReducer from "../reducers";
import rootSaga from "../sagas/";
const configureStore = (history: any) => {
const sagaMiddleware = createSagaMiddleware();
const logger = createLogger();
let middlewares = null;
if (process.env.NODE_ENV === "production") {
middlewares = applyMiddleware(
routerMiddleware(history),
sagaMiddleware
);
} else {
middlewares = applyMiddleware(
routerMiddleware(history),
sagaMiddleware,
logger
);
}
const store = createStore(
rootReducer,
{},
compose(middlewares)
);
if (process.env.NODE_ENV !== "production") {
if (module.hot) {
module.hot.accept("../reducers", () => {
const nextRootReducer = require("../reducers").default;
store.replaceReducer(nextRootReducer);
});
}
}
sagaMiddleware.run(rootSaga);
return store;
};
export default configureStore;
|
search_result['4732']=["topic_0000000000000B84_events--.html","ConfigWrapper Events",""];
|
// @flow
import React, { Component } from 'react';
import { Grid, Row, Col, FormGroup, FormControl, HelpBlock, ControlLabel } from 'react-bootstrap';
export default class AdminFamilySearch extends Component {
render() {
return (
<div>
<Grid>
<Row className="show-grid">
<Col xs={12} md={8}>
<form>
<FormGroup
controlId="formBasicText"
validationState={() => {}}
>
<ControlLabel><p>Search for family (phone; lastname; lastname, firstname)</p></ControlLabel>
<FormControl componentClass="text" />
<FormControl.Feedback />
<HelpBlock><p>Staff attended check-in station</p></HelpBlock>
</FormGroup>
</form>
</Col>
</Row>
</Grid>
</div>
);
}
}
|
db.products.aggregate([
{
"$group": {
"_id": {
"maker": "$manufacturer"
}, "categories": { '$addToSet' : '$category' }
}
}
])
|
/*
* Name: TUTableImpl.js
* Module:
* Location: Norris/test/unit
* Date: 2015-05-25
* Version: v1.00
*
* History:
*
* ================================================================================
* Version Date Programmer Changes
* ================================================================================
* v1.00 2015-06-15 Carlon Chiara Approved
* ================================================================================
* v0.02 2015-06-02 Pavanello Fabio Matteo Verify
* ================================================================================
* v0.01 2015-05-25 Bucco Riccardo Creation
* ================================================================================
*/
var TableImpl = require('../../main/DataModel/NorrisChart/TableImpl.js');
var assert = require("assert");
describe('TableImpl', function(){
describe('TableImpl(id: String)', function(){
it('should memorize the right type of the chart',function(){
var table = new TableImpl('randomID');
assert.equal('table', table.type);
});
it('should memorize the right id of the chart',function(){
var table = new TableImpl('randomID');
assert.equal('randomID', table.uid);
});
it('should memorize some default values for the keys of the settings',function(){
var table = new TableImpl('randomID');
var defaults = {
title: '',
description : 'This is a table.',
maxItems : 10 ,
showTableGrid : true ,
newLinePosition : 'bottom',
allowFilter: false,
allowSort: false,
pageSize: -1
};
assert.deepEqual(defaults,table.settings);
});
})
});
|
// passwort-generator.js
// http://passwort-generieren.de
// (c) 2014 Jan Krause
(function() {
"use strict";
var root = this;
var PasswordGenerator = function(options) {
if(!options){
options = {};
options.el = document.body;
}
this.options = this.extend(options, this.default_options);
};
// Export the object for **Node.js**
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = PasswordGenerator;
}
exports.PasswordGenerator = PasswordGenerator;
} else {
root.PasswordGenerator = PasswordGenerator;
}
PasswordGenerator.prototype = {
options: {},
default_options: {
length: 11,
lowercase: true,
uppercase: true,
numbers: true,
special_character: true,
brackets: true,
minus: true,
underscore: true,
space: true
},
_passwort: '',
extend: function(options,defaults){
var extended = {};
var prop;
for (prop in defaults) {
if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
extended[prop] = defaults[prop];
}
}
for (prop in options) {
if (Object.prototype.hasOwnProperty.call(options, prop)) {
extended[prop] = options[prop];
}
}
return extended;
},
generate: function() {
var _i, _len, _passwortString = '';
if(this.options.lowercase){
_passwortString += 'abcdefghijklmnopqrstuvwxyz';
}
if(this.options.uppercase){
_passwortString += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if(this.options.numbers){
_passwortString += '0123456789';
}
if(this.options.special_character){
_passwortString += ',.;:#+~*=&%$§!|/€@""^°`´\'\\';
}
if(this.options.brackets){
_passwortString += '<>[](){}';
}
if(this.options.minus){
_passwortString += '-';
}
if(this.options.underscore){
_passwortString += '_';
}
if(this.options.space){
_passwortString += ' ';
}
this._passwort = '';
for (_i = 0, _len = this.options.length; _i < _len; _i++) {
this._passwort += _passwortString.charAt(Math.floor(Math.random() * _passwortString.length));
}
},
set: function(param) {
this.options = this.extend(param,this.options);
},
get: function() {
this.generate();
return this._passwort;
},
render: function() {
this.options.el.innerHTML = this.get();
}
};
}.call(this));
|
////////////////////////////////////////////////
//
// Markdown to HTML converter demo (markdown widget)
//
//
// IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
//
// version : 1.0
// IoT Manager : 1.5.4 and above
//
////////////////////////////////////////////////
////////////////////////////////////////////////
var config = require("./config");
var host = config.host;
var port = config.port;
var user = config.user;
var pass = config.pass;
////////////////////////////////////////////////
var mqtt = require('mqtt');
var opt = {
host : host,
port : port,
username : user,
password : pass,
clientId : 'mqtt-js_' + Math.random().toString(16).substr(2, 8),
protocolId : 'MQTT',
connectTimeout: 3000
};
var deviceID = "device10";
var prefix = "/IoTmanager";
var config = [];
var client = mqtt.connect(opt);
// First line
var widget = "anydata";
var id = "0"
widget = "markdown";
id = "0"
config[0] = {
id : id,
widget : widget,
topic : prefix + "/" + deviceID + "/" + widget + id,
class1 : "padding"
};
client.on('connect', function () {
console.log('Broker connected');
client.subscribe(prefix, { qos : 1 }); // HELLO expected
pubConfig();
});
client.on('error', function () {
console.log('Broker error');
});
client.on('offline', function () {
console.log('Broker offline');
});
client.on('message', function (topic, message) {
console.log("Message arrived: " + topic.toString() + " => " + message.toString());
if (topic.toString() === prefix && message.toString() == "HELLO" ){
console.log('HELLO detected');
pubConfig();
}
pubStatus();
})
////////////////////////////////////////////////
function pubConfig() {
config.forEach(function(item, i, arr) {
client.publish(prefix + "/" + deviceID + "/config", JSON.stringify(item),{ qos : 1 });
});
}
////////////////////////////////////////////////
function pubStatus() {
var x = 10 + Math.round(Math.random() * 10);
var y = 100 + Math.round(Math.random() * 100);
var z = 1000 + Math.round(Math.random() * 1000);
var z1= 1000 + Math.round(Math.random() * 5000);
var text = '\n';
text += '\n__Sensor1 ' + x + '__';
text += '\n~~Sensor2 ' + y + '~~';
text += '\n**Sensor3 ' + z + '**';
text += '\n*Sensor4 ' + z1+ '*';
text += '\n';
text += '\n| Tables | Are | Cool |';
text += '\n| -------- |:-------------:|------:|';
text += '\n| col 2 | centered |'+x+'|';
text += '\n| col 3 | **right** |'+y+'|';
text += '\n| col 1 | ~~left~~ |'+z+'|';
text += '\n| | 4 |'+z1+'|';
text += '\n';
text += '\n# Sensor 1: '+x;
text += '\n## Sensor 2: '+y;
text += '\n### Sensor 3: '+z;
text += '\n#### Sensor 4: '+z1;
text += '\n';
client.publish( config[0].topic+"/status", JSON.stringify({ status: text }) );
console.log('Publish');
}
////////////////////////////////////////////////
// run main
console.log('Start');
setInterval(function() {
pubStatus();
}, 5000);
|
// Raymond Ho
// 8/22/15
var bodyParser = require('body-parser'),
express = require('express'),
Datastore = require('nedb');
var db = new Datastore({
filename: __dirname + '/db.json',
autoload: true
});
var app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
// This is to get all tags for a certain video
app.get('/bestpart/gettags', function(req, res) {
var urlObject = {url: req.query.url};
console.log("Received a GET tags request from:", urlObject.url);
db.findOne(urlObject, function(err, docs) {
if (docs === null) {
var errorString = urlObject.url + " was not found in the database..";
res.send({error: errorString});
}
else {
console.log('Sending over the docs..', docs);
res.send(docs);
}
});
});
// This is to add or update a new tag
app.post('/bestpart/tag', function(req, res) {
var tagJSON = req.body;
var tag = {
tag_created: new Date(),
tag_time: tagJSON.time,
tag_description: tagJSON.description,
tag_score: 0
};
var searchFor = {
url: tagJSON.url
};
console.log("Received a POST", tagJSON);
db.findOne(searchFor, function(err, docs) {
if (docs === null) {
video = {
url: tagJSON.url,
tags: [tag],
};
db.insert(video);
console.log("Added to db.");
} else {
console.log(docs);
db.update(searchFor, {
$push: {
tags: tag
}
}, {}, function() {});
console.log("Updated DB");
}
});
});
// This is to update the votes a tag has.
app.post('/bestpart/votes', function(req, res) {
var tagJSON = req.body;
var searchFor = {
url: tagJSON.url
};
var newScore = tagJSON.vote;
db.update(searchFor, {
$inc: {
score: newScore
}
}, {}, function() {});
});
var server = app.listen(3000, function() {
console.log("http://localhost:3000/");
});
|
module.exports = {
errorcodes: {
NoError: 0,
GeneralError: 1,
InvalidGame: 2,
Timeout: 3,
InvalidRequest: 4,
DoNotTrack: 5,
GeoIPDisabled: 100,
LeaderboardsDisabled: 200,
InvalidName: 201,
InvalidAuthKey: 202,
NoFacebookId: 203,
NoTableName: 204,
InvalidPermalink: 205,
NoLeaderboardId: 206,
InvalidLeaderboardId: 207,
PlayerBanned: 208,
NotBestScore: 209,
GameVarsDisabled: 300,
PlayerLevelsDisabled: 400,
InvalidRating: 401,
AlreadyRated: 402,
NoLevelName: 403,
NoLevelId: 404,
LevelAlreadyExists: 405,
AchievementsDisabled: 500,
NoPlayerId: 501,
NoPlayerName: 502,
NoAchievement: 503,
InvalidAchievement: 504,
AlreadyHadAchievementNotSaved: 505,
AlreadyHadAchievementSaved: 506,
NewsletterDisabled: 600,
MailChimpNotConfigured: 601,
MailChimpError: 602
},
descriptions: {
// General Errors
"0": "No error",
"1": "General error, this typically means the player is unable to connect",
"2": "Invalid game credentials. Make sure you use the keys you set up in your database",
"3": "Request timed out",
"4": "Invalid request",
// GeoIP Errors
"100": "GeoIP API has been disabled for this game",
// Leaderboard Errors
"200": "Leaderboard API has been disabled for this game",
"201": "The player's name was not provided when saving a score",
"203": "Player is banned from submitting scores in this game",
"204": "Score was not saved because it was not the player's best. You can allow players to have more than one score by specifying allowduplicates=true in your save options",
// GameVars Errors
"300": "GameVars API has been disabled for this game",
// LevelSharing Errors
"400": "Level sharing API has been disabled for this game",
"401": "Invalid rating value (must be 1 - 10)",
"402": "Player has already rated that level",
"403": "Missing level name",
"404": "Missing levelid",
"405": "Level already exists",
// Achievement errors
"500": "Achievements API has been disabled for this game",
"501": "Missing playerid",
"502": "Missing player name",
"503": "Missing achievement",
"504": "Invalid achievement for achievement key",
"505": "Player already had the achievement. You can overwrite old achievements with overwrite=true or save each time the player is awarded with allowduplicates=true",
"506": "Player already had the achievement and it was overwritten or a duplicate was saved successfully",
// Newsletter errors
"600": "Newsletter API has been disabled for this game",
"601": "MailChimp API key is not configured",
"602": "The MailChimp API returned an error"
}
};
|
/**
* Charge.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name: {
type: 'string'
},
scope: {
type: 'string'
},
}
};
|
import React from 'react';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import FormControl from 'react-bootstrap/lib/FormControl';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
class ValidatedTextBox extends React.Component {
constructor(props){
super(props);
this.props = props;
this.state = {value: ''}
}
handleChange(e){
this.setState({value: e.target.value});
this.props.onChange(e.target.value);
}
render () {
const { controlId, validationState, label, value, onChange, helpText } = this.props;
return (
<form>
<FormGroup
controlId={controlId}
validationState={validationState}>
<ControlLabel> {label} </ControlLabel>
<FormControl
type="text"
value={this.state.value}
placeholder="Enter Quizlet set number"
onChange={this.handleChange.bind(this)}
/>
<FormControl.Feedback />
<HelpBlock>{helpText}</HelpBlock>
</FormGroup>
</form>
);
}
}
module.exports = ValidatedTextBox
|
'use strict';
/**
* @ngdoc function
* @name networkAnalyzerApp.controller:ConnectionsCtrl
* @description
* # ConnectionsCtrl
* Controller of the networkAnalyzerApp
*/
angular.module('networkAnalyzerApp')
.controller('ConnectionsCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
/**
* @license Highcharts JS v9.2.0 (2021-08-18)
* @module highcharts/modules/broken-axis
* @requires highcharts
*
* (c) 2009-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import Highcharts from '../../Core/Globals.js';
import BrokenAxis from '../../Core/Axis/BrokenAxis.js';
var G = Highcharts;
// Compositions
BrokenAxis.compose(G.Axis, G.Series);
|
const url = require('url');
const _ = require('lodash');
const fetch = require('node-fetch');
const PouchDB = require('pouchdb');
const logout = require('../../logout')();
PouchDB.plugin(require('pouchdb-adapter-node-websql'));
PouchDB.plugin(require('pouchdb-find'));
module.exports = {
createPouchDB: _.memoize(createPouchDB),
sync: _.memoize(sync),
};
function createPouchDB(environment){
return new PouchDB(`${environment}.db`, {adapter: 'websql', auto_compaction: true});
}
function sync(environment, syncDbUrl, continuous_sync){
if(!environment) return;
if(!syncDbUrl) return;
const syncDbUri = url.parse(syncDbUrl);
const syncDbNamedUrl = ((!syncDbUri.path) || (syncDbUri.path === '/'))
? url.resolve(syncDbUrl, environment)
: url.resolve(syncDbUrl.replace(syncDbUri.path, ''), `${syncDbUri.path.replace(/\//g, '')}-${environment}`);
return fetch(syncDbNamedUrl, {method: 'PUT'})
.catch(error => error)
.then(data => data.json())
.then(data => {
return createPouchDB(environment)
.sync(syncDbNamedUrl, {
live: continuous_sync,
retry: continuous_sync,
})
.on('change', info => logout.log(`Change - ${syncDbUri.host} - ${environment}`))
.on('paused', () => logout.log(`Paused - ${syncDbUri.host} - ${environment}`))
.on('active', () => logout.log(`Active - ${syncDbUri.host} - ${environment}`))
.on('denied', info => logout.error(`Denied - ${syncDbUri.host} - ${environment}`))
.on('complete', info => logout.log(`Complete - ${syncDbUri.host} - ${environment}`))
.on('error', error => logout.error(`Error - ${syncDbUri.host} - ${environment}`));
})
.catch(error => logout.error(error));
}
|
define(function(require) {
'use strict';
var ColumnManagerView;
var _ = require('underscore');
var BaseView = require('oroui/js/app/views/base/view');
ColumnManagerView = BaseView.extend({
template: require('tpl!orodatagrid/templates/column-manager/column-manager.html'),
autoRender: true,
className: 'dropdown-menu',
events: {
'click [data-role="column-manager-select-all"]': 'onSelectAll'
},
listen: {
'change:renderable collection': 'onRenderableChange'
},
initialize: function(options) {
ColumnManagerView.__super__.initialize.call(this, options);
this.filterer = _.bind(options.columnFilterModel.filterer, options.columnFilterModel);
// to handle renderable change at once for multiple changes
this.onRenderableChange = _.debounce(this.onRenderableChange, 0);
this.listenTo(options.columnFilterModel, 'change', this.updateView);
},
render: function() {
ColumnManagerView.__super__.render.call(this);
this.updateView();
return this;
},
/**
* Update filter view from its state
*/
updateView: function() {
var models = this._getFilteredModels();
var hasUnrenderable = Boolean(_.find(models, function(model) {return !model.get('renderable');}));
this.$('[data-role="column-manager-select-all"]').toggleClass('disabled', !hasUnrenderable);
},
/**
* Handles renderable change of column models
* - updates the view
*/
onRenderableChange: function() {
this.updateView();
},
onSelectAll: function(e) {
e.preventDefault();
_.each(this._getFilteredModels(), function(model) {
model.set('renderable', true);
});
},
_getFilteredModels: function() {
return _.filter(this.collection.filter(this.filterer), function(model) {
return !model.get('disabledVisibilityChange');
});
}
});
return ColumnManagerView;
});
|
export default () => <h1>Projects</h1>
|
var mongoose = require('mongoose');
var rooms = require('./rooms');
mongoose.connect('mongodb://localhost:27017/rpgd');
var RoomSchema = require('mongoose').model('Room').schema;
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// Setup Database scheme
var ProjectSchema = new Schema({
name: String,
subtitle: String,
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
contributors: [UserSchema],
summary: String,
description: String,
comments: [CommentSchema],
created: {
type: Date,
default: Date.now()
},
private: {
type: Boolean,
default: false
},
meta: {
votes: Number,
favs: Number
},
rooms: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Room'
}]
});
var User = mongoose.model('User', UserSchema);
var Project = mongoose.model('Project', ProjectSchema);
var handleError = function (err) {
console.log('Error', err);
}
exports.findById = function (req, res) {
Project.findOne({
'_id': req.params.id
}, function (err, project) {
if (err) return handleError(err);
res.send(project);
})
.populate('createdBy')
.populate('rooms')
};
exports.findAll = function (req, res) {
Project.find({}, function (err, projects) {
if (err) handleError(err);
res.send(projects);
});
};
exports.updateRoom = function (req, res) {
/*Project.findByIdAndUpdate(
info._id,
{$push: {"rooms": }}
)
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(err);
}
);
*/
}
exports.addRoom = function (req, res) {
// find by document id and update
Project.findByIdAndUpdate(
req.params.projectId, {
$push: {
rooms: req.body
}
}, {
safe: true,
upsert: true
},
function (err, model) {
console.log(err);
}
);
res.send('Done')
}
exports.addProject = function (req, res) {
console.log('Request: ' + req);
console.log('Request body: ' + req.body);
var pro = new Project(req.body);
console.log('Crating new project ' + pro);
pro.save(function (err, result) {
if (err) return handleError(err);
res.send('Project created');
})
}
exports.updateProject = function (req, res) {}
exports.deleteProject = function (req, res) {}
|
import {
SIGN_IN,
SIGN_IN_SUCCESS,
SIGN_IN_ERROR,
SIGN_OUT,
SIGN_OUT_SUCCESS,
USER_LOGGED,
USER_UNLOGGED
} from '../../constants/action-types';
const INITIAL_STATE = {
isUserSignedIn: false,
isSignOutInProgress: false,
isInProgress: null,
hasError: false,
errorMessage: '',
userIsLogged: null,
user: {}
};
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case USER_LOGGED:
return {
...state,
userIsLogged: true,
user: {
...action.payload,
}
};
case USER_UNLOGGED:
return {
...state,
userIsLogged: false,
user: {}
};
case SIGN_IN_SUCCESS:
return {
...state,
isUserSignedIn: true,
isInProgress: false
};
case SIGN_IN:
return {
...state,
isInProgress: true
};
case SIGN_IN_ERROR:
return {
...state,
hasError: true,
error: action.error
};
case SIGN_OUT_SUCCESS:
return {
...state,
isUserSignedIn: false,
isSignOutInProgress: false
};
case SIGN_OUT:
return {
...state,
isSignOutInProgress: true
};
default:
return state;
}
}
|
/* eslint-disable camelcase */
import {Response} from 'ember-cli-mirage';
import {isBlank} from 'ember-utils';
import $ from 'jquery';
export default function mockAuthentication(server) {
server.post('/authentication/token', function ({roles, users}, {requestBody}) {
let params = $.deparam(requestBody);
if (params.grant_type === 'authorization_code') {
// OAuth sign-in
if (!users.all().models.length) {
let role = roles.findBy({name: 'Owner'});
server.create('user', {email: 'oauthtest@example.com', roles: [role]});
}
return {
access_token: '5JhTdKI7PpoZv4ROsFoERc6wCHALKFH5jxozwOOAErmUzWrFNARuH1q01TYTKeZkPW7FmV5MJ2fU00pg9sm4jtH3Z1LjCf8D6nNqLYCfFb2YEKyuvG7zHj4jZqSYVodN2YTCkcHv6k8oJ54QXzNTLIDMlCevkOebm5OjxGiJpafMxncm043q9u1QhdU9eee3zouGRMVVp8zkKVoo5zlGMi3zvS2XDpx7xsfk8hKHpUgd7EDDQxmMueifWv7hv6n',
expires_in: 3600,
refresh_token: 'XP13eDjwV5mxOcrq1jkIY9idhdvN3R1Br5vxYpYIub2P5Hdc8pdWMOGmwFyoUshiEB62JWHTl8H1kACJR18Z8aMXbnk5orG28br2kmVgtVZKqOSoiiWrQoeKTqrRV0t7ua8uY5HdDUaKpnYKyOdpagsSPn3WEj8op4vHctGL3svOWOjZhq6F2XeVPMR7YsbiwBE8fjT3VhTB3KRlBtWZd1rE0Qo2EtSplWyjGKv1liAEiL0ndQoLeeSOCH4rTP7'
};
} else {
// Password sign-in
return {
access_token: '5JhTdKI7PpoZv4ROsFoERc6wCHALKFH5jxozwOOAErmUzWrFNARuH1q01TYTKeZkPW7FmV5MJ2fU00pg9sm4jtH3Z1LjCf8D6nNqLYCfFb2YEKyuvG7zHj4jZqSYVodN2YTCkcHv6k8oJ54QXzNTLIDMlCevkOebm5OjxGiJpafMxncm043q9u1QhdU9eee3zouGRMVVp8zkKVoo5zlGMi3zvS2XDpx7xsfk8hKHpUgd7EDDQxmMueifWv7hv6n',
expires_in: 3600,
refresh_token: 'XP13eDjwV5mxOcrq1jkIY9idhdvN3R1Br5vxYpYIub2P5Hdc8pdWMOGmwFyoUshiEB62JWHTl8H1kACJR18Z8aMXbnk5orG28br2kmVgtVZKqOSoiiWrQoeKTqrRV0t7ua8uY5HdDUaKpnYKyOdpagsSPn3WEj8op4vHctGL3svOWOjZhq6F2XeVPMR7YsbiwBE8fjT3VhTB3KRlBtWZd1rE0Qo2EtSplWyjGKv1liAEiL0ndQoLeeSOCH4rTP7',
token_type: 'Bearer'
};
}
});
server.post('/authentication/passwordreset', function (schema, request) {
let {passwordreset} = JSON.parse(request.requestBody);
// eslint-disable-next-line ember-suave/prefer-destructuring
let email = passwordreset[0].email;
if (email === 'unknown@example.com') {
return new Response(404, {}, {
errors: [
{
message: 'There is no user with that email address.',
errorType: 'NotFoundError'
}
]
});
} else {
return {
passwordreset: [
{message: 'Check your email for further instructions.'}
]
};
}
});
server.get('/authentication/invitation/', function (schema, request) {
let {email} = request.queryParams;
let invite = schema.invites.findBy({email});
let user = schema.users.find(invite.createdBy);
let valid = !!invite;
let invitedBy = user && user.name;
return {
invitation: [{
valid,
invitedBy
}]
};
});
/* Setup ---------------------------------------------------------------- */
server.post('/authentication/setup', function ({roles, users}, request) {
let [attrs] = JSON.parse(request.requestBody).setup;
let role = roles.findBy({name: 'Owner'});
// create owner role unless already exists
if (!role) {
role = roles.create({name: 'Owner'});
}
attrs.roles = [role];
if (!isBlank(attrs.email)) {
attrs.slug = attrs.email.split('@')[0].dasherize();
}
// NOTE: server does not use the user factory to fill in blank fields
return users.create(attrs);
});
server.get('/authentication/setup/', function () {
return {
setup: [
{status: true}
]
};
});
}
|
define(["require", "exports", "./SignalConnection"], function (require, exports, SignalConnection_1) {
"use strict";
var Task = (function () {
function Task(fn) {
this.next = null;
this.fn = fn;
}
return Task;
}());
var SignalAbstract = (function () {
function SignalAbstract(listener) {
if (listener === void 0) { listener = null; }
this._deferredTasks = null;
this.connect = this.connectImpl;
this._head = (listener != null) ? new SignalConnection_1.default(this, listener) : null;
}
SignalAbstract.prototype.hasListeners = function () {
return this._head != null;
};
SignalAbstract.prototype.connectImpl = function (listener, prioritize) {
if (prioritize === void 0) { prioritize = false; }
var _g = this;
var conn = new SignalConnection_1.default(this, listener);
if (this.dispatching()) {
this.defer(function () {
_g.listAdd(conn, prioritize);
});
}
else {
this.listAdd(conn, prioritize);
}
return conn;
};
SignalAbstract.prototype.disconnect = function (conn) {
var _g = this;
if (this.dispatching()) {
this.defer(function () {
_g.listRemove(conn);
});
}
else {
this.listRemove(conn);
}
};
SignalAbstract.prototype.defer = function (fn) {
var tail = null;
var p = this._deferredTasks;
while (p != null) {
tail = p;
p = p.next;
}
var task = new Task(fn);
if (tail != null) {
tail.next = task;
}
else {
this._deferredTasks = task;
}
};
SignalAbstract.prototype.willEmit = function () {
var snapshot = this._head;
this._head = SignalAbstract.DISPATCHING_SENTINEL;
return snapshot;
};
SignalAbstract.prototype.didEmit = function (head) {
this._head = head;
var snapshot = this._deferredTasks;
this._deferredTasks = null;
while (snapshot != null) {
snapshot.fn();
snapshot = snapshot.next;
}
};
SignalAbstract.prototype.dispatching = function () {
return this._head == SignalAbstract.DISPATCHING_SENTINEL;
};
SignalAbstract.prototype.listAdd = function (conn, prioritize) {
if (prioritize) {
conn._next = this._head;
this._head = conn;
}
else {
var tail = null;
var p = this._head;
while (p != null) {
tail = p;
p = p._next;
}
if (tail != null) {
tail._next = conn;
}
else {
this._head = conn;
}
}
};
SignalAbstract.prototype.listRemove = function (conn) {
var prev = null;
var p = this._head;
while (p != null) {
if (p == conn) {
var next = p._next;
if (prev == null) {
this._head = next;
}
else {
prev._next = next;
}
return;
}
prev = p;
p = p._next;
}
};
SignalAbstract.DISPATCHING_SENTINEL = new SignalConnection_1.default(null, null);
return SignalAbstract;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = SignalAbstract;
});
|
function init(){
listar();
calcular();
}
function calcular(){
var tabla=$('#tbllistado').DataTable({
"paging": false,
"bInfo" : false,
"searching": false,
"bLengthChange": false //used to hide the property
});
/*FUNCION QUE DETECTA EL CLICK Y EL ID DE LA FILA*/
/*
$('#tbllistado').on('click', 'tr', function () {
var id = tabla.row(this).id();
alert('Clicked row id ' + id);
});*/
var total = 0;
var totalFeriado = 0;
/*FUNCION QUE DETECTA EL CHANGE Y EL VALOR PARA CANT*/
$('#tbllistado').on('change', '.normal', function () {
var id = $(this).val();
/*DESACTIVAMOS EL INPUT*/
$(this).prop('disabled', true);
var neto = parseInt($(this).parent().parent().find(".neto").html(), 10);
var monto = id*neto;
total = total+monto;
totalFeriado = total+(total*0.20);
$("#total").html('Normal: '+total+' / Feriado: '+totalFeriado);
});
}
function listar(){
$.post('controllers/tarifas.php?op=listarHTML',function(respuesta){
$("#contenido").html(respuesta);
});
}
init();
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
|
import Ember from "ember";
export default Ember.Object.extend({
targetRoute: null,
params: null,
isSingleResource: Ember.computed.match(
'targetRoute',
/(?:^(?!.*s\b))(?:^(?!index)).*$/
),
hasParams: Ember.computed.bool('params')
});
|
/*! UIkit 3.5.15 | https://www.getuikit.com | (c) 2014 - 2020 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) :
typeof define === 'function' && define.amd ? define('uikitcountdown', ['uikit-util'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitCountdown = factory(global.UIkit.util));
}(this, (function (uikitUtil) { 'use strict';
var Class = {
connected: function() {
!uikitUtil.hasClass(this.$el, this.$name) && uikitUtil.addClass(this.$el, this.$name);
}
};
var Component = {
mixins: [Class],
props: {
date: String,
clsWrapper: String
},
data: {
date: '',
clsWrapper: '.uk-countdown-%unit%'
},
computed: {
date: function(ref) {
var date = ref.date;
return Date.parse(date);
},
days: function(ref, $el) {
var clsWrapper = ref.clsWrapper;
return uikitUtil.$(clsWrapper.replace('%unit%', 'days'), $el);
},
hours: function(ref, $el) {
var clsWrapper = ref.clsWrapper;
return uikitUtil.$(clsWrapper.replace('%unit%', 'hours'), $el);
},
minutes: function(ref, $el) {
var clsWrapper = ref.clsWrapper;
return uikitUtil.$(clsWrapper.replace('%unit%', 'minutes'), $el);
},
seconds: function(ref, $el) {
var clsWrapper = ref.clsWrapper;
return uikitUtil.$(clsWrapper.replace('%unit%', 'seconds'), $el);
},
units: function() {
var this$1 = this;
return ['days', 'hours', 'minutes', 'seconds'].filter(function (unit) { return this$1[unit]; });
}
},
connected: function() {
this.start();
},
disconnected: function() {
var this$1 = this;
this.stop();
this.units.forEach(function (unit) { return uikitUtil.empty(this$1[unit]); });
},
events: [
{
name: 'visibilitychange',
el: uikitUtil.inBrowser && document,
handler: function() {
if (document.hidden) {
this.stop();
} else {
this.start();
}
}
}
],
update: {
write: function() {
var this$1 = this;
var timespan = getTimeSpan(this.date);
if (timespan.total <= 0) {
this.stop();
timespan.days
= timespan.hours
= timespan.minutes
= timespan.seconds
= 0;
}
this.units.forEach(function (unit) {
var digits = String(Math.floor(timespan[unit]));
digits = digits.length < 2 ? ("0" + digits) : digits;
var el = this$1[unit];
if (el.textContent !== digits) {
digits = digits.split('');
if (digits.length !== el.children.length) {
uikitUtil.html(el, digits.map(function () { return '<span></span>'; }).join(''));
}
digits.forEach(function (digit, i) { return el.children[i].textContent = digit; });
}
});
}
},
methods: {
start: function() {
this.stop();
if (this.date && this.units.length) {
this.$update();
this.timer = setInterval(this.$update, 1000);
}
},
stop: function() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}
};
function getTimeSpan(date) {
var total = date - Date.now();
return {
total: total,
seconds: total / 1000 % 60,
minutes: total / 1000 / 60 % 60,
hours: total / 1000 / 60 / 60 % 24,
days: total / 1000 / 60 / 60 / 24
};
}
if (typeof window !== 'undefined' && window.UIkit) {
window.UIkit.component('countdown', Component);
}
return Component;
})));
|
hljs.registerLanguage("handlebars",(()=>{"use strict";function e(...e){
return e.map((e=>{return(n=e)?"string"==typeof n?n:n.source:null;var n
})).join("")}return n=>{const a={
"builtin-name":"action bindattr collection component concat debugger each each-in get hash if in input link-to loc log lookup mut outlet partial query-params render template textarea unbound unless view with yield"
},s=/\[.*?\]/,t=/[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/,i=e("(",/'.*?'/,"|",/".*?"/,"|",s,"|",t,"|",/\.|\//,")+"),r=e("(",s,"|",t,")(?==)"),l={
begin:i,lexemes:/[\w.\/]+/},c=n.inherit(l,{keywords:{
literal:"true false undefined null"}}),o={begin:/\(/,end:/\)/},m={
className:"attr",begin:r,relevance:0,starts:{begin:/=/,end:/=/,starts:{
contains:[n.NUMBER_MODE,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,c,o]}}},d={
contains:[n.NUMBER_MODE,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,{begin:/as\s+\|/,
keywords:{keyword:"as"},end:/\|/,contains:[{begin:/\w+/}]},m,c,o],returnEnd:!0
},g=n.inherit(l,{className:"name",keywords:a,starts:n.inherit(d,{end:/\)/})})
;o.contains=[g];const b=n.inherit(l,{keywords:a,className:"name",
starts:n.inherit(d,{end:/\}\}/})}),u=n.inherit(l,{keywords:a,className:"name"
}),h=n.inherit(l,{className:"name",keywords:a,starts:n.inherit(d,{end:/\}\}/})})
;return{name:"Handlebars",
aliases:["hbs","html.hbs","html.handlebars","htmlbars"],case_insensitive:!0,
subLanguage:"xml",contains:[{begin:/\\\{\{/,skip:!0},{begin:/\\\\(?=\{\{)/,
skip:!0},n.COMMENT(/\{\{!--/,/--\}\}/),n.COMMENT(/\{\{!/,/\}\}/),{
className:"template-tag",begin:/\{\{\{\{(?!\/)/,end:/\}\}\}\}/,contains:[b],
starts:{end:/\{\{\{\{\//,returnEnd:!0,subLanguage:"xml"}},{
className:"template-tag",begin:/\{\{\{\{\//,end:/\}\}\}\}/,contains:[u]},{
className:"template-tag",begin:/\{\{#/,end:/\}\}/,contains:[b]},{
className:"template-tag",begin:/\{\{(?=else\}\})/,end:/\}\}/,keywords:"else"},{
className:"template-tag",begin:/\{\{(?=else if)/,end:/\}\}/,keywords:"else if"
},{className:"template-tag",begin:/\{\{\//,end:/\}\}/,contains:[u]},{
className:"template-variable",begin:/\{\{\{/,end:/\}\}\}/,contains:[h]},{
className:"template-variable",begin:/\{\{/,end:/\}\}/,contains:[h]}]}}})());
|
// Load Moongoose
var mongoose = require('mongoose');
// Automatically create a last modified date attribute that auto-updates
var lastMod = require('./lastMod');
// define the schema for our model
var organizationSchema = mongoose.Schema({
// The date this object was created
createdDate : { type: Date, default: Date.now },
});
organizationSchema.plugin(lastMod);
// create the model for organization and expose it to our app
module.exports = mongoose.model('Organization', organizationSchema);
|
jsonp({"cep":"64350000","cidade":"S\u00e3o Jo\u00e3o da Serra","uf":"PI","estado":"Piau\u00ed"});
|
import { escapeFormat } from '../../core/badge-urls/path-helpers.js'
import { redirector } from '../index.js'
function escapeFormatSlashes(t) {
return (
escapeFormat(t)
// Double slash
.replace(/\/\//g, '/')
)
}
/*
Old documentation, for reference:
<p>
<code>[OPTIONS]</code> can be:
<ul>
<li>
Nothing:
<code>…/website/…</code>
</li>
<li>
Online and offline text:
<code>…/website-up-down/…</code>
</li>
<li>
Online and offline text, then online and offline colors:
<code>…/website-up-down-green-orange/…</code></li>
</li>
</ul>
<table class="centered"><tbody>
<tr><td> Dashes <code>--</code>
</td><td> →
</td><td> <code>-</code> Dash
</td></tr>
<tr><td> Underscores <code>__</code>
</td><td> →
</td><td> <code>_</code> Underscore <br/>
</td></tr>
<tr><td> Slashes <code>//</code>
</td><td> →
</td><td> <code>/</code> Slash <br/>
</td></tr>
<tr><td> <code>_</code> or Space <code> </code>
</td><td> →
</td><td> <code> </code> Space
</td></tr>
</tbody></table>
</p>
*/
export default [
redirector({
category: 'monitoring',
route: {
base: '',
format:
'website-(([^-/]|--|//)+)-(([^-/]|--|//)+)(-(([^-/]|--|//)+)-(([^-/]|--|//)+))?/([^/]+)/(.+?)',
capture: [
// Some of these could be made into non-capturing groups so these unused
// params would not need to be declared.
'upMessage',
'unused2',
'downMessage',
'unused4',
'unused5',
'upColor',
'unused7',
'downColor',
'unused8',
'protocol',
'hostAndPath',
],
},
transformPath: () => '/website',
transformQueryParams: ({
upMessage,
downMessage,
upColor,
downColor,
protocol,
hostAndPath,
}) => ({
up_message: upMessage ? escapeFormatSlashes(upMessage) : undefined,
down_message: downMessage ? escapeFormatSlashes(downMessage) : undefined,
up_color: upColor,
down_color: downColor,
url: `${protocol}://${hostAndPath}`,
}),
dateAdded: new Date('2019-03-08'),
}),
redirector({
category: 'monitoring',
name: 'WebsiteUrlQueryParamRedirect',
route: {
base: 'website',
pattern: ':protocol(https|http)/:hostAndPath+',
},
transformPath: () => '/website',
transformQueryParams: ({ protocol, hostAndPath }) => ({
url: `${protocol}://${hostAndPath}`,
}),
dateAdded: new Date('2019-09-17'),
}),
]
|
var WidgetPreloader = Backbone.View.extend({
tagName: 'span',
className: 'preloader',
initialize: function(){
this.render();
},
render: function(){
$(this.el).html('<div class="spinner"><div class="bar1 bar"></div><div class="bar2 bar"></div><div class="bar3 bar"></div><div class="bar4 bar"></div><div class="bar5 bar"></div><div class="bar6 bar"></div><div class="bar7 bar"></div><div class="bar8 bar"></div><div class="bar9 bar"></div><div class="bar10 bar"></div><div class="bar11 bar"></div><div class="bar12 bar"></div></div>Loading...');
return this;
}
});
|
let a = 5; // 00000000000000000000000000000101
a ^= 3; // 00000000000000000000000000000011
console.log(a); // 00000000000000000000000000000110
// expected output: 6
|
angular.module('starter.controllers')
.controller('skillTreeControl', function ($scope, $storageServices, $ionicModal, $analytics, $window) {
$scope.showSkillMap = true;
$analytics.trackView('Skill Tree');
$scope.ratings = 0;
$scope.isInfinite = false;
$scope.learnedSkills = [];
$scope.modal = null;
$scope.openSkillsModal = function () {
$analytics.trackView('All Skills');
$ionicModal.fromTemplateUrl('templates/skills/my_skills.html', {
id: 'skills',
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
modal.show();
$scope.modal = modal;
});
};
$scope.closeSkillsModal = function () {
$scope.modal.hide();
};
$scope.$on('$ionicView.enter', function () {
// clear badge
$storageServices.set('badgePoints', 0);
var flareChild = {};
angular.forEach(ALL_SKILLS, function (skills, index) {
var skillFlareChild = {};
angular.forEach(skills, function (skill) {
$storageServices.get(skill.text, function (result) {
var rating = parseInt(result);
if (rating) {
$scope.showSkillMap = true;
skillFlareChild[skill.text] = [rating];
$scope.ratings = $scope.ratings + rating;
if (rating >= 0) {
$scope.learnedSkills.push({
skill: skill.text,
rating: rating
});
}
var MAX_SKILL_POINTS = 250;
if ($scope.ratings > MAX_SKILL_POINTS) {
$scope.isInfinite = true;
}
}
});
if (skillFlareChild) {
flareChild[index] = skillFlareChild
}
});
$storageServices.set('points', $scope.ratings);
});
if ($scope.ratings > 0) {
RenderSkillTree($window, {
"Skill": flareChild
});
RenderBubble($storageServices, $window);
} else {
$scope.showSkillMap = false;
}
});
});
|
import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import ClientListFilterComponent from './ClientListFilterComponent';
import ClientListItemComponent from './ClientListItemComponent';
class ClientListComponent extends React.Component {
constructor() {
super();
this.state = {
orderByDate: true,
gridView: false
}
}
setGridView(boolean) {
this.setState({
gridView: boolean
})
}
setSortedByDateState(boolean) {
this.setState({
orderByDate: boolean
})
}
chooseOrderByType() {
return this.state.orderByDate ? this.orderByDate() : this.orderByAlphabet();
}
orderByAlphabet() {
return _.orderBy(this.props.clientlist, 'clientName', 'asc');
}
orderByDate() {
return _.orderBy(this.props.clientlist, 'submitDate', 'desc');
}
render() {
return (
<div>
<ClientListFilterComponent
gridView={this.state.gridView}
changeToGridView={boolean => this.setGridView(boolean)}
orderByDate={this.state.orderByDate}
handleClick={boolean => this.setSortedByDateState(boolean)}
/>
<ul className={this.state.gridView ? "clientlist__list grid" : "clientlist__list"}>
{ this.chooseOrderByType().map(client => (
<ClientListItemComponent
gridView={this.state.gridView}
key={client.token}
getRequest={client => this.props.getRequest(client)}
client={client}/> ))}
</ul>
</div>
)
}
};
export default ClientListComponent;
|
jsonp({"cep":"59275500","cidade":"Ipiranga","uf":"RN","estado":"Rio Grande do Norte"});
|
var Entry = require("entry");
var reds = require("reds");
var transliterate = require("transliteration");
module.exports = function (req, callback) {
var blogID = req.blog.id;
// We couldn't find a search query
if (!req.query.q) {
return callback(null, []);
}
var q = transliterate(req.query.q);
var search = reds.createSearch("blog:" + blogID + ":search");
search.query(q).end(function (err, ids) {
if (err) return callback(err);
for (var i in ids) ids[i] = parseFloat(ids[i]);
Entry.get(blogID, ids, function (entries) {
return callback(null, entries);
});
});
};
|
import Vuex from 'vuex'
import store from './file-store'
export default new Vuex.Store({
state: {
characters: []
},
getters: {
characters: state => {
return state.characters;
},
fileNames: state => {
return store.getLists();
}
},
mutations: {
loadFile(state, fileName) {
state.characters = JSON.parse(store.loadFile(fileName));
}
},
actions: {
loadFile(context, fileName) {
context.commit('loadFile', fileName);
}
}
})
|
var Typeset = require("typeset");
module.exports = function typeset(req, res, next) {
var send = res.send;
res.send = function(string) {
var html = string instanceof Buffer ? string.toString() : string;
html = Typeset(html, { disable: ["hyphenate"] });
send.call(this, html);
};
next();
};
|
var _ = require("underscore-keypath");
var path = require("path");
var cli = require("cli");
var model = require("./parts/lib/model");
var Handlebars = require("handlebars");
var fs = require("fs");
var moment = require("moment");
var model = require("./parts/lib/model");
var template = Handlebars.compile(fs.readFileSync(path.join(__dirname, "generate.handlebars")).toString());
Handlebars.registerHelper("indent", function(level){
var indent = new Array(level + 1).join(" ");
var content = _(this.split(/[\r\n]+/g)).map(function (it){
return indent + it.trim();
}).join("\n");
return content;
});
Handlebars.registerHelper("comments", function(){
var contents = [];
var indent = " ";
_(this.descriptions).each(function (each) {
var lines = _(each.trim().split(/[\r\n]+/g)).map(function (it){
return indent + it.trim();
});
if(lines.length == 1){
contents = contents.concat("/**" + lines[0] + " */");
}
else{
contents = contents.concat(["/**"], lines, ["*/"]);
}
});
return contents.join("\n");
});
function Generator(options){
this.options = options;
return this;
}
Generator.prototype = {
generate : function(){
var me = this;
model.prefix = this.options.fieldPrefix;
model.fieldStyle = this.options.fieldStyle;
var generator = require(path.join(__dirname, "parts", this.options.type));
_(this.options.inputs).each(function(each){
generator.process.call(me, each);
});
model.trim();
var filename = path.basename(this.options.output);
var templateInput = _.extend({
"filename" : filename,
"macroName" : filename.replace(/[^a-zA-Z0-9]/g, "_"),
"date" : moment().format("llll"),
"groups" : model.groups,
"year" : moment().format("YYYY"),
"copyright" : this.options.copyright,
}, this.options.templateOverwrite);
var content = template(templateInput);
return content;
},
ok : cli.ok,
info : cli.info,
error : cli.error
};
module.exports = Generator;
|
module.exports = function(grunt) {
// Initializing the configuration object
grunt.initConfig({
copy: {
main: {
files: [
// includes files within path
{
expand: true,
flatten: true,
src: ['bower_components/bootstrap/fonts/*'],
dest: './fonts/',
filter: 'isFile'
},
{
expand: true,
flatten: true,
src: ['bower_components/fontawesome/fonts/*'],
dest: './fonts/',
filter: 'isFile'
},
]
}
},
// Task configuration
less: {
development: {
options: {
compress: true,
// minifying the result
},
files: {
// compiling styles.less into styles.css
'./css/main.min.css': './src/less/main.less'
}
}
},
concat: {
options: {
separator: ';',
},
js_frontend: {
src: [
'./bower_components/jquery/dist/jquery.js',
'./bower_components/bootstrap/dist/js/bootstrap.min.js',
'./src/js/plugins.js',
'./src/js/main.js'
],
dest: './js/main.js',
},
},
uglify: {
options: {
mangle: false
// Use if you want the names of your functions and variables
// unchanged.
},
frontend: {
files: {
'./js/main.min.js' : './js/main.js',
}
},
},
watch: {
js_frontend: {
files: [
// watched files
'./bower_components/bootstrap/dist/js/bootstrap.js',
'./src/js/main.js',
'./src/js/plugins.js',
],
// tasks to run
tasks: ['concat:js_frontend', 'uglify:frontend'],
},
less: {
files: ['./src/less/*.less',
'./src/less/**/*.less'
],
// watched files
tasks: ['less'],
// tasks to run
},
}
});
// Plugin loading
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
// Task definition
grunt.registerTask('default', ['watch']);
};
|
var GBYViewController = {};
GBYViewController.performSegueWithIdentifier = function() {};
GBYViewController.dismissViewControllerAnimated = function() {};
GBYViewController.interfaceOrientation = function() {};
GBYViewController.animateWithDurationAnimationsCompletion = function() {};
var GBYButton = {};
GBYButton.enabled = function() {};
GBYButton.hidden = function() {};
GBYButton.setTouchUpInsideCallback = function() {};
GBYButton.setTouchDownCallback = function() {};
GBYButton.setTitleForState = function() {};
var GBYBarButtonItem = {};
GBYBarButtonItem.enabled = function() {};
GBYBarButtonItem.setActionCallback = function() {};
GBYBarButtonItem.title = function() {};
var GBYImageView = {};
GBYImageView.clearImage = function() {};
GBYImageView.hidden = function() {};
var GBYSegmentedControl = {};
GBYSegmentedControl.enabled = function() {};
GBYSegmentedControl.setValueChangedCallback = function() {};
var GBYStepper = {};
GBYStepper.enabled = function() {};
GBYStepper.value = function() {};
GBYStepper.setValueChangedCallback = function() {};
var GBYSwitch = {};
GBYSwitch.enabled = function() {};
GBYSwitch.on = function() {};
GBYSwitch.setValueChangedCallback = function() {};
var GBYLabel = {};
GBYLabel.text = function() {};
GBYLabel.textColor = function() {};
GBYLabel.enabled = function() {};
GBYLabel.hidden = function() {};
GBYLabel.frame = function() {};
var GBYNavigationItem = {};
GBYNavigationItem.title = function() {};
var GBYTableView = {};
GBYTableView.hidden = function() {};
GBYTableView.frame = function() {};
GBYTableView.reloadData = function() {};
GBYTableView.reloadRowInSectionWithAnimation = function() {};
GBYTableView.scrollToRowInSectionAtScrollPositionAnimated = function() {};
GBYTableView.dataSource = function() {};
GBYTableView.delegate = function() {};
GBYTableView.beginUpdates = function() {};
GBYTableView.endUpdates = function() {};
GBYTableView.insertSectionWithRowAnimation = function() {};
GBYTableView.deleteSectionWithRowAnimation = function() {};
GBYTableView.insertRowInSectionWithRowAnimation = function() {};
GBYTableView.deleteRowInSectionWithRowAnimation = function() {};
GBYTableView.indexPathForSelectedRow = function() {};
GBYTableView.indexPathsForSelectedRows = function() {};
GBYTableView.allowsMultipleSelectionDuringEditing = function() {};
GBYTableView.setEditingAnimated = function() {};
GBYTableView.selectRowInSectionAnimatedScrollPosition = function() {};
var GBYTextField = {};
GBYTextField.enabled = function() {};
GBYTextField.hidden = function() {};
GBYTextField.text = function() {};
GBYTextField.textColor = function() {};
GBYTextField.setEditingDidBeginCallback = function() {};
GBYTextField.setEditingChangedCallback = function() {};
GBYTextField.setEditingDidEndCallback = function() {};
GBYTextField.setEditingDidEndOnExitCallback = function() {};
GBYTextField.becomeFirstResponder = function() {};
var GBYTableViewCell = {};
GBYTableViewCell.textLabel = function() {};
GBYTableViewCell.detailTextLabel = function() {};
var GBYColor = {};
GBYColor.colorWithRedGreenBlueAlpha = function() {};
GBYColor.blackColor = function() {};
GBYColor.darkGrayColor = function() {};
GBYColor.lightGrayColor = function() {};
GBYColor.whiteColor = function() {};
GBYColor.grayColor = function() {};
GBYColor.redColor = function() {};
GBYColor.greenColor = function() {};
GBYColor.blueColor = function() {};
GBYColor.cyanColor = function() {};
GBYColor.yellowColor = function() {};
GBYColor.magentaColor = function() {};
GBYColor.orangeColor = function() {};
GBYColor.purpleColor = function() {};
GBYColor.brownColor = function() {};
GBYColor.clearColor = function() {};
var GBYFetchedResultsController = {};
GBYFetchedResultsController.cljsDelegate = function() {};
GBYFetchedResultsController.performFetch = function() {};
GBYFetchedResultsController.objectAtSectionRow = function() {};
GBYFetchedResultsController.sectionCount = function() {};
GBYFetchedResultsController.numberOfObjectsInSection = function() {};
GBYFetchedResultsController.sectionIndexTitles = function() {};
var GBYSoundUtils = {};
GBYSoundUtils.playSoundWithNameAndExtension = function() {};
var GBYAlertUtils = {};
GBYAlertUtils.alertWithMessage = function() {};
|
/**
# @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0>
##############################################################################
# Copyright (c) 2016 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################
*/
/**
* React Routes
*
* @author: Vasu Srinivasan
* @since: 0.0.1
*/
import { IndexRoute, Redirect, Route } from 'react-router';
import React from "react";
import App from "./components/app";
import HomePage from './components/home-page'
import ProjectsPage from './components/projects-page'
import AuthorsPage from './components/authors-page'
import OrganizationsPage from './components/organizations-page'
import error404 from "./components/404";
export default (
<Route name="app" path="/" component={App}>
<IndexRoute component={HomePage}/>
<Route path="home" component={HomePage} />
<Route path="projects" component={ProjectsPage} />
<Route path="authors" component={AuthorsPage} />
<Route path="organizations" component={OrganizationsPage} />
<Route path="*" component={error404}/>
</Route>
);
|
function CarHelper(car) {
if (!(this instanceof arguments.callee)) {
return new CarHelper(car);
}
var backtrack = [];
car.helper = {
getElement: function (x, y) {
return car.table.children[y].children[x];
},
canMove: function (x, y) {
return /[wrgby\*]/.test(this.getElement(x, y).textContent);
},
gravity: function (x, y) {
return this.canMove(x, y) ? {x: x, y: y} : undefined;
},
left: function (x, y) {
x -= 1;
return x >= 0 ? this.gravity(x, y) : undefined;
},
right: function (x, y) {
x += 1;
return car.mapData.N > x ? this.gravity(x, y) : undefined;
},
up: function (x, y) {
y -= 1;
return y >= 0 ? this.gravity(x, y) : undefined;
},
down: function (x, y) {
y += 1;
return car.mapData.N > y ? this.gravity(x, y) : undefined;
},
random: function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
},
alreadyPassed: function (a, b) {
//FIXME : check for all the cars
var ways = car.way();
for (var i = 0, len = ways.length; i < len; i++) {
if (ways[i] === a.toPosition()) {
if (i > 0 && ways[i - 1] === b.toPosition())
return true;
if ((i + 1) < len && ways[i + 1] === b.toPosition())
return true;
}
}
return false;
},
direction: function () {
var where = []
, pos = car.position()
, x = pos.x
, y = pos.y;
if (backtrack.length === car.way().length) {
where = backtrack.pop();
} else {
// LEFT
var test = this.left(x, y);
if (test && !this.alreadyPassed(pos, test)) {
where.push(test);
}
// RIGHT
test = this.right(x, y);
if (test && !this.alreadyPassed(pos, test)) {
where.push(test);
}
// UP
test = this.up(x, y);
if (test && !this.alreadyPassed(pos, test)) {
where.push(test);
}
// DOWN
test = this.down(x, y);
if (test && !this.alreadyPassed(pos, test)) {
where.push(test);
}
}
if (where.length) {
var direction = where.splice(this.random(0, where.length), 1);
backtrack.push(where);
return direction.pop();
}
return undefined;
},
moveTo: function (x, y) {
var element = this.getElement(x, y)
, pos = car.position();
car.path(x + ',' + y, element.innerHTML);
element.innerHTML = 'w'.fontcolor(car.color());
car.way(x + ',' + y);
this.update();
return true;
},
backTo: function (x, y) {
var element = this.getElement(x, y)
, paths = car.path();
if (car.way().lastIndexOf(x + "," + y) === -1) {
element.innerHTML = paths[x + ',' + y];
}
this.update();
return true;
},
toCoord: function (str) {
var coord = str.split(',')
, y = Number(coord.pop())
, x = Number(coord.pop());
return {x: x, y: y};
},
update: function () {
var coord = this.toCoord(car.way().slice(-1).pop());
car.position(coord.x, coord.y);
},
move: function () {
var coord = this.direction();
if (coord) {
return this.moveTo(coord.x, coord.y);
}
var ways = car.way();
if (ways.length) {
var coord = this.toCoord(ways.pop());
return this.backTo(coord.x, coord.y);
}
return false;
}
};
return car;
}
|
//
// Speak To The Farmers ( 101 )
//
var log = require('../class.log'),
realmConfig = require('../../config.realm').config,
quest = require('../class.quest'),
questCondition = require('../class.questCondition').condition;
exports.questObject = function( args )
{
var self = this;
this.conditions = {};
this.checkConditions = function( _args )
{
var conditionsCompleted = 0;
//see if condition is met
var _callCondition = function( parameterName )
{
self.conditions[parameterName].checkState({
characterId: _args.characterId,
after: function()
{
conditionsCompleted++;
if( conditionsCompleted < nrConditions )
{
return;
}
quest.markCompleted({
characterId: _args.characterId,
questId: self.id,
questServer: args.questServer,
after: function(){}
});
}
});
}
var _checkAllConditions = function( )
{
for( var i in self.conditions )
{
_callCondition(i);
}
}
//if a conditions value is already known, start the check with it
if( "parameterName" in _args )
{
if( self.conditions[ _args.parameterName ].targetValue > _args.value )
{
return;
}
if( nrConditions == 1 )
{
quest.markCompleted({
characterId: _args.characterId,
questId: self.id,
questServer: args.questServer,
after: function(){}
});
return;
}
}
_checkAllConditions();
}
//
// Variables
//
this.id = 101;
var nrConditions = 1;
this.conditions['q101_1SpeakToTheFarmers'] = new questCondition({parameterName:'q101_1SpeakToTheFarmers', targetValue:1, quest: self, questServer: args.questServer});
return self;
}
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var partials = require('express-partials');
var methodOverride = require('method-override');
var session = require('express-session');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(partials());
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('Quiz 2015'));
app.use(session());
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
// Helpers dinámicos
app.use(function(req, res, next) {
// Guardar el path en session.redir para después del login.
if (!req.path.match(/\/login|\/logout/)) {
req.session.redir = req.path;
}
// Hacer visible req.session en las vistas.
res.locals.session = req.session;
next();
});
// Gestión del autologout.
app.use(function(req, res, next) {
var current_time = new Date();
var lastdate = req.session.time ? new Date(req.session.time): new Date();
if (req.session.user && !req.path.match(/\/logout/)) {
if ( (current_time.getMinutes() - 2) > lastdate.getMinutes() ) {
req.session.errors = [{"message": 'Sesión caducada'}];
delete req.session.user;
delete req.session.time;
res.redirect('/login');
} else {
console.log((current_time.getMinutes() - 2) + ' > '+ lastdate.getMinutes());
// Refrescamos el tiempo.
req.session.time = new Date();
next();
}
} else {
next();
}
});
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
errors: []
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {},
errors: []
});
});
module.exports = app;
|
angular.module('mainController',[])
.controller('mainController', function($rootScope, $location, Auth){
var vm = this;
vm.loggedIn = Auth.isLoggedIn();
// o rootscope é usado para detectar alterações na rota
// quando acontecer uma troca de rota (requisicao para outra pagina) verifica se tem um usuário logado
$rootScope.$on('$routeChangeStart',function(){
// pegar a pessoa que está logada
vm.loggedIn = Auth.isLoggedIn();
Auth.getUser().then(function(data){ // nao da pra usar success aqui porque quando falha, retorna uma promessa rejeitada
vm.user = data.data; // entao tem que ter algum tratamento pra quando isso acontece
}, function(response){ // no caso isso é feito no function(response)
});
});
// gerenciar o form de login
vm.doLogin = function() {
vm.processing = true; //variavel para mostrar q ta fazendo alguma coisa
Auth.login(vm.loginData.username, vm.loginData.password)
.success(function(data){
vm.processing = false;
if (data.success) $location.path('/users'); //se conseguiu logar, manda pra página de usuários
else vm.error = data.message;
});
};
// gerenciar o logout
vm.doLogout = function() {
Auth.logout();
vm.user = {}; // limpa os dados do usuario logado
$location.path('/login'); // redireciona para a página de login
};
});
|
// Scarlet Blaze Article Tool
// By: Jose Mulia
// http://www.scarletblaze.com
// Version: 1.1
ns4 = document.layers;
ie = document.all;
moz = document.getElementById && !document.all;
function changeFontSize (id, isIncrease) {
// 1 = increase
// 0 = decrease
var obj;
var size;
if (ns4) { alert ("Sorry, but NS4 does not allow font changes."); return false;
} else if (ie) {
// tested on ie6
// the font value is increased/decreased in em;
obj = document.getElementById(id);
size = obj.currentStyle.fontSize;
if (isIncrease) { size = parseFloat(size) + .1; // increase
} else { size = parseFloat(size) - .1; // decrease
}
obj.style.fontSize = size + "em";
} else if (moz) {
// only tested on firefox
// The next 2 lines work, but only return font size in px!
// So the font value is increased/decreased in px;
obj = window.getComputedStyle(document.getElementById(id), '');
size = obj.getPropertyValue('font-size'); // value only in px
if (isIncrease) { size = size = parseFloat(size) + 1; // increase
} else { size = size = parseFloat(size) - 1; // decrease
}
document.getElementById(id).style['fontSize'] = size + "px";
}
if (!obj) { alert("unrecognized ID"); return false; }
return true;
}
function changeAlignment (id, alignment) {
// align: "right", "left", "justify"
var obj;
if (ns4) { alert ("Sorry, but NS4 does not allow alignment change."); return false;
} else if (ie) {
// tested on ie6
// the font value is increased/decreased in em;
obj = document.getElementById(id);
obj.style.textAlign = alignment;
} else if (moz) {
// only tested on firefox
obj = window.getComputedStyle(document.getElementById(id), '');
document.getElementById(id).style['textAlign'] = alignment;
}
if (!obj) { alert("unrecognized ID"); return false; }
return true;
}
function Bookmark(docUrl, docTitle) {
if(document.all)
{
window.external.AddFavorite(docUrl, docTitle);
}
else
{
alert ("I'm sorry. Your browser: "+navigator.appName+" "+navigator.appVersion+ "\n doesn't support automatic bookmarking.\n You have to manually bookmark this page.");
}
}
function toPrint() {
window.print();
}
|
/*
============================================
G5Framework
=============================================
validation.js
==============================================
*/
var formValidation;
(function($){
formValidation = function(){
$('.form-validation').each(function() {
var _this = this,
_errorLabel = $(_this).find('.form-errors');
//Email Regex
$.validator.addMethod('emailRegex', function(value, element) {
return this.optional(element) || /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/i.test(value); },
'Email must contain only letters, numbers, and acceptable symbols.'
);
//Text Regex
$.validator.addMethod('textRegex', function(value, element) {
return this.optional(element) || /^([a-zA-Z '-]+)$/i.test(value); },
'No special characters allowed.'
);
//Not Equals Value
$.validator.addMethod('valueNotEquals', function(value, element, arg){
return arg != value; },
'Value must not equal arg.'
);
//Validate
$(_this).validate({
errorLabelContainer: _errorLabel,
messages: {
'name': {
required: 'Please enter a valid name'
},
'email': {
required: 'Please enter a valid email address'
}
},
rules: {
'name': {
minlength: 2,
maxlength: 22,
textRegex: true
},
'email': {
email: true,
maxlength: 30,
emailRegex: true
},
'primary-search-input': {
minlength: 2,
maxlength: 22,
textRegex: true
}
},
invalidHandler: function(form) {
//Error
// console.log('form validation: error');
},
submitHandler: function(form) {
// console.log("form submitted");
// console.log(_this);
if ($(_this).hasClass('seasonal')) {
sendFeedback();
return false;
}
// console.log("Submission");
if ($(_this).hasClass('top-ten')) {
// console.log("top ten");
}
var postData = $(_this).serialize();
//Success
// console.log('form validation: success');
// console.log(postData);
//$(_this).hide();
//$(_this).next('.thank-you').fadeIn('slow');
/*
$.ajax({
type: 'POST',
url: '/somewhere',
data: postData,
success: function() {
// console.log('ajax success');
return false;
}
});
*/
return false;
}
});
});//
if ( $('.form-validation').find('.action-link').length > 0 ) {
$('.form-validation').find('.button.action-link').on('click', function(event){
$(this).parent('form').submit();
event.preventDefault();
});
}
//Check Validation & Match Errors
$('.form-validation').submit(function(){
var phoneField = $('.phone-format'),
checkBoxes = $(this).find('input[type="checkbox"], input[type="radio"]');
//Remove dashes in phone field after submit
if ( phoneField.length > 0 ) {
phoneField.each(function() {
$(this).val( $(this).val().replace(/[^\d.]/g, '') );
});
};
//Add Errors
if ( checkBoxes.hasClass('error') ) {
var _invalid = checkBoxes.filter('.error');
_invalid.each(function(){
var _this = this,
_invalidName = $(_this).attr('name');
$('input[name="' + _invalidName + '"]').addClass('error').siblings('i').addClass('error');
});
};
});
};
}(jQuery));
|
/**
* Broadcast updates to client when the model changes
*/
'use strict';
var Post = require('./post.model');
exports.register = function(socket) {
Post.schema.post('save', function (doc) {
onSave(socket, doc);
});
Post.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
}
function onSave(socket, doc, cb) {
socket.emit('post:save', doc);
}
function onRemove(socket, doc, cb) {
socket.emit('post:remove', doc);
}
|
var express = require('express');
var router = express.Router();
/*
** www.g-trotter.eu/my-trip
*/
router.route('/')
.get(function(req, res) {
res.json({
path: 'www.g-trotter.eu/my-trip'
})
})
module.exports = router;
|
window.BOLDGRID = window.BOLDGRID || {};
BOLDGRID.EDITOR = BOLDGRID.EDITOR || {};
BOLDGRID.EDITOR.CONTROLS = BOLDGRID.EDITOR.CONTROLS || {};
BOLDGRID.EDITOR.CONTROLS.GENERIC = BOLDGRID.EDITOR.CONTROLS.GENERIC || {};
( function( $ ) {
'use strict';
var self,
BG = BOLDGRID.EDITOR;
BOLDGRID.EDITOR.CONTROLS.GENERIC.Fontsize = {
template: wp.template( 'boldgrid-editor-font-size' ),
render: function() {
var $control = $( this.template() );
BG.Panel.$element
.find( '.panel-body .customize' )
.find( '.section.size' )
.remove();
BG.Panel.$element.find( '.panel-body .customize' ).append( $control );
return $control;
},
bind: function() {
var $el = BG.Menu.getTarget( BG.Panel.currentControl ),
elementSize = $el.css( 'font-size' ),
defaultSize = elementSize ? parseInt( elementSize ) : 14;
defaultSize = 5 <= defaultSize ? defaultSize : 14;
BG.Panel.$element.find( '.section.size .value' ).html( defaultSize );
BG.Panel.$element.find( '.section.size .slider' ).slider( {
min: 5,
max: 115,
value: defaultSize,
range: 'max',
slide: function( event, ui ) {
BG.Panel.$element.find( '.section.size .value' ).html( ui.value );
BG.Controls.addStyle( $el, 'font-size', ui.value );
}
} );
}
};
self = BOLDGRID.EDITOR.CONTROLS.GENERIC.Fontsize;
} )( jQuery );
|
function main(){
alert("Se ha cargado la página.")
}
|
/* exported DwellClickIndicator */
const { Clutter, Gio, GLib, GObject, St } = imports.gi;
const PanelMenu = imports.ui.panelMenu;
const MOUSE_A11Y_SCHEMA = 'org.gnome.desktop.a11y.mouse';
const KEY_DWELL_CLICK_ENABLED = 'dwell-click-enabled';
const KEY_DWELL_MODE = 'dwell-mode';
const DWELL_MODE_WINDOW = 'window';
const DWELL_CLICK_MODES = {
primary: {
name: _("Single Click"),
icon: 'pointer-primary-click-symbolic',
type: Clutter.PointerA11yDwellClickType.PRIMARY,
},
double: {
name: _("Double Click"),
icon: 'pointer-double-click-symbolic',
type: Clutter.PointerA11yDwellClickType.DOUBLE,
},
drag: {
name: _("Drag"),
icon: 'pointer-drag-symbolic',
type: Clutter.PointerA11yDwellClickType.DRAG,
},
secondary: {
name: _("Secondary Click"),
icon: 'pointer-secondary-click-symbolic',
type: Clutter.PointerA11yDwellClickType.SECONDARY,
},
};
var DwellClickIndicator = GObject.registerClass(
class DwellClickIndicator extends PanelMenu.Button {
_init() {
super._init(0.5, _("Dwell Click"));
this._icon = new St.Icon({ style_class: 'system-status-icon',
icon_name: 'pointer-primary-click-symbolic' });
this.add_child(this._icon);
this._a11ySettings = new Gio.Settings({ schema_id: MOUSE_A11Y_SCHEMA });
this._a11ySettings.connect('changed::%s'.format(KEY_DWELL_CLICK_ENABLED), this._syncMenuVisibility.bind(this));
this._a11ySettings.connect('changed::%s'.format(KEY_DWELL_MODE), this._syncMenuVisibility.bind(this));
this._seat = Clutter.get_default_backend().get_default_seat();
this._seat.connect('ptr-a11y-dwell-click-type-changed', this._updateClickType.bind(this));
this._addDwellAction(DWELL_CLICK_MODES.primary);
this._addDwellAction(DWELL_CLICK_MODES.double);
this._addDwellAction(DWELL_CLICK_MODES.drag);
this._addDwellAction(DWELL_CLICK_MODES.secondary);
this._setClickType(DWELL_CLICK_MODES.primary);
this._syncMenuVisibility();
}
_syncMenuVisibility() {
this.visible =
this._a11ySettings.get_boolean(KEY_DWELL_CLICK_ENABLED) &&
this._a11ySettings.get_string(KEY_DWELL_MODE) == DWELL_MODE_WINDOW;
return GLib.SOURCE_REMOVE;
}
_addDwellAction(mode) {
this.menu.addAction(mode.name, this._setClickType.bind(this, mode), mode.icon);
}
_updateClickType(manager, clickType) {
for (let mode in DWELL_CLICK_MODES) {
if (DWELL_CLICK_MODES[mode].type == clickType)
this._icon.icon_name = DWELL_CLICK_MODES[mode].icon;
}
}
_setClickType(mode) {
this._seat.set_pointer_a11y_dwell_click_type(mode.type);
this._icon.icon_name = mode.icon;
}
});
|
'use strict';
var util = require('util');
var BaseController = require('hof').controllers.base;
var OriginalDocumentController = function OriginalDocumentController() {
BaseController.apply(this, arguments);
};
util.inherits(OriginalDocumentController, BaseController);
OriginalDocumentController.prototype.getValues = function getValues(req, res, callback) {
res.locals.backLink = 'other-documents';
BaseController.prototype.getValues.call(this, req, res, callback);
}
module.exports = OriginalDocumentController;
|
let React = require('react'),
SearchItem = require('./SearchItem');
let SearchAlbum = React.createClass({
contextTypes: {
updateRoute: React.PropTypes.func,
goBack: React.PropTypes.func,
data: React.PropTypes.array,
addTrack: React.PropTypes.func,
getAlbum: React.PropTypes.func
},
componentWillMount () {
this.context.getAlbum();
},
render () {
let tracks,
albumName,
artistName,
albumUrl,
albumId;
if (this.context.data.length > 0) {
tracks = this.context.data[0].data.map((d, i) => {
return (
<SearchItem key={i}
data={ d }
btnSrc="something.png"
onClick={ this.context.addTrack.bind(null, d.id) }
type="album-track"
/>
);
});
albumId = this.context.data[0].data[0].album.id;
albumName = this.context.data[0].data[0].name
artistName = this.context.data[0].data[0].artist.name;
albumUrl = `http://direct.rhapsody.com/imageserver/v2/albums/${albumId}/images/170x170.jpg`;
}
return (
<div>
<div className="album-header">
<img src={ albumUrl } />
<div className="title">
<p>{ albumName }</p>
<p>{ artistName }</p>
</div>
</div>
<div className="searchResults">
<div className="searchListContainer">
<span className="listHeader">Tracks</span>
<a className="navLink" onClick={ this.context.goBack }>{ '< Back' }</a>
<ul className="list song-title-tile">
{ tracks }
</ul>
</div>
</div>
</div>
);
}
});
module.exports = SearchAlbum;
|
Template.billingInfo.helpers({
expMonth: function() {
return [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
]
},
expYear: function() {
var curYear = moment().format('YYYY');
var yearsArray = [];
for (i = 0; i < 10; i++) {
yearsArray.push(parseInt(curYear)+i);
}
return yearsArray;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.