text
stringlengths 2
6.14k
|
|---|
const path = require('path');
const fs = require('fs');
const { flattenDeep, memoize } = require('lodash');
function locateSourceFile(modulesPath, moduleName, importPath = '') {
const srcPrefixes = ['src', ''];
const indexFiles = ['', 'index'];
const extensions = ['.ts', '.tsx', '.js', '.jsx'];
const paths = srcPrefixes.map(prefix =>
extensions.map(extension =>
indexFiles.map(indexFile => {
return path.join(modulesPath, moduleName, prefix, importPath, indexFile) + extension;
}),
),
);
return flattenDeep(paths).find(p => fs.existsSync(p));
}
function _getAllSpinnakerPackages(modulesPath) {
const paths = fs.readdirSync(modulesPath);
return paths
.map(file => path.join(modulesPath, file))
.filter(child => fs.statSync(child).isDirectory())
.map(packagePath => packagePath.split('/').pop());
}
const getAllSpinnakerPackages = memoize(_getAllSpinnakerPackages);
function makeResult(pkg, importPath) {
const subPkg = getSubPackage(pkg, importPath);
importPath = importPath || '';
const importPathWithSlash = importPath ? '/' + importPath : '';
return pkg ? { pkg, subPkg, importPath, importPathWithSlash } : undefined;
}
/**
* Given '@spinnaker/amazon', returns { pkg: 'amazon', path: undefined };
* Given '@spinnaker/core/deep/import', returns { pkg: 'core', path: 'deep/import' };
* Given 'anythingelse', returns undefined
*/
function getImportFromNpm(importString) {
const regexp = new RegExp(`^@spinnaker/([^/]+)(/.*)?$`);
const [, pkg, importPath] = regexp.exec(importString) || [];
return makeResult(pkg, importPath);
}
/**
* If code imports from a known spinnaker package alias
* Given 'amazon', returns { pkg: 'amazon', path: undefined };
* Given 'core/deep/import', returns { pkg: 'core', path: 'deep/import' };
* Given 'nonspinnakerpackage/deep/import', returns undefined
*/
function getAliasImport(allSpinnakerPackages, importString) {
const [, pkg, importPath] = /^([^/]+)\/(.*)$/.exec(importString) || [];
return allSpinnakerPackages.includes(pkg) ? makeResult(pkg, importPath) : undefined;
}
/**
* If code imports from .. relatively, returns the potential alias
* Assume all examples are from a file /app/scripts/modules/core/subdir/file.ts
* Given '../../amazon/loadbalancers/loadbalancer', returns { pkg: 'amazon', path: 'loadbalancers/loadbalancer' };
* Given '../widgets/button', returns { pkg: 'core', path: 'widgets/button' };
* Given './file2', returns { pkg: 'core', path: 'subdir/file2' };
*/
function getRelativeImport(sourceFileName, modulesPath, importString) {
if (!importString.startsWith('../')) {
return undefined;
}
const resolvedPath = path.resolve(sourceFileName, importString);
const maybeImport = path.relative(modulesPath, resolvedPath);
const [pkg, ...rest] = maybeImport.split(path.sep);
return pkg ? makeResult(pkg, rest.join('/')) : undefined;
}
function _getSourceFileDetails(sourceFile) {
const [, modulesPath, ownPackage, filePath] =
/^(.*app\/scripts\/modules)\/([^/]+)\/(?:src\/)?(.*)$/.exec(sourceFile) || [];
const ownSubPackage = getSubPackage(ownPackage, filePath);
const sourceDirectory = path.resolve(sourceFile, '..');
return { modulesPath, sourceDirectory, ownPackage, ownSubPackage, filePath };
}
function getSubPackage(packageName, filePath) {
if (packageName === 'kubernetes') {
// subpackage is v1/foo or v2/foo
const [, subPkg] = /^((?:v[12]\/)?[^/]+)\/?.*/.exec(filePath) || [];
return subPkg;
} else {
const [, subPkg] = /^([^/]+)\/?.*/.exec(filePath) || [];
return subPkg;
}
}
const getSourceFileDetails = memoize(_getSourceFileDetails);
module.exports = {
getAliasImport,
getAllSpinnakerPackages,
getImportFromNpm,
getRelativeImport,
getSourceFileDetails,
locateSourceFile,
};
|
"use strict";
var marvelNameGenerator = require('./index.js');
console.log("Expect to see a cool name:\n"+marvelNameGenerator());
|
class Queue {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
remove() {
return this.items.shift();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
module.exports = Queue;
|
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific
*
*/
import _ from "lodash";
/**
* Given a set of nodes with id and parentId constructs a 'searchStr' property for each
* node which is the concatenation of a specified property (attr) (or function) of all the nodes
* parent nodes.
*/
export function prepareSearchNodes(nodes = [],
attr = "name",
parentKey = "parentId") {
const nodesById = _.keyBy(nodes, "id");
const attrFn = _.isString(attr)
? n => n[attr]
: attr;
return _.map(nodes, n => {
let ptr = n;
let searchStr = "";
const nodePath = [];
while (ptr) {
nodePath.push(ptr);
searchStr += (attrFn(ptr) || "") + " ";
const parentId = ptr[parentKey];
ptr = nodesById[parentId];
}
return {
searchStr: searchStr.toLowerCase(),
node: n,
nodePath
};
});
}
/**
* The given `termStr` will be tokenised and
* all nodes (given in `searchNodes`) which contain all tokens
* will be returned (de-duped).
*
* Use `prepareSearchNodes` to prepare the search nodes.
* @param termStr
* @param searchNodes
*/
export function doSearch(termStr = "", searchNodes = []) {
const terms = _.split(termStr.toLowerCase(), /\W+/);
return _
.chain(searchNodes)
.filter(sn => {
const noTerms = termStr.trim().length === 0;
const allMatch = _.every(terms, t => sn.searchStr.indexOf(t) >=0);
return noTerms || allMatch;
})
.flatMap("nodePath")
.uniqBy(n => n.id)
.value();
}
/**
* Given data that looks like:
*
* [ { id: "", parentId: ?, ... } , .. ]
*
* Gives back an array of top level objects which have children
* nested in them, the result looks something like:
*
* [ id: "", parentId : ?, parent : {}?, children : [ .. ], ... }, .. ]
*
* @param nodes
* @param parentsAsRefs - whether to include parent as references or simple ids
* @returns {Array}
*/
export function populateParents(nodes, parentsAsRefs = true) {
const byId = _.chain(_.cloneDeep(nodes))
.map(u => _.merge(u, { children: [], parent: null }))
.keyBy("id")
.value();
_.each(_.values(byId), u => {
if (u.parentId) {
const parent = byId[u.parentId];
if (parent) {
parent.children.push(u);
u.parent = parentsAsRefs
? parent
: parent.id;
}
}
});
return _.values(byId);
}
export function buildHierarchies(nodes, parentsAsRefs = true) {
// only give back root element/s
return _.reject(populateParents(nodes, parentsAsRefs), n => n.parent);
}
export const reduceToSelectedNodesOnly = (nodes, selectedNodeIds = []) => {
const byId = _.keyBy(nodes, d => d.id);
const selectedNodesOnly = _
.chain(selectedNodeIds)
.map(nId => byId[nId])
.compact()
.value();
const selectedWithParents = _
.chain(selectedNodesOnly)
.flatMap(n => _.concat([n], getParents(n, d => byId[d.parentId])))
.uniq()
.value();
return selectedWithParents;
}
/**
* Given a forest like structure (typically generated by buildHierarchies)
* returns a flattened map object representing the hierarchical structure,
* the map is indexed by the value returned by the keyFn.
*
* The second argument is a function which returns the key value for a given node
*
* End users should call this function without passing a third argument
* as it is simply the accumulator used when recursing down the branches of the
* trees.
*/
export function indexHierarchyByKey(tree = [], keyFn = n => n.id, acc = {}) {
_.forEach(tree, node => {
acc[keyFn(node)] = node;
indexHierarchyByKey(node.children, keyFn, acc);
});
return acc;
}
export function groupHierarchyByKey(tree = [], keyFn = n => n.id, acc = {}) {
_.forEach(tree, node => {
const key = keyFn(node);
const bucket = acc[key] || [];
bucket.push(node)
acc[key] = bucket;
groupHierarchyByKey(node.children, keyFn, acc);
});
return acc;
}
export function flattenChildren(node, acc = []) {
_.forEach(node.children || [], child => {
acc.push(child);
flattenChildren(child, acc);
});
return acc;
}
/**
The wix tree widget does deep comparisons.
Having parents as refs therefore blows the callstack.
This method will replace refs with id's.
*/
export function switchToParentIds(treeData = []) {
_.each(treeData, td => {
td.parent = td.parent ? td.parent.id : null;
switchToParentIds(td.children);
});
return treeData;
}
export function findNode(nodes = [], id) {
const found = _.find(nodes, { id });
if (found) return found;
for(let i = 0; i < nodes.length; i++) {
const f = findNode(nodes[i].children, id);
if (f) return f;
}
return null;
}
/**
*
* @param node
* @param getParentFn - function to resolve parent, defaults to `n => n.parent`
* @returns {Array}
*/
export function getParents(node, getParentFn = (n) => n.parent) {
if (! node) return [];
let ptr = getParentFn(node);
const result = [];
while (ptr) {
result.push(ptr);
ptr = getParentFn(ptr);
}
return result;
}
|
import React from 'react';
import { graphql } from 'react-relay';
import { makeFilter } from '@ncigdc/utils/filters';
import { compose, withPropsOnChange } from 'recompose';
import { BaseQuery } from '@ncigdc/modern_components/Query';
export default (Component: ReactClass<*>) =>
compose(
withPropsOnChange(['projectId', 'mutated'], ({ projectId, mutated }) => {
return {
variables: {
filters: makeFilter([
{
field: 'cases.project.project_id',
value: [projectId],
},
...(mutated
? [{ field: 'cases.available_variation_data', value: ['ssm'] }]
: []),
]),
},
};
}),
)((props: Object) => {
return (
<BaseQuery
parentProps={props}
name="HasCases"
variables={props.variables}
Component={Component}
query={graphql`
query HasCases_relayQuery($filters: FiltersArgument) {
viewer {
explore {
cases {
hits(first: 0, filters: $filters) {
total
}
}
}
}
}
`}
/>
);
});
|
'use strict';
/**
* NetSuite Records
* @return {Records}
*/
var Records = module.exports = {};
Records.RecordRef = require('./recordRef');
|
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
describe("Unit: orgUserService", function () {
var $httpBackend;
var orgUserServiceSUT;
var targetProviderStub;
var $rootScope;
beforeEach(module('app'));
beforeEach(module(function($provide){
targetProviderStub = {}
$provide.value('targetProvider', targetProviderStub);
}));
beforeEach(inject(function (_orgUserService_, $injector, _$httpBackend_, _$rootScope_) {
$httpBackend = _$httpBackend_;
orgUserServiceSUT = _orgUserService_;
$rootScope = _$rootScope_;
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should call for users from apropriate organization on refresh', inject(function () {
targetProviderStub.getOrganization = sinon.stub().returns({ guid: "1234" });
var callbackSpied = sinon.stub();
$httpBackend.expectGET('/rest/orgs/1234/users').respond(200, []);
orgUserServiceSUT.getAll()
.then(callbackSpied);
$httpBackend.flush();
expect(callbackSpied.called).to.be.true;
}));
it('should fail while calling for users form unavailable organization on refresh', inject(function () {
targetProviderStub.getOrganization = sinon.stub().returns(null);
var errcallbackSpied = sinon.stub();
orgUserServiceSUT.getAll().catch(errcallbackSpied);
$rootScope.$digest();
expect(errcallbackSpied.called).to.be.true;
}));
it('should send POST on adding user', inject(function () {
var user = {
username: "waclaw",
roles: ["manager"]
};
targetProviderStub.getOrganization = sinon.stub().returns({ guid: "1234" });
$httpBackend.expectPOST('/rest/orgs/1234/users').respond(201, {});
var callbackSpied = sinon.stub();
orgUserServiceSUT.addUser(user).then(callbackSpied);
$httpBackend.flush();
expect(callbackSpied.called).to.be.true;
}));
});
|
import '@polymer/iron-icon/iron-icon.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/paper-ripple/paper-ripple.js';
import '@polymer/paper-item/paper-icon-item.js';
import '@polymer/paper-icon-button/paper-icon-button.js';
import {html, PolymerElement} from '@polymer/polymer';
import css from './dashboard-view.css';
import template from './dashboard-view.pug';
import './card-styles.js';
import './iframe-link.js';
import './notebooks-card.js';
import './pipelines-card.js';
import './resource-chart.js';
import {getGCPData} from './resources/cloud-platform-data.js';
import utilitiesMixin from './utilities-mixin.js';
export class DashboardView extends utilitiesMixin(PolymerElement) {
static get template() {
return html([`
<style include="card-styles">
${css.toString()}
</style>
${template()}
`]);
}
/**
* Object describing property-related metadata used by Polymer features
*/
static get properties() {
return {
documentationItems: Array,
quickLinks: Array,
namespace: {
type: Object,
observer: '_namespaceChanged',
},
platformDetails: Object,
platformInfo: {
type: Object,
observer: '_platformInfoChanged',
},
};
}
/**
* Observer for platformInfo property
*/
_platformInfoChanged() {
if (this.platformInfo && this.platformInfo.providerName === 'gce') {
this.platformName = 'GCP';
const pieces = this.platformInfo.provider.split('/');
let gcpProject = '';
if (pieces.length >= 3) {
gcpProject = pieces[2];
}
this.platformDetails = getGCPData(gcpProject);
}
}
/**
* Rewrites the links adding the namespace as a query parameter.
* @param {namespace} namespace
*/
_namespaceChanged(namespace) {
this.quickLinks.map((quickLink) => {
quickLink.link = this.buildHref(quickLink.link, {ns: namespace});
return quickLink;
});
// We need to deep-copy and re-assign in order to trigger the
// re-rendering of the component
this.quickLinks = JSON.parse(JSON.stringify(this.quickLinks));
}
}
customElements.define('dashboard-view', DashboardView);
|
/*
* @Author: yw850
* @Date: 2017-07-24 18:13:22
* @Last Modified by: yw850
* @Last Modified time: 2017-07-24 18:41:42
*/
'use strict';
require('./index.css')
require('page/common/header/index.js');
require('page/common/nav/index.js');
var _mm = require('util/mm.js');
var _payment = require('service/payment-service.js');
var templateIndex = require('./index.string');
// page逻辑部分
var page = {
data : {
orderNumber : _mm.getUrlParam('orderNumber')
},
init : function(){
this.onLoad();
},
onLoad : function(){
this.loadPaymentInfo();
},
loadPaymentInfo : function(){
var paymentHtml = '',
_this = this,
$pageWrap = $('.page-wrap');
// loading icon
$pageWrap.html('<div class="loading"></div>');
_payment.getPaymentInfo(this.data.orderNumber, function(res){
// render
paymentHtml = _mm.renderHtml(templateIndex, res);
$pageWrap.html(paymentHtml);
_this.listenOrderStatus();
}, function(errMsg){
$pageWrap.html('<p class="err-tip">' + errMsg + '</p>');
});
},
// 监听订单状态,轮询
listenOrderStatus : function(){
var _this = this;
this.paymentTimer = window.setInterval(function(){
_payment.getPaymentStatus(_this.data.orderNumber, function(res){
if (res === true) {
window.location.href = './result.html?type=payment&orderNumber=' + _this.data.orderNumber;
}
});
}, 5e3);
}
};
$(function(){
page.init();
});
|
/* eslint-env jest */
jest.unmock('../as-array');
import {
asArray,
} from '../as-array';
describe('asArray()', () => {
it('returns input as it is if an array', () => {
expect(asArray([1, 2, 3])).toEqual([1, 2, 3]);
});
it('converts scalar value to an array which contains it', () => {
expect(asArray(42)).toEqual([42]);
});
it('converts null and undefined to an empty array', () => {
expect(asArray(null)).toEqual([]);
expect(asArray(undefined)).toEqual([]);
});
});
|
'use strict';
describe('myApp.view3 module', function() {
var scope, view3Ctrl;
beforeEach(module('myApp.view3'));
beforeEach(module('matchingServices'));
beforeEach(inject(function ($controller, $rootScope) { // inject $rootScope
scope = $rootScope.$new();
view3Ctrl = $controller('View3Ctrl',{$scope : scope});
}));
describe('view3 controller', function(){
it('should ....', function() {
//spec body
expect(view3Ctrl).toBeDefined();
});
});
});
|
import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
constructor(ref: Firebase) {
this.ref = ref;
}
asArray() {
return new FirebaseArray(this.ref);
}
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: Firebase) {
this.ref = ref;
this.list = [];
// listen for changes at the Firebase instance
this.ref.on('child_added', this.created.bind(this), this.error);
this.ref.on('child_moved', this.moved.bind(this), this.error);
this.ref.on('child_changed', this.updated.bind(this), this.error);
this.ref.on('child_removed', this.removed.bind(this), this.error);
// determine when initial load is completed
// ref.once('value', function() { resolve(null); }, resolve);
}
getItem(recOrIndex: any) {
var item = recOrIndex;
if(typeof(recOrIndex) === "number") {
item = this.getRecord(recOrIndex);
}
return item;
}
getChild(recOrIndex: any) {
var item = this.getItem(recOrIndex);
return this.ref.child(item._key);
}
add(rec: any) {
this.ref.push(rec);
}
remove(recOrIndex: any) {
this.getChild(recOrIndex).remove();
}
save(recOrIndex: any) {
var item = this.getItem(recOrIndex);
this.getChild(recOrIndex).update(item);
}
keyify(snap) {
var item = snap.val();
item._key = snap.key();
return item;
}
created(snap) {
debugger;
var addedValue = this.keyify(snap);
this.list.push(addedValue);
}
moved(snap) {
var key = snap.key();
this.spliceOut(key);
}
updated(snap) {
var key = snap.key();
var indexToUpdate = this.indexFor(key);
this.list[indexToUpdate] = this.keyify(snap);
}
removed(snap) {
var key = snap.key();
this.spliceOut(key);
}
bulkUpdate(items) {
this.ref.update(items);
}
spliceOut(key) {
var i = this.indexFor(key);
if( i > -1 ) {
return this.list.splice(i, 1)[0];
}
return null;
}
indexFor(key) {
var record = this.getRecord(key);
return this.list.indexOf(record);
}
getRecord(key) {
return this.list.find((item) => key === item._key);
}
}
|
/**
* epubBundle
*
* Copyright 2015 David Herron
*
* This file is part of epubtools (http://akashacms.com/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var util = require('util');
var epubber = require('../epubber');
module.exports = function(grunt) {
grunt.registerTask('epubBundle', function() {
var renderTo = grunt.config.get('epubtools.renderTo');
var epubFileName = grunt.config.get('epubtools.bookYaml.epub');
var done = this.async();
epubber.bundleEPUB(renderTo, epubFileName)
.then(() => { done(); })
.catch(err => { done(err); });
});
};
|
var fs = require('fs');
var path = require('path');
var createSourceMapLocatorPreprocessor = function(args, logger, helper) {
var log = logger.create('preprocessor.sourcemap');
return function(content, file, done) {
function sourceMapData(data){
file.sourceMap = JSON.parse(data);
done(content);
}
function inlineMap(inlineData){
var data;
var b64Match = inlineData.match(/^data:.+\/(.+);base64,(.*)$/);
if (b64Match !== null && b64Match.length == 3) {
// base64-encoded JSON string
log.debug('base64-encoded source map for', file.originalPath);
var buffer = new Buffer(b64Match[2], 'base64');
sourceMapData(buffer.toString());
} else {
// straight-up URL-encoded JSON string
log.debug('raw inline source map for', file.originalPath);
sourceMapData(decodeURIComponent(inlineData.slice('data:application/json'.length)));
}
}
function fileMap(mapPath){
fs.exists(mapPath, function(exists) {
if (!exists) {
done(content);
return;
}
fs.readFile(mapPath, function(err, data) {
if (err){ throw err; }
log.debug('external source map exists for', file.originalPath);
sourceMapData(data);
});
});
}
var lastLine = content.split(new RegExp(require('os').EOL)).pop();
var match = lastLine.match(/^\/\/#\s*sourceMappingURL=(.+)$/);
var mapUrl = match && match[1];
if (!mapUrl) {
fileMap(file.path + ".map");
} else if (/^data:application\/json/.test(mapUrl)) {
inlineMap(mapUrl);
} else {
fileMap(path.resolve(path.dirname(file.path), mapUrl));
}
};
};
createSourceMapLocatorPreprocessor.$inject = ['args', 'logger', 'helper'];
// PUBLISH DI MODULE
module.exports = {
'preprocessor:sourcemap': ['factory', createSourceMapLocatorPreprocessor]
};
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(name) {
// [START vision_v1p3beta1_generated_ProductSearch_DeleteReferenceImage_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The resource name of the reference image to delete.
* Format is:
* `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`
*/
// const name = 'abc123'
// Imports the Vision library
const {ProductSearchClient} = require('@google-cloud/vision').v1p3beta1;
// Instantiates a client
const visionClient = new ProductSearchClient();
async function callDeleteReferenceImage() {
// Construct request
const request = {
name,
};
// Run request
const response = await visionClient.deleteReferenceImage(request);
console.log(response);
}
callDeleteReferenceImage();
// [END vision_v1p3beta1_generated_ProductSearch_DeleteReferenceImage_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
load("jstests/libs/slow_weekly_util.js");
test = new SlowWeeklyMongod("conc_update");
db = test.getDB("concurrency");
db.dropDatabase();
NRECORDS = 3 * 1024 * 1024;
print("loading " + NRECORDS + " documents (progress msg every 1024*1024 documents)");
var bulk = db.conc.initializeUnorderedBulkOp();
for (var i = 0; i < NRECORDS; i++) {
bulk.insert({x: i});
}
assert.writeOK(bulk.execute());
print("making an index (this will take a while)");
db.conc.ensureIndex({x: 1});
var c1 = db.conc.count({x: {$lt: NRECORDS}});
updater = startParallelShell(
"db = db.getSisterDB('concurrency');\
db.concflag.insert({ inprog: true });\
sleep(20);\
assert.writeOK(db.conc.update({}, \
{ $inc: { x: " +
NRECORDS +
"}}, false, true)); \
assert.writeOK(db.concflag.update({}, { inprog: false }));");
assert.soon(function() {
var x = db.concflag.findOne();
return x && x.inprog;
}, "wait for fork", 30000, 1);
querycount = 0;
decrements = 0;
misses = 0;
assert.soon(function() {
c2 = db.conc.count({x: {$lt: NRECORDS}});
print(c2);
querycount++;
if (c2 < c1)
decrements++;
else
misses++;
c1 = c2;
return !db.concflag.findOne().inprog;
}, "update never finished", 2 * 60 * 60 * 1000, 10);
print(querycount + " queries, " + decrements + " decrements, " + misses + " misses");
assert.eq(NRECORDS, db.conc.count(), "AT END 1");
updater(); // wait()
test.stop();
|
import { postToServer } from "../app/utils";
import { wait } from "../app/utils";
/**
* Google Authentication and linking module
* @returns {{link: function:object, login: function}}
*/
const googleProvider = new firebase.auth.GoogleAuthProvider();
function callIfFunction(func, arg1, arg2) {
if ($.isFunction(func))
func(arg1, arg2);
}
export function login() {
return firebase.auth().signInWithPopup(googleProvider)
.then(function (result) {
const userLoggedIn = result && result.user;
if (userLoggedIn)
return result.user.getIdToken(false);
else
throw Error('Could not authenticate');
});
}
/**
* Google Linking Module
* @returns {{linkGoogle: function(callback), unlinkGoogle: function(callback), isGoogleLinked: function(callback}}
*/
export function link() {
function getProviderData(providerDataArray, providerId) {
if (!providerDataArray)
return null;
for (var i = 0; i < providerDataArray.length; i++)
if (providerDataArray[i].providerId === providerId)
return providerDataArray[i];
return null;
}
function isProvider(providerData, providerId) {
return getProviderData(providerData, providerId) !== null;
}
function updateUser(user, providerData) {
if (!providerData)
return;
const updateUser = {};
if (!user.displayName)
updateUser.displayName = providerData.displayName;
if (!user.photoURL)
updateUser.photoURL = providerData.photoURL;
user.updateProfile(updateUser)
.then(function () {
return firebase.auth().currentUser.getIdToken(false);
}).then(function (token) {
return postToServer('/profile/api/link', token);
}).then(function (response) {
if (response !== 'OK')
return;
wait(5000).then(function () {
window.location = '/profile?refresh';
});
});
}
function accountLinked(linkCallback, user) {
callIfFunction(linkCallback, true);
updateUser(user, getProviderData(user.providerData, googleProvider.providerId));
}
function deletePreviousUser(prevUser, credential) {
const auth = firebase.auth();
return auth.signInWithCredential(credential)
.then(function(user) {
return user.delete();
}).then(function() {
return prevUser.linkWithCredential(credential);
}).then(function() {
return auth.signInWithCredential(credential);
});
}
return {
linkGoogle: function (linkCallback) {
firebase.auth().currentUser.linkWithPopup(googleProvider)
.then(function(result) {
accountLinked(linkCallback, result.user);
}).catch(function(error) {
if (error.code === 'auth/credential-already-in-use') {
const prevUser = firebase.auth().currentUser;
const credential = error.credential;
deletePreviousUser(prevUser, credential)
.then(function (user) {
accountLinked(linkCallback, user);
}).catch(function(error) {
callIfFunction(linkCallback, false, error);
});
} else {
callIfFunction(linkCallback, false, error);
}
});
},
unlinkGoogle: function (unlinkCallback) {
firebase.auth().currentUser.unlink(googleProvider.providerId)
.then(function () {
callIfFunction(unlinkCallback, true);
}).catch(function (error) {
callIfFunction(unlinkCallback, false, error);
});
},
isGoogleLinked: function (linked) {
firebase.auth().onAuthStateChanged(function (user) {
if (!$.isFunction(linked))
return;
if (user) {
linked(isProvider(user.providerData, googleProvider.providerId));
} else {
linked(); // Trigger hiding the button
}
});
}
};
}
export default {
link,
login
}
|
import Ember from 'ember';
const { Controller } = Ember;
export default Controller.extend({
columns: [
{
propertyName : 'name',
template : 'components/ui-table/cell/cell-event',
title : 'Name'
},
{
propertyName : 'starts-at',
template : 'components/ui-table/cell/cell-date',
title : 'Date'
},
{
propertyName : 'roles',
template : 'components/ui-table/cell/cell-roles',
title : 'Roles',
disableSorting : true,
disableFiltering : true
},
{
propertyName : 'sessionsByState',
template : 'components/ui-table/cell/cell-sessions',
title : 'Sessions',
disableSorting : true,
disableFiltering : true
},
{
propertyName : 'speakers.length',
title : 'Speakers',
disableSorting : true,
disableFiltering : true
},
{
propertyName : 'tickets',
template : 'components/ui-table/cell/cell-tickets',
title : 'Tickets',
disableSorting : true,
disableFiltering : true
},
{
propertyName : 'url',
template : 'components/ui-table/cell/cell-link',
title : 'Public URL',
disableSorting : true,
disableFiltering : true
},
{
template : 'components/ui-table/cell/cell-buttons',
title : 'Action',
disableSorting : true,
disableFiltering : true
}
],
actions: {
moveToDetails(id) {
this.transitionToRoute('events.view', id);
},
editEvent(id) {
this.transitionToRoute('events.view.edit.basic-details', id);
},
openDeleteEventModal(id, name) {
this.set('isEventDeleteModalOpen', true);
this.set('confirmName', '');
this.set('eventName', name);
this.set('eventId', id);
},
deleteEvent() {
this.set('isLoading', true);
this.store.findRecord('event', this.get('eventId'), { backgroundReload: false }).then(function(event) {
event.destroyRecord();
})
.then(() => {
this.notify.success(this.l10n.t('Event has been deleted successfully.'));
})
.catch(()=> {
this.notify.error(this.l10n.t('An unexpected error has occurred.'));
})
.finally(() => {
this.set('isLoading', false);
});
this.set('isEventDeleteModalOpen', false);
}
}
});
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(fulfillment, updateMask) {
// [START dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The fulfillment to update.
*/
// const fulfillment = {}
/**
* Required. The mask to control which fields get updated. If the mask is not
* present, all fields will be updated.
*/
// const updateMask = {}
// Imports the Dialogflow library
const {FulfillmentsClient} = require('@google-cloud/dialogflow').v2;
// Instantiates a client
const dialogflowClient = new FulfillmentsClient();
async function callUpdateFulfillment() {
// Construct request
const request = {
fulfillment,
updateMask,
};
// Run request
const response = await dialogflowClient.updateFulfillment(request);
console.log(response);
}
callUpdateFulfillment();
// [END dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'magicline', 'ko', {
title: '여기에 그래프 삽입'
} );
|
$(function () {
$(window).scroll(function() {
if ($(".navbar").offset().top>30) {
$(".navbar-fixed-top").addClass("sticky");
}
else {
$(".navbar-fixed-top").removeClass("sticky");
}
});
// Flex
if ($(".flexslider").length) {
$('.flexslider').flexslider();
}
servicesOptions.initialize();
staticHeader.initialize();
portfolioItem.initialize();
// segun esto corrige el pedo del dropdown en tablets and such
// hay que testearlo!
$('.dropdown-toggle').click(function(e) {
e.preventDefault();
setTimeout($.proxy(function() {
if ('ontouchstart' in document.documentElement) {
$(this).siblings('.dropdown-backdrop').off().remove();
}
}, this), 0);
});
});
var portfolioItem = {
initialize: function () {
var $container = $("#portfolio_tem .left_box");
var $bigPics = $container.find(".big img");
var $thumbs = $container.find(".thumbs .thumb");
$bigPics.hide().eq(0).show();
$thumbs.click(function (e) {
e.preventDefault();
var index = $thumbs.index(this);
$bigPics.fadeOut();
$bigPics.eq(index).fadeIn();
});
}
}
var staticHeader = {
initialize: function () {
if ($(".navbar-static-top").length) {
$("body").css("padding-top", 0);
}
}
}
var servicesOptions = {
initialize: function () {
var $container = $(".services_circles");
var $texts = $container.find(".description .text");
var $circles = $container.find(".areas .circle");
$circles.click(function () {
var index = $circles.index(this);
$texts.fadeOut();
$texts.eq(index).fadeIn();
$circles.removeClass("active");
$(this).addClass("active");
});
}
}
$(document).ready(function(){
$("#menuContent div").hide();
$("#menuContent div:first").show();
$("#subMenu li:first").addClass("active");
$("#subMenu li a").click(function(){
$('#subMenu li').removeClass("active");
$(this).parent().addClass("active");
var current = $(this).attr("href");
$("#menuContent div:visible").fadeOut("fast");
$("#menuContent").animate({"height":$(current).height()},function(){
$(current).fadeIn("fast");
});
return false;
});
});
|
$(function() {
YtopMgr = {
//退出账号
logOut : function() {
window.parent.location.href = "logout";
}
}
})
|
define(
({
_widgetLabel: "분석",
executeAnalysisTip: "실행할 분석 도구 클릭",
noToolTip: "분석 도구를 선택하지 않았습니다!",
back: "뒤로",
next: "다음",
home: "홈",
jobSubmitted: "제출하였습니다.",
jobCancelled: "취소되었습니다.",
jobFailed: "실패함",
jobSuccess: "성공했습니다.",
executing: "실행 중",
cancelJob: "분석 작업 취소",
paramName: "매개변수 이름",
link: "링크",
learnMore: "자세한 정보",
messages: "메시지",
outputs: "결과",
outputtip: "참고: 결과 피처 및 테이블은 운영 레이어로 맵에 추가됩니다.",
outputSaveInPortal: "데이터가 포털에 저장되었습니다.",
privilegeError: "내 사용자 역할은 분석을 수행할 수 없습니다. 분석을 수행하려면 내 기관의 관리자가 특정 <a href=\"http://doc.arcgis.com/en/arcgis-online/reference/roles.htm\" target=\"_blank\">권한</a>을 부여해야 합니다."
})
);
|
var game, gameOptions;
gameOptions = {
renderer: Kiwi.RENDERER_WEBGL,
deviceTarget: Kiwi.TARGET_BROWSER,
width: 1280,
height: 800
};
game = new Kiwi.Game("content", "MAZE", null, gameOptions);
game.states.addState(MAZE.Game);
game.states.switchState("Game");
//# sourceMappingURL=main.js.map
|
/**
* Copyright IBM Corp. 2020, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment node
*/
'use strict';
describe('yml', () => {
let vol;
let adapter;
beforeEach(() => {
jest.mock('fs', () => {
const memfs = require('memfs');
vol = memfs.vol;
return memfs.fs;
});
adapter = require('../yml');
});
afterEach(() => {
vol.reset();
});
it('should read a filepath and return its content as a value', async () => {
const data = { foo: 'bar' };
vol.fromJSON({
'/test.yml': adapter.serialize(data),
});
const result = await adapter.read('/', 'test');
expect(result).toEqual(data);
});
it('should write the given data as yml to the given filepath', async () => {
const data = { foo: 'bar' };
await adapter.write('/', 'test', data);
const result = await adapter.read('/', 'test');
expect(result).toEqual(data);
});
it('should throw if the file its trying to read from does not exist', async () => {
await expect(
adapter.read('/', 'test')
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to find extension \`test\` at filepath: /test.yml. Either create the file or update the extension to be computed."`
);
});
it('should throw if the given data is invalid yml', async () => {
await expect(
adapter.write('/', 'test', { data: undefined })
).rejects.toThrow();
});
});
|
angular.module("userTableModule", [])
.controller('userTableController', ['$http', function ($http, $scope, $log) {
var userTable = this;
userTable.users = [];
$http.get('/allUsers').success(function (data) {
userTable.users = data;
}).error(function (data) {
});
userTable.addRow = function() {
userTable.users = push({
'id' : $scope.id,
'fullName' : userTable.fullName,
'lastName' : userTable.lastName,
'description' : userTable.description
});
userTable.fullName = '';
userTable.lastName = '';
userTable.description = '';
};
userTable.deleteUserById = function (id) {
var userArr = eval(userTable.users);
var index = -1;
for (var i = 0; i < userArr.length; i++) {
if (userArr[i].id == id) {
index = i;
break;
}
}
if (index == -1) {
alert("Не удалось найти строку с таким id:" + id);
}
userTable.users.splice(index, 1);
};
}]);
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import eventsModule from 'events/events_module';
describe('Event Card List controller', () => {
/**
* Event Card List controller.
* @type {!events/eventcardlist_component.EventCardListController}
*/
let ctrl;
beforeEach(() => {
angular.mock.module(eventsModule.name);
angular.mock.inject(
($componentController) => { ctrl = $componentController('kdEventCardList', {}); });
});
it('should not filter any events if all option is selected', () => {
// given
let eventType = 'All';
let events = [
{
type: 'Warning',
message: 'event-1',
},
{
type: 'Normal',
message: 'event-2',
},
];
// when
let result = ctrl.filterByType(events, eventType);
// then
expect(result.length).toEqual(2);
});
it('should filter all non-warning events if warning option is selected', () => {
// given
let eventType = 'Warning';
let events = [
{
type: 'Warning',
message: 'event-1',
},
{
type: 'Normal',
message: 'event-2',
},
{
type: 'Normal',
message: 'event-3',
},
];
// when
let result = ctrl.filterByType(events, eventType);
// then
expect(result.length).toEqual(1);
});
it('should return true when there are events to display', () => {
// given
ctrl.filteredEvents = ['Some event'];
// when
let result = ctrl.hasEvents();
// then
expect(result).toBeTruthy();
});
it('should return false if there are no events to display', () => {
// when
let result = ctrl.hasEvents();
// then
expect(result).toBeFalsy();
});
it('should filter events and show only warnings', () => {
// given
ctrl.eventType = 'Warning';
ctrl.events = [
{
type: 'Warning',
message: 'event-1',
},
{
type: 'Normal',
message: 'event-2',
},
{
type: 'Normal',
message: 'event-3',
},
];
// when
ctrl.handleEventFiltering();
// then
expect(ctrl.filteredEvents.length).toEqual(1);
});
it('should not filter any events and show all', () => {
// given
ctrl.eventType = 'All';
ctrl.events = [
{
type: 'Warning',
message: 'event-1',
},
{
type: 'Normal',
message: 'event-2',
},
{
type: 'Normal',
message: 'event-3',
},
];
// when
ctrl.handleEventFiltering();
// then
expect(ctrl.filteredEvents.length).toEqual(3);
});
it('should return true when warning event', () => {
// given
let event = {
type: 'Warning',
message: 'event-1',
};
// when
let result = ctrl.isEventWarning(event);
// then
expect(result).toBeTruthy();
});
it('should return false when not warning event', () => {
// given
let event = {
type: 'Normal',
message: 'event-1',
};
// when
let result = ctrl.isEventWarning(event);
// then
expect(result).toBeFalsy();
});
});
|
'use strict'
const config = {
local: {
pino: {
prettyPrint: false
}
},
ci: {
pino: {
prettyPrint: false
}
},
staging: {
pino: {
prettyPrint: false
}
},
prod: {
pino: {
prettyPrint: false
}
}
}
module.exports = function resolveConfig (mode) {
return config[mode || process.env.NODE_ENV || 'local']
}
|
//// For registering Service Worker
// if ('serviceWorker' in navigator) {
// navigator.serviceWorker
// .register('./service-worker.js', { scope: './' })
// .then(function(registration) {
// console.log("Service Worker Registered");
// })
// .catch(function(err) {
// console.log("Service Worker Failed to Register", err);
// })
// }
$(function(){
// Image Slider
var leftarrow = $('.slider .left');
var rightarrow = $('.slider .right');
leftarrow.click(function(){
var left = $(this).siblings('.container').css('margin-left').replace('px', '');
left = parseInt(left)+250;
if(left <= 50)
$('.container').animate({'margin-left': left},500);
});
rightarrow.click(function(){
var total = $(this).siblings('.container').children('.item').length;
var left = $(this).siblings('.container').css('margin-left').replace('px', '') - 250;
if(left >= -(total-5)*250)
$('.container').animate({'margin-left': left},500);
});
// Feedback Form
var arrow = $('.chat-head img');
var textarea = $('.chat-text textarea');
arrow.on('click', function(){
var src = arrow.attr('src');
$('.chat-body').slideToggle('fast');
if(src == 'asset/img/down.png'){
arrow.attr('src', 'asset/img/up.png');
}
else{
arrow.attr('src', 'asset/img/down.png');
}
});
textarea.keypress(function(event) {
var $this = $(this);
if(event.keyCode == 13){
var msg = $this.val();
if(msg != ''){
$this.val('');
$('.msg-insert').prepend("<div class='msg-send'>"+msg+"</div>");
}
else{alert('xfghjkl');}
}
});
});
|
'use strict';
angular.module('eventappApp')
.config(function ($stateProvider) {
$stateProvider
.state('register', {
parent: 'account',
url: '/register',
data: {
roles: [],
pageTitle: 'register.title'
},
views: {
'content@': {
templateUrl: 'scripts/app/account/register/register.html',
controller: 'RegisterController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('register');
return $translate.refresh();
}]
}
});
});
|
var interfaceorg_1_1onosproject_1_1net_1_1behaviour_1_1PortAdmin =
[
[ "enable", "interfaceorg_1_1onosproject_1_1net_1_1behaviour_1_1PortAdmin.html#a4fa39b1dc477558945e9211986dabcf3", null ]
];
|
/**
* DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler.
* @link https://github.com/gdbots/pbjc-php
*
* Returns an array of curies using mixin "gdbots:ncr:mixin:node-marked-as-draft:v1"
* @link http://schemas.triniti.io/json-schema/gdbots/ncr/mixin/node-marked-as-draft/1-0-0.json#
*/
export default [
];
|
function HtmlElementsPlugin(locations) {
this.locations = locations;
}
HtmlElementsPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('compilation', function(compilation) {
compilation.options.htmlElements = compilation.options.htmlElements || {};
compilation.plugin('html-webpack-plugin-before-html-generation', function(htmlPluginData, callback) {
const locations = self.locations;
if (locations) {
const publicPath = htmlPluginData.assets.publicPath;
Object.getOwnPropertyNames(locations).forEach(function(loc) {
compilation.options.htmlElements[loc] = getHtmlElementString(locations[loc], publicPath);
});
}
callback(null, htmlPluginData);
});
});
};
const RE_ENDS_WITH_BS = /\/$/;
/**
* Create an HTML tag with attributes from a map.
*
* Example:
* createTag('link', { rel: "manifest", href: "/assets/manifest.json" })
* // <link rel="manifest" href="/assets/manifest.json">
* @param tagName The name of the tag
* @param attrMap A Map of attribute names (keys) and their values.
* @param publicPath a path to add to eh start of static asset url
* @returns {string}
*/
function createTag(tagName, attrMap, publicPath) {
publicPath = publicPath || '';
// add trailing slash if we have a publicPath and it doesn't have one.
if (publicPath && !RE_ENDS_WITH_BS.test(publicPath)) {
publicPath += '/';
}
const attributes = Object.getOwnPropertyNames(attrMap)
.filter(function(name) { return name[0] !== '='; } )
.map(function(name) {
var value = attrMap[name];
if (publicPath) {
// check if we have explicit instruction, use it if so (e.g: =herf: false)
// if no instruction, use public path if it's href attribute.
const usePublicPath = attrMap.hasOwnProperty('=' + name) ? !!attrMap['=' + name] : name === 'href';
if (usePublicPath) {
// remove a starting trailing slash if the value has one so we wont have //
value = publicPath + (value[0] === '/' ? value.substr(1) : value);
}
}
return name + '="' + value + '"';
});
return '<' + tagName + ' ' + attributes.join(' ') + '>';
}
/**
* Returns a string representing all html elements defined in a data source.
*
* Example:
*
* const ds = {
* link: [
* { rel: "apple-touch-icon", sizes: "57x57", href: "/assets/icon/apple-icon-57x57.png" }
* ],
* meta: [
* { name: "msapplication-TileColor", content: "#00bcd4" }
* ]
* }
*
* getHeadTags(ds);
* // "<link rel="apple-touch-icon" sizes="57x57" href="/assets/icon/apple-icon-57x57.png">"
* "<meta name="msapplication-TileColor" content="#00bcd4">"
*
* @returns {string}
*/
function getHtmlElementString(dataSource, publicPath) {
return Object.getOwnPropertyNames(dataSource)
.map(function(name) {
if (Array.isArray(dataSource[name])) {
return dataSource[name].map(function(attrs) { return createTag(name, attrs, publicPath); } );
} else {
return [ createTag(name, dataSource[name], publicPath) ];
}
})
.reduce(function(arr, curr) {
return arr.concat(curr);
}, [])
.join('\n\t');
}
module.exports = HtmlElementsPlugin;
|
export function searchToObject(search) {
const params = {};
if (search) {
search.slice(1).split('&').forEach((param) => {
const [name, value] = param.split('=');
params[name] = decodeURIComponent(value);
});
}
return params;
}
export function getLocationParams() {
return searchToObject(window.location.search);
}
// export function replaceLocationParams (params) {
// const search = Object.keys(params)
// .map(name => `${name}=${encodeURIComponent(params[name])}`).join('&');
// window.history.pushState(undefined, undefined, `?${search}`);
// }
|
/**
* Module dependencies
*/
var httpStatus = require('../helpers/http-status')
, User = require('mongoose').model('User')
, logger = require('../../logger');
exports.login = function (req, res) {
res.render('users/login', {title: 'login'});
};
exports.checkAuth = function (req, res, next) {
var errors = [];
['username', 'password'].forEach(function (prop) {
if (!req.body[prop] || req.body[prop].trim() === '') {
errors.push({
error: 'empty',
expected: 'not empty',
value: req.body[prop] || '',
field: prop,
msg: prop + ' field is empty'
});
}
});
if (errors.length > 0) {
return checkAccessTokenAuth(req, res, function () {
res.send(httpStatus.BAD_REQUEST, { errors: errors });
});
}
next();
};
function checkAccessTokenAuth(req, res, next) {
var accessToken = req.get('Authorization') || req.query.Authorization;
if (accessToken && accessToken !== '') {
logger.log('info', 'Trying authentication with accessToken=[%s]', accessToken);
User.findByAccessToken(accessToken, function (err, user) {
if (user && user.hasAccessToken(accessToken)) {
logger.log('info', 'Access token authentication successful for user=[%s]', user.username);
req.accessToken = accessToken.replace('Justbrew ', '');
req.user = user;
return authenticate(req, res, next); //valid access token
}
logger.log('warn', 'Access token authentication invalid for token=[%s]', accessToken);
return res.send(httpStatus.UNAUTHORIZED); //invalid access token
});
return;
}
next();
}
function authenticate(req, res) {
var accessToken = req.accessToken || req.user.newAccessToken();
var user = {
id: req.user.id,
name: req.user.name,
email: req.user.email,
username: req.user.username
};
var ret = { user: user, accessToken: accessToken };
res.format({
html: function () {
return res.redirect('/?Authorization=' + accessToken);
},
json: function () {
return res.json(httpStatus.OK, ret);
}
});
}
exports.authenticate = authenticate;
|
import Koa from 'koa'
import body from 'koa-bodyparser'
import convert from 'koa-convert'
import cors from 'koa-cors'
import mongoose from 'mongoose'
import config from './config'
import mongooseConfig from './config/mongoose'
import routeRegistry from './routeRegistry'
const app = new Koa()
app.context.db = mongoose
mongooseConfig()
app.on('error', (err, context) => {
console.error(`Server error: ${err} \nContext: ${context}`)
})
app.use(body())
app.use(convert(cors({ origin: true, methods: ['OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'] })))
app.use(async function (ctx, next) {
const start = new Date()
await next()
const ms = new Date() - start
ctx.set(`X-Response-Time: ${ms}`)
ctx.set('X-Server: node')
})
app.use(async function (ctx, next) {
const start = new Date()
await next()
const ms = new Date() - start
console.info(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
routeRegistry(app)
const { server } = config
app.listen(server.port, () =>
console.log(`Server started at http://localhost:${server.port}`))
// export default app
|
var quickconnect = require('rtc-quickconnect');
var mesh = require('../../');
var Model = require('scuttlebutt/model');
module.exports = function(roomId, members, opts) {
return function(t) {
var model;
var qc;
t.plan(1);
qc = quickconnect(window.location.origin, {
room: roomId
});
// create the mesh participant
members.push(model = mesh(qc, opts));
t.ok(model instanceof Model, 'successfully created scuttlebutt model');
};
};
|
(function () {
'use strict';
angular.module('components.tabs')
.component('tabs', {
templateUrl: 'components/tabs/tabs.html',
controller: 'TabsController',
bindings: {
classes: '@?',
selected: '<?'
},
transclude: true
})
.component('tab', {
templateUrl: 'components/tabs/tab.html',
controller: 'TabController',
bindings: {
label: '@'
},
require: {
tabs: '^^'
},
transclude: true
});
})();
|
window.locales = window.locales || {};
window.locales["de"] = {
_error_check: "muss sein",
_error_unknown_locale: "unbekannte Sprache -> setze zurück auf standardmäßig vorgegebene Sprache:",
_help_at_start_1: "Willkommen zu getstarted.js - entwickelt von @ThomasGreiner",
_help_at_start_2: "Geben Sie einfach ein Kommando unterhalb ein, um die Grundlagen zu entdecken, was Sie mit JavaScript tun können.",
_help_at_start_3: "Hier ist ein Beispiel, womit Sie sich das BODY Element holen können:",
_help_at_start_4: "entdecken Sie alle Möglichkeiten hier:",
_info_BODY: "das primäre Seitenelement",
_info_different: "ein anderer Typ sein",
_info_HTML: "die ganze Seite",
_info_HTMLElement: "ein HTML Element (z.B. <b></b> oder <div></div>)",
_info_IMG: "ein Bild Element",
_info_NodeList: "eine Liste von HTML Elementen (z.B. <b></b> oder <div></div>)",
_info_none: "(keine Beschreibung vorhanden für dieses Element)",
_info_string: "Text",
_msg_more: "das ist",
hide_help_at_start: "verstecke_hilfe_beim_start",
set_locale: "sprache_festlegen",
about_getstarted: "ueber_getstarted",
contact_developer: "entwickler_kontaktieren",
show_examples: "beispiele_zeigen",
add: "fuege_hinzu",
and_create_new_element_to_page_that_is: "und_erstelle_neues_element_in_der_seite_vom_typ",
existing_element_to_page: "vorhandenes_element_zur_seite",
change: "aendere",
class_of_element: "class_von_element",
content_of: "inhalt_von",
each_element: "jedem_element",
element: "element",
id_of_element: "id_von_element",
name_of_element: "name_von_element",
text: "text",
visibility_of_element_to: "sichtbarkeit_von_element_zu",
hidden: "versteckt",
the_opposite: "gegenteil",
visible: "sichtbar",
find_out: "finde_heraus",
if_text: "ob_text",
contains: "enthaelt",
ends_with: "endet_mit",
starts_with:"beginnt_mit",
more_about_element: "mehr_ueber_element",
get: "hole",
element_that: "element_mit",
has_class: "class",
has_id: "id",
has_name: "name",
is: "typ",
elements_that: "elemente_mit",
are: "typ",
have_class: "class",
have_name: "name",
have_id: "id",
entire_page: "ganze_seite",
help: "hilfe",
remove: "entferne",
when: "wenn",
element_is: "element_ist",
clicked: "geklickt"
}
|
//Convenient comparisons
Compare = {
Equal: function(o){
return o == this;
},
StrictEqual: function(o){
return o === this;
},
NotEqual: function(o){
return o != this;
},
StrictNotEqual: function(o){
return o !== this;
},
GreaterThan: function(o){
return o > this;
},
GreaterThanOrEqual: function(o){
return o >= this;
},
LessThan: function(o){
return o < this;
},
LessThanOrEqual: function(o){
return o <= this;
}
}
//Colour
Colour.Clear = function(){
return new Colour(0, 0, 0, 0);
};
Object.defineProperty(Colour.prototype, "hex", {
get: function(){
return "#" + [this.r, this.g, this.b].map(function(c){
var h = Math.round(255 * c).toString(16);
return h.length == 1 ? "0" + h : h;
}).join("");
}
});
Colour.prototype.opacity = function(a){
return new Colour(this.r, this.g, this.b, a);
}
function Colour(r, g, b, a)
{
this.r = r == undefined ? 0 : r;
this.g = g == undefined ? 0 : g;
this.b = b == undefined ? 0 : b;
this.a = a == undefined ? 1 : a;
}
//Array
Array.prototype.each = function(callback, args){
var array = this;
for (var loop = 0, count = array.length; loop < count; loop++)
{
callback.apply(array[loop], args);
}
};
|
/**
* Created by shuyi.wu on 2015/4/1.
*/
'use strict';
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
del = require('del'),
webpack = require('gulp-webpack');
gulp.task('compileES6', function () {
return gulp.src('./assets/js-es6/functions.js')
.pipe(webpack({
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
}
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('./assets/js/'));
});
gulp.task('watch-compileES6', function () {
return gulp.src('./assets/js-es6/functions.js')
.pipe(webpack({
watch: true,
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
}
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('./assets/js/'));
});
gulp.task('min', ['compileES6'], function () {
return gulp.src('./assets/js/build.js')
.pipe(uglify())
.pipe(rename('build.min.js'))
.pipe(gulp.dest('./assets/js/'));
});
gulp.task('clean', function (cb) {
del('./assets/js/**', cb);
});
gulp.task('default', ['clean', 'min']);
|
var pyraminxHeuristic = null;
var MIN_PYRAMINX_LENGTH = 6;
var PYRAMINX_HEURISTIC_DEPTH = 7;
function pyraminxState() {
if (pyraminxHeuristic === null) {
pyraminxHeuristic = new pyraminx.EdgesHeuristic(PYRAMINX_HEURISTIC_DEPTH);
}
while (true) {
var solution = pyraminx.solve(pyraminx.randomState(), pyraminxHeuristic);
if (solution.length < MIN_PYRAMINX_LENGTH) {
continue;
}
var tipMoves = pyraminx.randomTipMoves();
var solutionStr = pyraminx.movesToString(solution);
if (tipMoves !== '') {
return solutionStr + ' ' + tipMoves;
} else {
return solutionStr;
}
}
}
|
var path = require("path");
module.exports = {
mouseposition: path.join(__dirname, "web", "client", "examples", "mouseposition", "app"),
scalebar: path.join(__dirname, "web", "client", "examples", "scalebar", "app"),
layertree: path.join(__dirname, "web", "client", "examples", "layertree", "app"),
"3dviewer": path.join(__dirname, "web", "client", "examples", "3dviewer", "app"),
queryform: path.join(__dirname, "web", "client", "examples", "queryform", "app"),
featuregrid: path.join(__dirname, "web", "client", "examples", "featuregrid", "app"),
print: path.join(__dirname, "web", "client", "examples", "print", "app"),
login: path.join(__dirname, "web", "client", "examples", "login", "app"),
plugins: path.join(__dirname, "web", "client", "examples", "plugins", "app"),
rasterstyler: path.join(__dirname, "web", "client", "examples", "rasterstyler", "app")
// this example is not linked and seems to cause a big slow down with uglyfyplugin. disabled temporary
// styler: path.join(__dirname, "web", "client", "examples", "styler", "app")
};
|
/**
* @module ol/control/Zoom
*/
import {inherits} from '../index.js';
import {listen} from '../events.js';
import EventType from '../events/EventType.js';
import Control from '../control/Control.js';
import {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';
import {easeOut} from '../easing.js';
/**
* @typedef {Object} Options
* @property {number} [duration=250] Animation duration in milliseconds.
* @property {string} [className='ol-zoom'] CSS class name.
* @property {string|Element} [zoomInLabel='+'] Text label to use for the zoom-in
* button. Instead of text, also an element (e.g. a `span` element) can be used.
* @property {string|Element} [zoomOutLabel='-'] Text label to use for the zoom-out button.
* Instead of text, also an element (e.g. a `span` element) can be used.
* @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.
* @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.
* @property {number} [delta=1] The zoom delta applied on each click.
* @property {Element|string} [target] Specify a target if you want the control to be
* rendered outside of the map's viewport.
*/
/**
* @classdesc
* A control with 2 buttons, one for zoom in and one for zoom out.
* This control is one of the default controls of a map. To style this control
* use css selectors `.ol-zoom-in` and `.ol-zoom-out`.
*
* @constructor
* @extends {ol.control.Control}
* @param {module:ol/control/Zoom~Options=} opt_options Zoom options.
* @api
*/
const Zoom = function(opt_options) {
const options = opt_options ? opt_options : {};
const className = options.className !== undefined ? options.className : 'ol-zoom';
const delta = options.delta !== undefined ? options.delta : 1;
const zoomInLabel = options.zoomInLabel !== undefined ? options.zoomInLabel : '+';
const zoomOutLabel = options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2212';
const zoomInTipLabel = options.zoomInTipLabel !== undefined ?
options.zoomInTipLabel : 'Zoom in';
const zoomOutTipLabel = options.zoomOutTipLabel !== undefined ?
options.zoomOutTipLabel : 'Zoom out';
const inElement = document.createElement('button');
inElement.className = className + '-in';
inElement.setAttribute('type', 'button');
inElement.title = zoomInTipLabel;
inElement.appendChild(
typeof zoomInLabel === 'string' ? document.createTextNode(zoomInLabel) : zoomInLabel
);
listen(inElement, EventType.CLICK,
Zoom.prototype.handleClick_.bind(this, delta));
const outElement = document.createElement('button');
outElement.className = className + '-out';
outElement.setAttribute('type', 'button');
outElement.title = zoomOutTipLabel;
outElement.appendChild(
typeof zoomOutLabel === 'string' ? document.createTextNode(zoomOutLabel) : zoomOutLabel
);
listen(outElement, EventType.CLICK,
Zoom.prototype.handleClick_.bind(this, -delta));
const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
const element = document.createElement('div');
element.className = cssClasses;
element.appendChild(inElement);
element.appendChild(outElement);
Control.call(this, {
element: element,
target: options.target
});
/**
* @type {number}
* @private
*/
this.duration_ = options.duration !== undefined ? options.duration : 250;
};
inherits(Zoom, Control);
/**
* @param {number} delta Zoom delta.
* @param {Event} event The event to handle
* @private
*/
Zoom.prototype.handleClick_ = function(delta, event) {
event.preventDefault();
this.zoomByDelta_(delta);
};
/**
* @param {number} delta Zoom delta.
* @private
*/
Zoom.prototype.zoomByDelta_ = function(delta) {
const map = this.getMap();
const view = map.getView();
if (!view) {
// the map does not have a view, so we can't act
// upon it
return;
}
const currentResolution = view.getResolution();
if (currentResolution) {
const newResolution = view.constrainResolution(currentResolution, delta);
if (this.duration_ > 0) {
if (view.getAnimating()) {
view.cancelAnimations();
}
view.animate({
resolution: newResolution,
duration: this.duration_,
easing: easeOut
});
} else {
view.setResolution(newResolution);
}
}
};
export default Zoom;
|
import $ from '../core';
import { userAgent } from '../../common/navigator';
$.os = (() => {
const match = userAgent.match($.regexp.os);
const mobile = (/mobile/i).test(userAgent);
const os = RegExp.$1.toLowerCase();
if($.device.idevice){
return 'ios';
}
if(os === 'blackberry' && mobile){
return 'bbmobile';
}
if(os === 'macintosh'){
return 'osx';
}
return os;
})();
export default $;
|
// This file was procedurally generated from the following sources:
// - src/dstr-assignment/obj-id-init-assignment-missing.case
// - src/dstr-assignment/default/assignment-expr.template
/*---
description: If the Initializer is present and v is undefined, the Initializer should be evaluated and the result assigned to the target reference (no corresponding property defined). (AssignmentExpression)
esid: sec-variable-statement-runtime-semantics-evaluation
es6id: 13.3.2.4
features: [destructuring-binding]
flags: [generated]
info: |
VariableDeclaration : BindingPattern Initializer
1. Let rhs be the result of evaluating Initializer.
2. Let rval be GetValue(rhs).
3. ReturnIfAbrupt(rval).
4. Return the result of performing BindingInitialization for
BindingPattern passing rval and undefined as arguments.
---*/
var x;
var result;
var vals = {};
result = { x = 1 } = vals;
assert.sameValue(x, 1);
assert.sameValue(result, vals);
|
var assert = require("should");
var exec = require('child_process').exec;
var restify = require('restify');
var boplishHost = exec(__dirname + '/../run.js --bootstrap ws://chris.ac:5000 --port 10000',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
describe('BOPlish Emulation Host test', function() {
this.timeout(5000);
var restClient;
it('should create client', function() {
restClient = restify.createJsonClient({
url: 'http://localhost:10000',
version: '*'
});
});
var peerId;
it('should start Peer', function(done) {
restClient.post('/peer', function(err, req, res, obj) {
assert.ifError(err);
peerId = obj.id;
peerId.should.not.be.empty;
done();
});
});
it('should list Peer Ids Peer', function(done) {
restClient.get('/peers', function(err, req, res, obj) {
assert.ifError(err);
obj.should.containEql(peerId);
done();
});
});
it('should get Peer status', function(done) {
restClient.get('/peer' + '/' + peerId, function(err, req, res, obj) {
assert.ifError(err);
obj.id.should.not.be.empty;
obj.started.should.not.be.empty;
obj.bootstrapNode.should.not.be.empty;
done();
});
});
it('should stop Peer', function(done) {
restClient.del('/peer' + '/' + peerId, function(err, req, res, obj) {
assert.ifError(err);
obj.id.should.not.be.empty;
obj.status.should.equal('killed');
done();
});
});
it('should stop all Peers', function(done) {
var peerId1, peerId2;
restClient.post('/peer', function(err, req, res, obj) {
assert.ifError(err);
peerId1 = obj.id;
restClient.post('/peer', function(err, req, res, obj) {
assert.ifError(err);
peerId2 = obj.id;
restClient.del('/killAll', function(err, req, res, obj) {
restClient.get('/listAllIds', function(err, req, res, obj) {
assert.ifError(err);
obj.should.be.empty;
done();
});
});
});
});
});
it('should get Host status', function(done) {
restClient.get('/status', function(err, req, res, obj) {
assert.ifError(err);
obj.startDate.should.not.be.empty;
obj.bootstrapNode.should.not.be.empty;
obj.numberOfPeers.should.equal(0);
done();
});
});
it('should request log handler');
after(function() {
boplishHost.kill();
});
});
|
// Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
const BaseCompiler = require('../base-compiler'),
_ = require('underscore'),
path = require('path'),
argumentParsers = require("./argument-parsers");
class RustCompiler extends BaseCompiler {
constructor(info, env) {
super(info, env);
this.compiler.supportsIntel = true;
this.compiler.supportsIrView = true;
this.compiler.irArg = ['--emit', 'llvm-ir'];
}
getSharedLibraryPathsAsArguments() {
return [];
}
optionsForFilter(filters, outputFilename, userOptions) {
let options = ['-C', 'debuginfo=1', '-o', this.filename(outputFilename)];
let userRequestedEmit = _.any(userOptions, opt => opt.indexOf("--emit") > -1);
//TODO: Binary not supported (?)
if (!filters.binary) {
if (!userRequestedEmit) {
options = options.concat('--emit', 'asm');
}
if (filters.intel) options = options.concat('-Cllvm-args=--x86-asm-syntax=intel');
}
options = options.concat(['--crate-type', 'rlib']);
return options;
}
// Override the IR file name method for rustc because the output file is different from clang.
getIrOutputFilename(inputFilename) {
return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase)
.replace('.s', '.ll');
}
getArgumentParser() {
return argumentParsers.Rust;
}
isCfgCompiler(/*compilerVersion*/) {
return true;
}
}
module.exports = RustCompiler;
|
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.bgiframe = function(s) {
s = $.extend({
top : 'auto', // auto == borderTopWidth
left : 'auto', // auto == borderLeftWidth
width : 'auto', // auto == offsetWidth
height : 'auto', // auto == offsetHeight
opacity : true,
src : 'javascript:false;',
conditional : /MSIE 6.0/.test(navigator.userAgent) // expresion or function. return false to prevent iframe insertion
}, s);
// wrap conditional in a function if it isn't already
if (!$.isFunction(s.conditional)) {
var condition = s.conditional;
s.conditional = function() { return condition; };
}
var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;"/>');
return this.each(function() {
var $this = $(this);
if ( s.conditional(this) === false ) { return; }
var existing = $this.children('iframe.bgiframe');
var $el = existing.length === 0 ? $iframe.clone() : existing;
$el.css({
'top': s.top == 'auto' ?
((parseInt($this.css('borderTopWidth'),10)||0)*-1)+'px' : prop(s.top),
'left': s.left == 'auto' ?
((parseInt($this.css('borderLeftWidth'),10)||0)*-1)+'px' : prop(s.left),
'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width),
'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height),
'opacity': s.opacity === true ? 0 : undefined
});
if ( existing.length === 0 ) {
$this.prepend($el);
}
});
};
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
}));
|
Clazz.declarePackage ("J.shape");
Clazz.load (["J.shape.AtomShape"], "J.shape.Halos", ["JU.BSUtil", "$.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.colixSelection = 2;
this.bsHighlight = null;
this.colixHighlight = 10;
Clazz.instantialize (this, arguments);
}, J.shape, "Halos", J.shape.AtomShape);
Clazz.defineMethod (c$, "initState",
function () {
this.translucentAllowed = false;
});
Clazz.overrideMethod (c$, "setProperty",
function (propertyName, value, bs) {
if ("translucency" === propertyName) return;
if ("argbSelection" === propertyName) {
this.colixSelection = JU.C.getColix ((value).intValue ());
return;
}if ("argbHighlight" === propertyName) {
this.colixHighlight = JU.C.getColix ((value).intValue ());
return;
}if ("highlight" === propertyName) {
this.bsHighlight = value;
return;
}if (propertyName === "deleteModelAtoms") {
JU.BSUtil.deleteBits (this.bsHighlight, bs);
}this.setPropAS (propertyName, value, bs);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setModelVisibilityFlags",
function (bs) {
var bsSelected = (this.vwr.getSelectionHaloEnabled (false) ? this.vwr.bsA () : null);
for (var i = this.ac; --i >= 0; ) {
var isVisible = bsSelected != null && bsSelected.get (i) || (this.mads != null && this.mads[i] != 0);
this.setShapeVisibility (this.atoms[i], isVisible);
}
}, "JU.BS");
Clazz.overrideMethod (c$, "getShapeState",
function () {
return this.vwr.getShapeState (this);
});
});
|
(function(){
var b_prepared = false;
var prep_pos = { x: 0, y: 0 };
var b_dragging = false;
var current_params = {};
var current_element = false;
var placeholder = false;
var old_style = {};
var drag_offset = { x: 0, y: 0 };
glyph.dragInit = function( container, params )
{
if ( !container ) return;
if ( typeof container == 'string' )
container = glyph.id( container );
if ( !params )
params = {};
params.group = params.group || '';
params.templates = params.templates || false;
params.axis = params.axis || 'both';
container.dragparams = params;
};
glyph.ready( function()
{
var draggable = glyph.sel( '.glyph_draggable' );
for ( var i = 0; i < draggable.length; i++ )
{
var params = draggable[i].getAttribute( 'glyph-dragparams' );
if ( params )
params = eval( '(' + params + ')' );
glyph.dragInit( draggable[i], params );
}
});
function dragMouseMove( e )
{
if ( e.button !== 0 ) return;
if ( b_prepared )
{
if ( current_params.safezone )
if ( glyph.mouseDist( prep_pos ) < current_params.safezone )
return;
b_prepared = false;
b_dragging = true;
var el = current_element;
if ( current_params.templates )
{
current_element = el.cloneNode( true );
el.parentNode.appendChild( current_element );
}
drag_offset.x = glyph.mousePos.x - glyph.bounds( el ).left;
drag_offset.y = glyph.mousePos.y - glyph.bounds( el ).top;
old_style.width = current_element.style.width || '';
old_style.height = current_element.style.height || '';
current_element.style.width = glyph.bounds( el ).width + 'px';
current_element.style.height = glyph.bounds( el ).height + 'px';
placeholder = el.cloneNode( true );
glyph.addClass( placeholder, 'glyph_drag-placeholder' );
glyph.insertAfter( placeholder, el );
old_style.position = current_element.style.position || '';
old_style.left = current_element.style.left || '';
old_style.top = current_element.style.top || '';
old_style.zIndex = current_element.style.zIndex || '';
current_element.style.position = 'absolute';
current_element.style.zIndex = '999';
glyph.addClass( current_element, 'glyph_drag-active' );
}
if ( b_dragging )
{
window.getSelection().removeAllRanges();
var axis = current_params.axis;
if ( axis == 'both' || axis == 'x' )
current_element.style.left = glyph.mousePos.x - drag_offset.x + glyph.pageScroll().left + 'px';
if ( axis == 'both' || axis == 'y' )
current_element.style.top = glyph.mousePos.y - drag_offset.y + glyph.pageScroll().top + 'px';
var pos = glyph.mousePos;
if ( axis == 'x' )
pos.y = glyph.offset( current_element ).top + current_element.offsetHeight / 2;
if ( axis == 'y' )
pos.x = glyph.offset( current_element ).left + current_element.offsetWidth / 2;
glyph.forEach( glyph.sel('.glyph_draggable'), function( group, j )
{
if ( group.dragparams.group != current_params.group )
return;
if ( !glyph.isUnderPos( group, pos ) )
return;
glyph.forEach( group.children, function( el, i )
{
if ( el == current_element || el == placeholder )
return;
if ( glyph.hasClass( el, 'glyph_drag-frozen' ) )
return;
if ( glyph.isUnderPos( el, pos ) )
{
var mouseOffset = glyph.mouseOffset( el );
var scootXa = mouseOffset.x < el.offsetWidth / 2;
var scootXb = mouseOffset.x > el.offsetWidth - el.offsetWidth / 2;
var scootYa = mouseOffset.y < el.offsetHeight / 2;
var scootYb = mouseOffset.y > el.offsetHeight - el.offsetHeight / 2;
if ( glyph.hasClass( el, 'glyph_drag-lockbottom' ) )
{
if ( scootYa )
scootYb = true;
if ( scootXa )
scootXb = true;
scootYa = false;
scootXa = false;
}
if ( glyph.hasClass( el, 'glyph_drag-locktop' ) )
{
if ( scootYb )
scootYa = true;
if ( scootXb )
scootXa = true;
scootYb = false;
scootXb = false;
}
if ( axis == 'both' || axis == 'x' )
{
if ( scootXa )
glyph.insertAfter( placeholder, el );
else if ( scootXb )
glyph.insertBefore( placeholder, el );
}
else if ( axis == 'both' || axis == 'y' )
{
if ( scootYa )
glyph.insertAfter( placeholder, el );
else if ( scootYb )
glyph.insertBefore( placeholder, el );
}
return;
}
} );
} );
}
}
glyph.event( window, 'mousemove', dragMouseMove );
function dragMouseDown( e )
{
if ( e.button !== 0 ) return;
if ( b_dragging ) return;
var el = e.target;
var parentMatch = glyph.matchParents( el, '.glyph_draggable' );
if ( parentMatch !== false )
{
var match = glyph.matchParents( el, '.glyph_draggable', -1 );
if ( !glyph.matches( match, '.glyph_drag-disabled' ) )
{
b_prepared = true;
prep_pos = glyph.mousePos;
current_element = match;
current_params = parentMatch.dragparams;
}
}
}
glyph.event( window, 'mousedown', dragMouseDown );
function dragMouseUp( e )
{
if ( e.button !== 0 ) return;
if ( b_prepared )
b_prepared = false;
if ( b_dragging )
{
b_prepared = false;
b_dragging = false;
current_element.style.width = old_style.width;
current_element.style.height = old_style.height;
current_element.style.position = old_style.position;
current_element.style.left = old_style.left;
current_element.style.top = old_style.top;
current_element.style.zIndex = old_style.zIndex;
glyph.removeClass( current_element, 'glyph_drag-active' );
glyph.insertAfter( current_element, placeholder );
glyph.remove( placeholder );
}
}
glyph.event( window, 'mouseup', dragMouseUp );
}());
|
// This file was procedurally generated from the following sources:
// - src/spread/sngl-err-obj-unresolvable.case
// - src/spread/error/array.template
/*---
description: Object Spread operator results in error when using an unresolvable reference (Array initializer)
esid: sec-runtime-semantics-arrayaccumulation
es6id: 12.2.5.2
features: [object-spread]
flags: [generated]
info: |
SpreadElement : ...AssignmentExpression
1. Let spreadRef be the result of evaluating AssignmentExpression.
2. Let spreadObj be ? GetValue(spreadRef).
3. Let iterator be ? GetIterator(spreadObj).
4. Repeat
a. Let next be ? IteratorStep(iterator).
b. If next is false, return nextIndex.
c. Let nextValue be ? IteratorValue(next).
d. Let status be CreateDataProperty(array, ToString(ToUint32(nextIndex)),
nextValue).
e. Assert: status is true.
f. Let nextIndex be nextIndex + 1.
Pending Runtime Semantics: PropertyDefinitionEvaluation
PropertyDefinition:...AssignmentExpression
1. Let exprValue be the result of evaluating AssignmentExpression.
2. Let fromValue be GetValue(exprValue).
3. ReturnIfAbrupt(fromValue).
4. Let excludedNames be a new empty List.
5. Return CopyDataProperties(object, fromValue, excludedNames).
---*/
assert.throws(ReferenceError, function() {
[{...unresolvableReference}];
});
|
//index.js
//获取应用实例
let User = new wx.BaaS.TableObject(1997)
let user = User.create()
var query = new wx.BaaS.Query()
var app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
pages: [
'logs',
'weatherDemo',
'calculatorDemo',
'moviesDemo',
'articlesDemo',
],
user
},
//事件处理函数
bindPageViewTap: function(e) {
let page = e.currentTarget.dataset.page
wx.navigateTo({
url: `../${page}/${page}`
})
},
fetchUserId: function(openid) {
query.compare('openid', '=', openid)
User.setQuery(query).find().then( (res) => {
let objects = res.objects
let total = res.meta.total_count
console.log(res)
console.log('fetchUserId: ', undefined ? total === 0 : objects[0]._id)
if(total === 0) {
console.log('need save')
} else if(total === 1) {
return objects[0].openid
} else {
// error
return null
}
}, (err) => {
console.log(err)
return null
})
},
saveUserInfo: function(openid) {
let userData = {
openid: openid
}
user.set(userData).save().then( (res) => {
console.log('saved......... user data')
}, (err) => {
console.log('failed.........')
})
},
onLoad: function () {
console.log('onLoad')
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function(userInfo){
//更新数据
that.setData({
userInfo:userInfo
})
that.saveUserInfo(userInfo.openid)
})
},
})
|
/*
* These two features seemed out of place everywhere else so I stuck them in here.
* My plan is for UI.js to manage further user interaction
* I'm going to incorporate sliders to customize visualizations in real time
*/
// called when play button overlay is clicked; plays audio+runs render()
var play = function() {
$(document.getElementById('play')).fadeOut('normal', function() {
$(this).remove();
});
// starts the audio
source.start(0);
/** onAudio(callback)
** callback() : audio-sensitive visualizer data
** @array : frequency data array
** @boost : data array scalar
** @newData : alerts render() to new data */
onAudio(function(array, boost){
render.array = array;
render.boost = boost;
render.newData = true;
});
render();
};
var onAudio = function(cb){
sourceJs.onaudioprocess = function(e) {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
var boost = 0;
for (var i = 0; i < array.length; i++) {
boost += array[i];
}
boost = boost/ array.length;
if(cb && boost>.1) cb(array, boost);
};
};
|
var struct_grape_f_s_1_1___performance_operation =
[
[ "_PerformanceOperation", "struct_grape_f_s_1_1___performance_operation.html#a9251cc499a0ab5c9d2fe2762ca2eb7a2", null ],
[ "FillProc", "struct_grape_f_s_1_1___performance_operation.html#ac8a4badb2cb3594ba22870efc8d68434", null ],
[ "ToString", "struct_grape_f_s_1_1___performance_operation.html#a742c658271c3f69f124539db6e0c3f89", null ],
[ "ToString", "struct_grape_f_s_1_1___performance_operation.html#ad3427b318ecbca0944f3bf326abf4de5", null ],
[ "identifier", "struct_grape_f_s_1_1___performance_operation.html#ab66edf64c9e08ae157f5f592ccd9bf95", null ],
[ "operation", "struct_grape_f_s_1_1___performance_operation.html#af6cedcbc967016a023da9b2348216b2c", null ],
[ "values", "struct_grape_f_s_1_1___performance_operation.html#a14e15664f2ea761afbe217b00162ece7", null ]
];
|
import template from './popup.html';
import controller from './popup.controller.js';
import './popup.less';
export default {
restrict: 'E',
bindings: {},
template,
controller,
controllerAs: 'vm'
};
|
'use strict';
var React = require('react-native');
var {StyleSheet, PixelRatio, Platform} = React;
var styles = StyleSheet.create({
container: {
flex:1,
paddingTop: 70,
backgroundColor: '#F7F7F7',
},
row: {
flexDirection: 'row',
backgroundColor:'white',
borderRadius: 0,
borderWidth: 0,
borderTopWidth: 1 / PixelRatio.get(),
borderColor: '#d6d7da',
padding:10,
alignItems: 'center'
},
categoryLabel: {
fontSize: 15,
textAlign: 'left',
left: 10,
padding:10,
fontWeight:'bold',
},
lastRow: {
flexDirection: 'row',
backgroundColor:'white',
borderRadius: 0,
borderWidth: 0,
borderTopWidth: 1 / PixelRatio.get(),
borderBottomWidth: 1 / PixelRatio.get(),
borderColor: '#d6d7da',
padding:10,
alignItems: 'center'
},
rowLabel: {
left:10,
flex:1,
fontSize:15,
},
rowInput: {
fontSize:15,
flex:1,
height:(Platform.OS=='ios') ? 30 : 50
},
messageItem: {
padding:10,
paddingRight:20,
fontSize:15
},
messageBar: {
backgroundColor:'white',
flexDirection:'row',
left:0,
right:0,
height:55
},
message: {
left:10,
right:10,
fontSize:15,
flex:1,
height:30
},
button: {
backgroundColor: 'white',
padding: 15,
borderColor: '#eeeeee',
borderWidth:1,
borderBottomWidth: 1 / PixelRatio.get(),
marginTop:20,
borderRadius:10,
width:300,
marginRight:20,
marginLeft:20,
alignSelf: 'center'
},
sendButton: {
justifyContent: 'center',
width:80
},
navBar: {
backgroundColor: '#0db0d9'
},
loadingContainer: {
position: 'absolute',
top:0,
bottom:0,
left:0,
right:0,
backgroundColor:'black',
opacity:0.7,
justifyContent: 'center',
alignItems: 'center'
},
loading: {
width:70,
borderRadius: 6,
height:70,
justifyContent: 'center',
alignItems: 'center',
backgroundColor:'white'
}
});
module.exports = styles;
|
(function ($) {
$(document).ready(function () {
var config = window._lbconfig || {},
$uacLiveBlog = $('#uacLiveBlog')
.width(Math.max(100, config.width))
.liveUpdateUi({
postId: config.postId,
url: config.updateUrl,
toolbarEnabled: false,
tweetButtons: false,
tagsEnabled: false,
imageExpandEnabled: false,
thumbnailDimensions: {
height: 100,
width: 100
},
postLimit: 3,
pollInterval: 5,
linkParams: config.trackingCode,
height: Math.max(100, config.height)
});
});
}(jQuery));
|
function loadTxt()
{
document.getElementById("btnClose").value = "chiudi";
}
function writeTitle()
{
document.write("<title>Anteprima</title>")
}
|
suite('a11y', function() {
test('dialog has role="dialog"', function() {
var dialog = fixture('basic');
assert.equal(dialog.getAttribute('role'), 'dialog', 'has role="dialog"');
});
});
|
(function(){
d3.timeline = function(){
var itemHeight = 20,
height = null,
width = 1000;
function chart(selection){
selection.each(function(data){
var groups = grouping(data),
levels = d3.sum(d3.values(groups).map(function(d){ return d.length; })),
margin = {top: 20, right: 15, bottom: 50, left: 150},
x = d3.time.scale().range([margin.left, width]).domain([
d3.min(data, start),
d3.max(data, end)
]),
xAxis = d3.svg.axis().scale(x).orient('bottom').tickSize(6, 0, 0);
if (!height) {
height = itemHeight * levels + margin.top + margin.bottom;
} else {
itemHeight = (height- margin.top +- margin.bottom)/levels;
}
selection.selectAll('svg').remove();
var svg = selection.append('svg:svg')
.attr('width', width)
.attr('height', height);
svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('width', width-margin.left)
.attr('height', height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var last = 0,
current = 0;
var items = svg.selectAll('g.itemGroup')
.data(d3.entries(groups))
.enter().append('g')
.attr("class","itemGroup")
.attr("transform", function(d,i){
current = last;
last += d.value.length*itemHeight;
return "translate(" + 0 + "," + (margin.top + current) + ")";
});
items.append('line')
.attr('x1', margin.left)
.attr('y1', 0)
.attr('x2', width)
.attr('y2', 0)
.attr('stroke', 'lightgrey');
items.append('text')
.text(function(d) { return d.key; })
.attr('x', margin.left-10)
.attr('y', 0)
.attr('dy', function(d) { return (d.value.length * itemHeight)/2; })
.attr('text-anchor', 'end')
.attr('class', 'groupText');
svg.append('g')
.attr('transform', 'translate(0,' + (itemHeight * (levels+1)) + ')')
.attr('class', 'focus axis date')
.call(xAxis);
var itemsClip = svg.append('g')
.attr('clip-path', 'url(#clip)')
update();
function update(){
var rects = itemsClip.selectAll('rect')
.data(data, function(d){return d.__id;})
.attr('x', function(d) { return x(start(d)); })
.attr('width', function(d) { return x(end(d)) - x(start(d)); })
rects.enter().append('rect')
.attr('x', function(d) { return x(start(d)); })
.attr('y', function(d,i) { return itemHeight * d.__level + margin.top; })
.attr('width', function(d) { return x(end(d)) - x(start(d)); })
.attr('height', itemHeight)
.attr('class', function(d) { return 'focusItem'; })
rects.exit().remove();
}
})
}
function grouping(data){
var level = id = 0;
return d3.nest()
.key(group)
.rollup(function(g) {
var l, levels = [];
g.forEach(function(item,i){
l=0;
while(overlap(item, levels[l])) l++;
if (!levels[l]) levels[l] = [];
item.__level = l+level;
item.__id = id++;
levels[l].push(item);
})
level++;
return levels;
})
.map(data)
}
function overlap(item, g) {
if (!g) return false;
for(var i in g) {
if(start(item) < end(g[i]) && end(item) > start(g[i])) {
return true;
}
}
return false;
};
function group(d) {
return d.group;
}
function start(d) {
return d.start;
}
function end(d) {
return d.end;
}
/* Getter/Setter */
chart.group = function(x) {
if (!arguments.length) return x;
group = x;
return chart;
}
chart.start = function(x) {
if (!arguments.length) return start;
start = x;
return chart;
}
chart.end = function(x) {
if (!arguments.length) return end;
end = x;
return chart;
}
chart.height = function(x) {
if (!arguments.length) return height;
height = x;
return chart;
}
return chart;
}
})();
|
//
// ClearBox Language File (JavaScript)
//
var
CB_NavTextPrv='zurück', // text of previous image
CB_NavTextNxt='weiter', // text of next image
CB_NavTextFull='volle grösse', // text of original size (only at pictures)
CB_NavTextOpen='in neuem Browser-Fenster öffnen', // text of open in a new browser window
CB_NavTextDL='herunterladen', // text of download picture or any other content
CB_NavTextClose='schliessen', // text of close CB
CB_NavTextStart='Diaschau starten', // text of start slideshow
CB_NavTextStop='Diaschau stoppen', // text of stop slideshow
CB_NavTextRotR='Bild 90 grad nach rechts drehen', // text of rotation right
CB_NavTextRotL='Bild 90 grad nach links drehen', // text of rotation left
CB_NavTextReady='clearbox is ready' // text of clearbox ready
;
|
module.exports = {
addAttribute: require("./addAttribute"),
addAttributes: require("./addAttributes"),
addClass: require("./addClass"),
alignElement: require("./alignElement"),
appendChild: require("./appendChild"),
createElement: require("./createElement"),
createElementNS: require("./createElementNS"),
filterElements: require("./filterElements"),
findElement: require("./findElement"),
findElements: require("./findElements"),
findLastElement: require("./findLastElement"),
findNextElement: require("./findNextElement"),
findNextElements: require("./findNextElements"),
findParentElement: require("./findParentElement"),
findPreviousElement: require("./findPreviousElement"),
findPreviousElements: require("./findPreviousElements"),
findSiblingElement: require("./findSiblingElement"),
findSiblingElements: require("./findSiblingElements"),
getAllNextElements: require("./getAllNextElements"),
getAllPreviousElements: require("./getAllPreviousElements"),
getAllSiblingElements: require("./getAllSiblingElements"),
getAttribute: require("./getAttribute"),
getAttributes: require("./getAttributes"),
getBoundings: require("./getBoundings"),
getChildren: require("./getChildren"),
getDistributedElement: require("./getDistributedElement"),
getDistributedElements: require("./getDistributedElements"),
getElement: require("./getElement"),
getElementById: require("./getElementById"),
getElements: require("./getElements"),
getHTML: require("./getHTML"),
getHeight: require("./getHeight"),
getMargin: require("./getMargin"),
getNextElement: require("./getNextElement"),
getNode: require("./getNode"),
getNodes: require("./getNodes"),
getPadding: require("./getPadding"),
getParentElement: require("./getParentElement"),
getPreviousElement: require("./getPreviousElement"),
getSiblingElements: require("./getSiblingElements"),
getStyle: require("./getStyle"),
getStyles: require("./getStyles"),
getTag: require("./getTag"),
getText: require("./getText"),
getValue: require("./getValue"),
getWidth: require("./getWidth"),
hasAttribute: require("./hasAttribute"),
hasChild: require("./hasChild"),
hasClass: require("./hasClass"),
listen: require("./listen"),
matches: require("./matches"),
onMutation: require("./onMutation"),
prependChild: require("./prependChild"),
preventDefault: require("./preventDefault"),
removeAttribute: require("./removeAttribute"),
removeAttributes: require("./removeAttributes"),
removeChild: require("./removeChild"),
removeClass: require("./removeClass"),
removeStyle: require("./removeStyle"),
removeStyles: require("./removeStyles"),
renameElement: require("./renameElement"),
replaceNode: require("./replaceNode"),
requestAnimationFrame: require("./requestAnimationFrame"),
setAttribute: require("./setAttribute"),
setAttributes: require("./setAttributes"),
setChildren: require("./setChildren"),
setHTML: require("./setHTML"),
setStyle: require("./setStyle"),
setStyles: require("./setStyles"),
setText: require("./setText"),
stop: require("./stop"),
stopPropagation: require("./stopPropagation"),
toggleAttribute: require("./toggleAttribute"),
toggleClass: require("./toggleClass"),
unlisten: require("./unlisten"),
updateElement: require("./updateElement"),
willBleedBottom: require("./willBleedBottom"),
willBleedHorizontally: require("./willBleedHorizontally"),
willBleedLeft: require("./willBleedLeft"),
willBleedRight: require("./willBleedRight"),
willBleedTop: require("./willBleedTop"),
willBleedVertically: require("./willBleedVertically")
};
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// Baidu Maps: http://dev.baidu.com/wiki/map/index.php?title=%E9%A6%96%E9%A1%B5
KindEditor.plugin('baidumap', function (K) {
var self = this, name = 'baidumap', lang = self.lang(name + '.');
var mapWidth = K.undef(self.mapWidth, 558);
var mapHeight = K.undef(self.mapHeight, 360);
self.clickToolbar(name, function () {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-header">',
// left start
'<div class="ke-left">',
lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
'</span>',
'</div>',
// right start
'<div class="ke-right">',
'<input type="checkbox" id="keInsertDynamicMap" name="insertDynamicMap" value="1" /> <label for="keInsertDynamicMap">' + lang.insertDynamicMap + '</label>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
'<div class="ke-map" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></div>',
'</div>'].join('');
var dialog = self.createDialog({
name: name,
width: mapWidth + 42,
title: self.lang(name),
body: html,
yesBtn: {
name: self.lang('yes'),
click: function (e) {
var map = win.map;
var centerObj = map.getCenter();
var center = centerObj.lng + ',' + centerObj.lat;
var zoom = map.getZoom();
var url = [checkbox[0].checked ? self.pluginsPath + 'baidumap/index.html' : 'http://api.map.baidu.com/staticimage',
'?center=' + encodeURIComponent(center),
'&zoom=' + encodeURIComponent(zoom),
'&width=' + mapWidth,
'&height=' + mapHeight,
'&markers=' + encodeURIComponent(center),
'&markerStyles=' + encodeURIComponent('l,A')].join('');
if (checkbox[0].checked) {
self.insertHtml('<iframe src="' + url + '" frameborder="0" style="width:' + (mapWidth + 2) + 'px;height:' + (mapHeight + 2) + 'px;"></iframe>');
} else {
self.exec('insertimage', url);
}
self.hideDialog().focus();
}
},
beforeRemove: function () {
searchBtn.remove();
if (doc) {
doc.write('');
}
iframe.remove();
}
});
var div = dialog.div,
addressBox = K('[name="address"]', div),
searchBtn = K('[name="searchBtn"]', div),
checkbox = K('[name="insertDynamicMap"]', dialog.div),
win, doc;
var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'baidumap/map.html" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></iframe>');
function ready() {
win = iframe[0].contentWindow;
doc = K.iframeDoc(iframe);
}
iframe.bind('load', function () {
iframe.unbind('load');
if (K.IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
K('.ke-map', div).replaceWith(iframe);
// search map
searchBtn.click(function () {
win.search(addressBox.val());
});
});
});
|
define(["require", "exports", '../../has', "../dom/form/Text"], function (require, exports, has) {
var Text;
if (has('host-browser')) {
Text = require('../dom/form/Text');
}
return Text;
});
//# sourceMappingURL=../../_debug/ui/form/Text.js.map
|
define(function () {'use strict';
function rn (n) {
return n.toLowerCase().replace(/a$/, '');
}
return rn;
});
|
//= require mes/modeler
|
// @flow
import compose from 'ramda/src/compose';
import contains from 'ramda/src/contains';
import curry from 'ramda/src/curry';
import curryN from 'ramda/src/curryN';
import pipe from 'ramda/src/pipe';
import props from 'ramda/src/props';
import uniq from 'ramda/src/uniq';
import {
FORMAT_HUETODEGREES,
FORMAT_INCLUDEALPHA,
FORMAT_INTTOPERCENT,
FORMAT_SHORTHEX,
linearTransformFactory,
toHex,
splitDoubles,
checkDoubles
} from './Transforms';
/* --- STRING --- */
const hasAlpha = contains(FORMAT_INCLUDEALPHA);
const hasHueToDegress = contains(FORMAT_HUETODEGREES);
const hasIntToPercent = contains(FORMAT_INTTOPERCENT);
const hasShortHex = contains(FORMAT_SHORTHEX);
/**
* Extract keys from Disjoint ColorObject
*/
function getValue(func: string, keys: Array<string>, color: ColorObject): Array<any> {
return (color.func === func) ? props(keys, color) : [];
};
const getRgbVals: Function =
curryN(3, getValue)('rgb', ['r', 'g', 'b', 'alpha', 'format']);
function floatToPercent(n: number): string {
let x = (n > 1) ? 1 : n;
return `${Math.round(x * 100)}%`;
}
/**
* Convert a float [0,1] to an int [0,255]
*/
function percentToInt(n: number): number {
if (!n) return 0;
return linearTransformFactory(0, 1, 0, 255)(n);
}
/**
* RGB/RGBA -> String
*/
function makeRgbString(color: ColorObject): string {
const keys = ['func', 'r', 'g', 'b', 'alpha', 'format'];
let props = [];
if (color.func === 'rgb') {
props = getValue('rgb', keys, color);
}
if (color.func === 'rgba') {
props = getValue('rgba', keys, color);
}
const [func, r, g, b, alpha, format] = props;
let rgb: Array<any> = [r, g, b];
if (hasIntToPercent(format)) {
rgb = rgb.map(floatToPercent); // [0, 1] -> n%
} else {
rgb = rgb.map(percentToInt); // [0, 1] -> [0, 255]
}
const [nr, ng, nb] = rgb;
if (hasAlpha(format) || func === 'rgba') {
return `rgba(${nr}, ${ng}, ${nb}, ${alpha})`;
}
return `rgb(${nr}, ${ng}, ${nb})`;
}
/**
* HSL/HSLA -> String
*/
function makeHslString(color: ColorObject): string {
const keys = ['func', 'h', 's', 'l', 'alpha', 'format'];
let props = [];
let out = "";
if (color.func === 'hsl') {
props = getValue('hsl', keys, color);
}
if (color.func === 'hsla') {
props = getValue('hsla', keys, color);
}
const [func, h, s, l, alpha, format] = props;
let hsl: Array<any> = [
Math.round(h * 360),
`${Math.round(s * 100)}%`,
`${Math.round(l * 100)}%`
];
if (hasHueToDegress(format)) {
hsl[0] = `${hsl[0]}deg`;
}
if (hasAlpha(format) || func === 'hsla') {
out = `hsla(${hsl.join(', ')}, ${alpha})`;
} else {
out = `hsl(${hsl.join(', ')})`;
}
return out;
}
/**
* HEX -> String
*/
function makeHexString(color: ColorObject): string {
const keys = ['func', 'hex', 'r', 'g', 'b', 'alpha', 'format'];
let props = [];
if (color.func === 'hex') {
props = getValue('hex', keys, color);
}
const [, hex, r, g, b, alpha, format] = props;
let out = hex; // operate on a copy
let pairs = []; // store modified channels
// No changes to format and 6/8 long then short circuit using
// the stored hex string. ALSO, account for the '#'!!
if (!format.length && hex.length >= 7) {
if (hex.length === 7) {
return out;
}
// Lop off alpha hex
if (hex.length === 9) {
return out.substr(0, 7);
}
}
// If we're not shortening and the hex string is short,
// then expand it back out (ex: parse(#039f))
if (!hasShortHex(format) && hex.length <= 7) {
if (hasAlpha(format)) {
pairs = [r, g, b, alpha].map(toHex);
out = "#" + pairs.join('');
} else {
pairs = [r, g, b].map(toHex);
out = "#" + pairs.join('');
}
}
// We can only shorten if all pairs are doubles
if (hasShortHex(format)) {
if (hasAlpha(format)) {
pairs = [r, g, b, alpha].map(toHex);
} else {
pairs = [r, g, b].map(toHex);
}
const hasDoubles = pairs.map(checkDoubles).every(x => x);
if (hasDoubles) {
out = "#" + pairs.map(splitDoubles).join('');
} else {
out = "#" + pairs.join(''); // no alpha and no doubles so just 6
}
}
return out;
}
function makeString(result: ColorObject): string {
const {func} = result;
switch (func) {
case 'hex':
return makeHexString(result);
case 'hsl':
case 'hsla':
return makeHslString(result);
case 'rgb':
case 'rgba':
return makeRgbString(result);
default:
return '#error - could not output string for this color object';
}
};
export {
makeString
};
|
define(function (require) {
'use strict';
var $ = require('jquery');
var _ = require('underscore');
var XMLSerialiser = new window.XMLSerializer();
function xmlNodeReducer (memo, node) {
return memo + XMLSerialiser.serializeToString(node);
}
/**
* @typedef {Object} XMLParseResult
*
* @property {string} * - String representation of Either the value or subform Form definitions.
*/
/**
* Takes a xml node and turns it into the format required for FORMS
*
* @param {Node} xmlNode - The XML Node of the subform element.
* @return {XMLParseResult} - The result of parsing the subform node
*/
return function parseFormChildXML (xmlNode) {
var result = {};
var $xmlNode = $(xmlNode);
var children = $xmlNode.children();
result[$xmlNode.prop('nodeName')] = children.length ? _.reduce(children, xmlNodeReducer, '') : $xmlNode.text();
return result;
};
});
|
'use strict';
var express = require('express');
var configurations = module.exports;
var app = express.createServer();
var nconf = require('nconf');
var redis = require('redis');
var db = redis.createClient();
var settings = require('./settings')(app, configurations, express);
nconf.argv().env().file({ file: 'local.json' });
var isLoggedIn = function(req, res, next) {
if (req.session.email) {
next();
} else {
res.redirect('/');
}
};
// routes
require('./routes')(app, db, isLoggedIn);
require('./routes/auth')(app, db, nconf, isLoggedIn);
app.get('/404', function(req, res, next){
next();
});
app.get('/403', function(req, res, next){
err.status = 403;
next(new Error('not allowed!'));
});
app.get('/500', function(req, res, next){
next(new Error('something went wrong!'));
});
app.listen(process.env.PORT || nconf.get('port'));
|
module.exports = function() {
return [{
"request": {
"method": "GET",
"url": "http://api.wordnik.com/v4/word.json/test/definitions",
"params": {
"limit":"1",
"includeRelated":"true",
"sourceDictionaries":"webster",
"useCanonical":"true",
"api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
}
},
"response": {
"code": 200,
"data": [{
"textProns":[],
"sourceDictionary":"gcide",
"exampleUses":[],
"relatedWords":[],
"labels":[{"type":"fld","text":"(Metal.)"}],
"citations":
[
{
"source":"Chaucer.",
"cite":"Our ingots, tests, and many mo."
}
],
"word":"test",
"text":[
"A cupel or cupelling hearth in which precious metals ",
"are melted for trial and refinement."
].join(""),
"sequence":"0",
"score":0.0,
"partOfSpeech":"noun",
"attributionText":
[
"from the GNU version of the Collaborative International ",
"Dictionary of English"].join(""),
"seqString":"1."
}]
}
},
{
"request": {
"method": "GET",
"url": "http://api.wordnik.com/v4/word.json/asd/definitions",
"params": {
"limit":"1",
"includeRelated":"true",
"sourceDictionaries":"webster",
"useCanonical":"true",
"api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
}
},
"response": {
"code": 200,
"data": [{
"textProns":[],
"sourceDictionary":"gcide",
"exampleUses":[],
"relatedWords":[
{
"words":["added"],
"gram":"imp. & p. p.",
"relationshipType":"form"},
{
"words":["adding"],
"gram":"p. pr. & vb. n.",
"relationshipType":"form"},
{
"words":["added"],
"gram":"imp. & p. p.",
"relationshipType":"form"},
{
"words":["adding"],
"gram":"p. pr. & vb. n.",
"relationshipType":"form"}],
"labels":[],
"citations":
[
{
"source":"Gen. xxx. 24.",
"cite":"The Lord shall add to me another son."
}
],
"word":"add",
"text":[
"To give by way of increased possession (to any one); to ",
"bestow (on)."
].join(""),
"sequence":"0",
"score":0.0,
"partOfSpeech":"verb-transitive",
"attributionText":
[
"from the GNU version of the Collaborative International ",
"Dictionary of English"].join(""),
"seqString":"1."
}]
}
},
{
"request": {
"method": "GET",
"url": "http://api.wordnik.com/v4/word.json/add/definitions",
"params": {
"limit":"1",
"includeRelated":"true",
"sourceDictionaries":"webster",
"useCanonical":"true",
"api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
}
},
"response": {
"code": 200,
"data": [{
"word":"add",
"text":[
"To give by way of increased possession (to any one); to ",
"bestow (on)."
].join("")
}]
}
},
{
"request": {
"method": "GET",
"url": "http://api.wordnik.com/v4/word.json/notaword/definitions",
"params": {
"limit":"1",
"includeRelated":"true",
"sourceDictionaries":"webster",
"useCanonical":"true",
"api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
}
},
"response": {
"code": 200,
"data": []
}
},
{
"request": {
"method": "GET",
"url": "http://api.wordnik.com/v4/word.json/longword/definitions",
"params": {
"limit":"1",
"includeRelated":"true",
"sourceDictionaries":"webster",
"useCanonical":"true",
"api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
}
},
"response": {
"code": 200,
"data": [{
"word":"longword",
"text":[
"This is a definition that is very very very very very",
" very very very very very very very very very very very",
" very very very very very very very very very very very",
" very very very very very very very very very very very",
" very very very very very very very very very very long"
].join("")
}]
}
}];
};
|
Meteor.methods({
uploadFile: function (file) {
console.log('saving '+file.name+' on server');
//appends to current file by same name..
file.save('/tmp/uploads', {});
}
});
|
var DataMapping = require("montage-data/logic/service/data-mapping").DataMapping,
ObjectDescriptor = require("montage-data/logic/model/object-descriptor").ObjectDescriptor;
describe("A DataMapping", function() {
function ClassA(a, b, c, d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
function ClassB(a, b, c, d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
it("can be created", function () {
expect(new DataMapping()).toBeDefined();
});
it("copies raw data properties by default", function () {
var object = {x: 42},
random = Math.random(),
data = new ClassA(1, 2, object, random),
mapped = new ClassB();
new DataMapping().mapFromRawData(mapped, data);
expect(mapped).toEqual(new ClassB(1, 2, object, random));
});
});
|
export function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date = new Date(y, m, d, h, M, s, ms);
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
date.setFullYear(y);
}
return date;
}
export function createUTCDate(y) {
var date = new Date(Date.UTC.apply(null, arguments));
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
return date;
}
|
"use strict";
// https://codereview.chromium.org/api/148223004/70001/?comments=true
function PatchSet(issue, id, sequence)
{
this.files = []; // Array<PatchFile>
this.sourceFiles = []; // Array<PatchFile>
this.testFiles = []; // Array<PatchFile>
this.tryJobResults = []; // Array<tryJobResults>
this.created = ""; // Date
this.messageCount = 0;
this.draftCount = 0;
this.lastModified = ""; // Date
this.issue = issue || null;
this.owner = null // User
this.message = "";
this.id = id || 0;
this.sequence = sequence || 0;
this.commit = false;
this.mostRecent = false;
this.active = false;
}
PatchSet.DETAIL_URL = "/api/{1}/{2}/?comments=true"
PatchSet.REVERT_URL = "/api/{1}/{2}/revert";
PatchSet.prototype.getDetailUrl = function()
{
return PatchSet.DETAIL_URL.assign(
encodeURIComponent(this.issue.id),
encodeURIComponent(this.id));
};
PatchSet.prototype.getRevertUrl = function()
{
return PatchSet.REVERT_URL.assign(
encodeURIComponent(this.issue.id),
encodeURIComponent(this.id));
};
PatchSet.prototype.loadDetails = function()
{
var patchset = this;
return loadJSON(this.getDetailUrl()).then(function(data) {
patchset.parseData(data);
return patchset;
});
};
PatchSet.prototype.revert = function(options)
{
if (!options.reason)
return Promise.reject(new Error("Must supply a reason"));
var patchset = this;
return this.createRevertData(options).then(function(data) {
return sendFormData(patchset.getRevertUrl(), data);
});
};
PatchSet.prototype.createRevertData = function(options)
{
return User.loadCurrentUser().then(function(user) {
return {
xsrf_token: user.xsrfToken,
revert_reason: options.reason,
revert_cq: options.commit ? "1" : "0",
};
});
};
PatchSet.prototype.parseData = function(data)
{
var patchset = this;
if (!this.issue || data.issue != this.issue.id || data.patchset != this.id) {
throw new Error("Invalid patchset loaded " + data.issue + " != " + this.issue.id
+ " or " + data.patchset + " != " + this.id);
}
this.owner = new User(data.owner);
this.message = data.message || "";
this.lastModified = Date.utc.create(data.modified);
this.created = Date.utc.create(data.created);
Object.keys(data.files || {}, function(name, value) {
var file = new PatchFile(patchset, name);
file.parseData(value);
patchset.files.push(file);
});
this.files.sort(PatchFile.compare);
this.files.forEach(function(file) {
if (file.isLayoutTest)
this.testFiles.push(file);
else
this.sourceFiles.push(file);
}, this);
var tryResults = (data.try_job_results || []).groupBy("builder");
this.tryJobResults = Object.keys(tryResults)
.sort()
.map(function(builder) {
var jobSet = new TryJobResultSet(builder);
jobSet.results = tryResults[builder].map(function(resultData) {
var result = new TryJobResult();
result.parseData(resultData);
return result;
}).reverse();
return jobSet;
});
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let prettyPrintTypes = function (types) {
const addArticle = (str) => {
let vowels = ['a', 'e', 'i', 'o', 'u'];
if (vowels.indexOf(str[0]) !== -1) {
return 'an ' + str;
}
return 'a ' + str;
};
return types.map(addArticle).join(' or ');
};
let isArrayOfNotation = function (typeDefinition) {
return /array of /.test(typeDefinition);
};
let extractTypeFromArrayOfNotation = function (typeDefinition) {
// The notation is e.g. 'array of string'
return typeDefinition.split(' of ')[1];
};
let isValidTypeDefinition = (typeStr) => {
if (isArrayOfNotation(typeStr)) {
return isValidTypeDefinition(extractTypeFromArrayOfNotation(typeStr));
}
return [
'string',
'number',
'boolean',
'array',
'object',
'buffer',
'null',
'undefined',
'function'
].some(function (validType) {
return validType === typeStr;
});
};
const detectType = function (value) {
if (value === null) {
return 'null';
}
if (Array.isArray(value)) {
return 'array';
}
if (Buffer.isBuffer(value)) {
return 'buffer';
}
return typeof value;
};
const onlyUniqueValuesInArrayFilter = function (value, index, self) {
return self.indexOf(value) === index;
};
let detectTypeDeep = function (value) {
let type = detectType(value);
let typesInArray;
if (type === 'array') {
typesInArray = value
.map((element) => {
return detectType(element);
})
.filter(onlyUniqueValuesInArrayFilter);
type += ' of ' + typesInArray.join(', ');
}
return type;
};
let validateArray = function (argumentValue, typeToCheck) {
let allowedTypeInArray = extractTypeFromArrayOfNotation(typeToCheck);
if (detectType(argumentValue) !== 'array') {
return false;
}
return argumentValue.every(function (element) {
return detectType(element) === allowedTypeInArray;
});
};
function validateArgument(methodName, argumentName, argumentValue, argumentMustBe) {
let isOneOfAllowedTypes = argumentMustBe.some(function (type) {
if (!isValidTypeDefinition(type)) {
throw new Error('Unknown type "' + type + '"');
}
if (isArrayOfNotation(type)) {
return validateArray(argumentValue, type);
}
return type === detectType(argumentValue);
});
if (!isOneOfAllowedTypes) {
throw new Error('Argument "' + argumentName + '" passed to ' + methodName + ' must be '
+ prettyPrintTypes(argumentMustBe) + '. Received ' + detectTypeDeep(argumentValue));
}
return false;
}
exports.validateArgument = validateArgument;
;
function validateOptions(methodName, optionsObjName, obj, allowedOptions) {
if (obj !== undefined) {
validateArgument(methodName, optionsObjName, obj, ['object']);
Object.keys(obj).forEach(function (key) {
let argName = optionsObjName + '.' + key;
if (allowedOptions.hasOwnProperty(key)) {
validateArgument(methodName, argName, obj[key], allowedOptions[key]);
}
else {
throw new Error('Unknown argument "' + argName + '" passed to ' + methodName);
}
});
}
}
exports.validateOptions = validateOptions;
;
//# sourceMappingURL=validate.js.map
|
;(function($){
var objects = {};
$.editlive.sync = function() {
$('editlive').each(function(){
var el = $(this);
if (el.attr('app-label') && el.attr('module-name') && el.attr('field-name') && el.attr('object-id')) {
var model = el.attr('app-label') +'.'+ el.attr('module-name');
if (!objects[model]) objects[model] = [];
objects[model].push({
app_label: el.attr('app-label'),
field_name: el.attr('field-name'),
//field_type: el.data('type'),
rendered_value: el.attr('rendered-value'),
object_id: el.attr('object-id'),
template_filters: el.attr('template_filters'),
module_name: el.attr('module-name'),
formset: el.attr('formset'),
value: $('#'+ el.data('field-id')).val()
//data: el.data()
});
}
});
};
var synched = function(data) {
console.log(data);
}
$.editlive.do_sync = function() {
Dajaxice.editlive.sync(synched, objects);
};
$(function(){
$.editlive.sync();
});
})(jQuery);
|
/**
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* This software is a derived product, based on:
*
* Simple Machines Forum (SMF)
* copyright: 2011 Simple Machines (http://www.simplemachines.org)
* license: BSD, See included LICENSE.TXT for terms and conditions.
*
* @version 1.1 dev
*/
/**
* This file contains javascript associated with the captcha visual verification stuffs.
*/
(function($) {
$.fn.Elk_Captcha = function(options) {
var settings = {
// By default the letter count is five.
'letterCount' : 5,
'uniqueID' : '',
'imageURL' : '',
'useLibrary' : false,
'refreshevent': 'click',
'playevent': 'click',
'admin': false
};
$.extend(settings, options);
return this.each(function() {
$this = $(this);
if ($this.data('type') == 'sound')
{
// Maybe a voice is here to spread light?
$this.on(settings.playevent, function(e) {
e.preventDefault();
// Don't follow the link if the popup worked, which it would have done!
popupFailed = reqWin(settings.imageURL + ";sound", 400, 300);
if (!popupFailed)
{
if (is_ie && e.cancelBubble)
e.cancelBubble = true;
else if (e.stopPropagation)
{
e.stopPropagation();
e.preventDefault();
}
}
return popupFailed;
});
}
else
{
$this.on(settings.refreshevent, function(e) {
e.preventDefault();
var uniqueID = settings.uniqueID ? '_' + settings.uniqueID : '',
new_url = '',
i = 0;
// The Admin area is a bit different unfortunately
if (settings.admin)
{
settings.imageURL = $('#verification_image' + uniqueID).attr('src').replace(/.$/, '') + $this.val();
new_url = String(settings.imageURL);
}
else
{
// Make sure we are using a new rand code.
new_url = String(settings.imageURL);
new_url = new_url.substr(0, new_url.indexOf("rand=") + 5);
// Quick and dirty way of converting decimal to hex
var hexstr = "0123456789abcdef";
for (i = 0; i < 32; i++)
new_url = new_url + hexstr.substr(Math.floor(Math.random() * 16), 1);
}
if (settings.useLibrary)
{
$('#verification_image' + uniqueID).attr('src', new_url);
}
else if (document.getElementById("verification_image" + uniqueID))
{
for (i = 1; i <= settings.letterCount; i++)
if (document.getElementById("verification_image" + uniqueID + "_" + i))
document.getElementById("verification_image" + uniqueID + "_" + i).src = new_url + ";letter=" + i;
}
});
}
});
};
})( jQuery );
|
import stringify from 'json-stable-stringify'
import { createHash } from 'crypto'
export default function hash (val) {
const data = Buffer.isBuffer(val) ? val : stringify(val)
return createHash('sha256').update(data).digest('hex')
}
|
if (typeof require != 'undefined' || !jsyrup)
var jsyrup = require('../../../jsyrup');
describe('when creating', function() {
var ds, modelClass, callback;
beforeEach(function() {
ds = new jsyrup.SQLDataSource();
callback = jasmine.createSpy();
modelClass = jsyrup.ModelFactory({
key: 'id',
datasources: {
sql: 'items'
},
schema: {
id: { type: 'Integer' },
name: { type: 'Text' }
}
});
});
it('should exists', function() {
expect(ds).toBeDefined();
});
it('should have a craete method', function() {
expect(ds.create).toBeFunction();
});
describe('when creating', function() {
var instance;
beforeEach(function() {
instance = new modelClass();
instance.set('name', 'Fred');
});
it('should create', function() {
spyOn(ds, '_execute');
ds.create(instance, callback);
expect(ds._execute).toHaveBeenCalledWith(
"INSERT INTO items (items.name) VALUES ($1)",
['Fred'], callback);
});
});
describe('when updating', function() {
var instance;
beforeEach(function() {
instance = new modelClass();
instance.load({ id: 3, name: 'Frank' });
});
it('should update', function() {
spyOn(ds, '_execute');
ds.update(instance, callback);
expect(ds._execute).toHaveBeenCalledWith(
"UPDATE items SET items.name = $1 WHERE items.id = $2",
['Frank', 3], callback);
});
});
});
|
'use strict';
angular.module('BaubleApp')
.controller('OrgEditCtrl', ['$scope', '$location', 'Alert', 'User', 'Organization',
function ($scope, $location, Alert, User, Organization) {
$scope.save = function(org){
$scope.working = true;
Organization.save(org)
.success(function(data, status, headers, config) {
$scope.user = User.local();
$scope.user.organization_id = data.id;
User.local($scope.user);
// TODO: we should probably return to where we came from
$location.path('/');
})
.error(function(data, status, headers, config) {
var defaultMessage = "Could not save organization.";
Alert.onErrorResponse(data, defaultMessage);
})
.finally(function() {
$scope.working = false;
});
};
}]);
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Scroll handling.
//
// Switches the sidebar between floating on the left and position:fixed
// depending on whether it's scrolled into view.
(function() {
var sidebar = document.getElementById('gc-sidebar');
var offsetTop = sidebar.offsetTop;
window.addEventListener('scroll', function() {
// Obviously, this code executes every time the window scrolls, so avoid
// putting things in here.
if (sidebar.classList.contains('floating')) {
if (window.scrollY < offsetTop)
sidebar.classList.remove('floating');
} else {
if (window.scrollY > offsetTop) {
sidebar.classList.add('floating');
sidebar.scrollTop = 0;
}
}
});
}());
|
(function () {
"use strict";
var Pos = CodeMirror.Pos;
function getHints(cm, options) {
var tags = options && options.schemaInfo;
var quote = (options && options.quoteChar) || '"';
if (!tags) return;// logO(tags, 'tags');//gets tags from schema (html in this case)
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var inner = CodeMirror.innerMode(cm.getMode(), token.state);
if (inner.mode.name != "xml") return;//logO(inner.mode.name,'inner.mode.name'); //(still xml when in attribute quotes)
var result = [], replaceToken = false, prefix;
var isTag = token.string.charAt(0) == "<";
//Gather custom completions from my plugin //MY CUSTOM CODE
var word = token.string;//logO(word, 'word');
if (CodeMirrorCustomCompletions && CodeMirrorCustomCompletions.length > 0) {
for (var n = 0; n < CodeMirrorCustomCompletions.length; n++) {
var name = CodeMirrorCustomCompletions[n].name;
if (name.toLowerCase().indexOf(word) !== -1) {
result.push(name);
replaceToken = true; //IMPORTANT- I added this for custom completions to work, its possible that it may screw something up!
}
}
}//end of my code
//logO(result, 'result');
if (!inner.state.tagName || isTag) { // Tag completion
if (isTag) {
prefix = token.string.slice(1);
replaceToken = true;
}
var cx = inner.state.context, curTag = cx && tags[cx.tagName];
var childList = cx ? curTag && curTag.children : tags["!top"];
if (childList) {
for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0)
result.push("<" + childList[i]);
} else {
for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.lastIndexOf(prefix, 0) == 0))
result.push("<" + name);
}
if (cx && (!prefix || ("/" + cx.tagName).lastIndexOf(prefix, 0) == 0))
result.push("</" + cx.tagName + ">");
}
else { // Attribute completion
var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;
if (!attrs) return;
if (token.type == "string" || token.string == "=") { // A value
var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),
Pos(cur.line, token.type == "string" ? token.start : token.end));
var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget
if (token.type == "string") {
prefix = token.string;
if (/['"]/.test(token.string.charAt(0))) {
quote = token.string.charAt(0);
prefix = token.string.slice(1);
}
replaceToken = true;
}
for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0)
result.push(quote + atValues[i] + quote);
}
else { // An attribute name
if (token.type == "attribute") {
//logO(token, 'token xml-hint attribute');
prefix = token.string;
replaceToken = true;
}
for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0))
result.push(attr);
}
}
return {
list: result,
from: replaceToken ? Pos(cur.line, token.start) : cur,
to: replaceToken ? Pos(cur.line, token.end) : cur
};
}
CodeMirror.xmlHint = getHints; // deprecated
CodeMirror.registerHelper("hint", "xml", getHints);
})();
|
module.exports.name = 'development';
module.exports.dbtype = "mssql";
module.exports.datasource = {user: "sa", password: "sa", host: "localhost", port: 1433};
module.exports.windwalkerPort = 8080;
|
/**
* This file is the event bus demo
**/
// Global namespace
var EventBus = (function() {
var
// List of optional events
events = {},
// Reference to the last fired event
lastEvent,
domNodes = []
;
function init() {
domNodes['create-name'] = document.querySelector('[data-create-name]');
domNodes['create-handler'] = document.querySelector('[data-create-handler]');
domNodes['events-list'] = document.querySelector('.js-events-list');
domNodes['last-event'] = document.querySelector('[data-last-event]')
}
/**
* Register new event
*
* @param {Object} eventData - The event data.
* The eventData should contain the following info
*
* {eventData} : name: The name of the event
* handler: The callback to be called when the event is triggered
*/
function registerEvent(eventData) {
var name;
// Validation
if (!eventData) {
console.log('Missing parameters');
return;
}
// Get the event name or set default name
name = eventData.name || 'event' + Date.now();
// Store the event in the events list
events[name] = eventData;
// add event listener to print out when the vent was called
document.addEventListener(name, function(myEvent) {
console.log(myEvent);
// Update the last event
domNodes['last-event'].textContent = JSON.stringify(myEvent.detail);
});
// Update the UI
updateList();
}
/**
* Update the GUI events list
*/
function updateList() {
// Get the list of the events
var events = EventBus.getEventsList().sort(),
// The new list markup
listFragment = document.createDocumentFragment()
;
// Clear the previous list
domNodes['events-list'].innerHTML = '';
// Loop and output the events
events.forEach(function(eventName) {
var radio = document.createElement('input'),
label = document.createElement('label');
radio.type = 'checkbox';
radio.name = eventName;
radio.addEventListener('click', EventBus.fireEvent);
listFragment.appendChild(radio);
label.textContent = eventName;
listFragment.appendChild(label);
listFragment.appendChild(document.createElement('br'));
});
domNodes['events-list'].appendChild(listFragment);
}
/**
* Create new event.
*/
function createEvent(e) {
// We don't do anything with the event
registerEvent({
"name": domNodes['create-name'].value,
"handler": domNodes['create-handler'].value
});
domNodes['create-name'].value = '';
domNodes['create-handler'].value = '';
}
/**
* Fire the event.
*/
function fireEvent() {
var event;
// un-check the previous event
lastEvent ? lastEvent.checked = false : undefined;
// Store the current event
lastEvent = this;
event = new CustomEvent(
this.name,
{
detail: {
message: "Fired event: " + this.name,
time: Date.now()
},
bubbles: true,
cancelable: true
}
);
// Dispatch the event.
document.dispatchEvent(event);
}
// Prepare the object
init();
return {
createEvent: createEvent,
registerEvent: registerEvent,
fireEvent: fireEvent,
getEventsList: function() {
return Object.keys(events);
}
}
})();
// Bind the click button
document.querySelector('.js-create-event').addEventListener('click', EventBus.createEvent);
|
var Backbone = require('backbone');
var camshaftReference = require('builder/data/camshaft-reference');
var areaOfInfluenceTemplate = require('builder/editor/layers/layer-content-views/analyses/analysis-form-models/area-of-influence-form.tpl');
var BaseAnalysisFormModel = require('builder/editor/layers/layer-content-views/analyses/analysis-form-models/base-analysis-form-model');
var AnalysisFormView = require('builder/editor/layers/layer-content-views/analyses/analysis-form-view');
var analyses = require('builder/data/analyses');
describe('editor/layers/layer-content-view/analyses/analysis-form-view', function () {
beforeEach(function () {
this.formModel = new BaseAnalysisFormModel({
id: 'a1',
type: 'buffer',
source: 'a0',
radius: '100'
}, {
analyses: analyses,
configModel: {},
layerDefinitionModel: {},
analysisSourceOptionsModel: {}
});
this.formModel.schema.source = {type: 'Text'};
this.formModel.schema.radius = {type: 'Number'};
spyOn(this.formModel, 'getTemplate').and.returnValue(areaOfInfluenceTemplate);
spyOn(this.formModel, 'getTemplateData').and.returnValue({parametersDataFields: 'radius'});
spyOn(this.formModel, 'setFormValidationErrors').and.callThrough();
spyOn(camshaftReference, 'validate');
this.view = new AnalysisFormView({
formModel: this.formModel,
configModel: {}
});
this.view.render();
});
it('should render with template and data from form model', function () {
expect(this.view.$el.html()).toContain('form');
expect(this.view.$el.html()).toContain('data-fields="radius"');
});
it('should not validate when view is rendered intially', function () {
expect(camshaftReference.validate).not.toHaveBeenCalled();
});
describe('when form changes with erroneous data', function () {
beforeEach(function () {
camshaftReference.validate.and.returnValue({radius: '42 is not the answer, you fool!'});
// simulate change
this.view._formView.setValue('radius', '42');
this.view._formView.trigger('change');
});
it('should show errors when validation fails', function (done) {
var self = this;
setTimeout(function () {
expect(camshaftReference.validate).toHaveBeenCalled();
expect(self.view.$el.html()).toContain('Error');
done();
}, 0);
});
it('should update form model anyway', function () {
expect(this.formModel.get('radius')).toEqual(42);
});
it('should set form validation errors on the model', function (done) {
var self = this;
setTimeout(function () {
expect(self.formModel.setFormValidationErrors).toHaveBeenCalled();
expect(self.formModel.setFormValidationErrors.calls.argsFor(0)[0]).toBeUndefined();
expect(self.formModel.setFormValidationErrors.calls.argsFor(1)[0]).toEqual({radius: jasmine.any(String)});
done();
}, 0);
});
describe('when validation passes', function () {
beforeEach(function () {
this.formModel.setFormValidationErrors.calls.reset();
camshaftReference.validate.and.returnValue(undefined);
// simulate change
this.view._formView.setValue('radius', '20');
this.view._formView.trigger('change');
});
it('should remove form validation errors', function () {
expect(this.formModel.setFormValidationErrors.calls.argsFor(0)[0]).toBeUndefined();
expect(this.formModel.setFormValidationErrors.calls.argsFor(1)[0]).toBeUndefined();
});
it('should update model', function () {
expect(this.formModel.get('radius')).toEqual(20);
});
});
});
describe('when schema changes', function () {
beforeEach(function () {
this.prev$form = this.view.$('form');
this.formModel.trigger('changeSchema');
});
afterEach(function () {
this.prev$form = null;
});
it('should re-render the form', function () {
expect(this.view.$('form').length).toEqual(1);
expect(this.view.$('form')).not.toBe(this.prev$form);
});
});
describe('_onChangeAnalysisFormView and _showAnalysisFormErrors', function () {
it('_onChangeAnalysisFormView calls _showAnalysisFormErrors with the form view Id that was active when the function was called', function (done) {
var self = this;
spyOn(this.view, '_showAnalysisFormErrors');
var formId = this.view._formView.cid;
this.view._onChangeAnalysisFormView();
setTimeout(function () {
expect(self.view._showAnalysisFormErrors).toHaveBeenCalledWith(formId);
done();
}, 0);
});
it('_showAnalysisFormErrors should not commit the form if the current form is different from the one who called it', function () {
var _prevShowFn = this.view._showAnalysisFormErrors;
var self = this;
spyOn(this.view, '_showAnalysisFormErrors').and.callFake(function (formId) {
self.view._formView.cid = 'another-form-808';
_prevShowFn.call(this, formId);
});
spyOn(this.view, '_formView');
this.view._onChangeAnalysisFormView();
expect(this.view._formView).not.toHaveBeenCalled();
});
});
describe('when form is cleaned', function () {
beforeEach(function () {
spyOn(Backbone.Form.prototype, 'remove').and.callThrough();
this.view.clean();
});
it('should remove form when view is cleaned', function () {
expect(Backbone.Form.prototype.remove).toHaveBeenCalled();
});
});
it('should not have any leaks', function () {
expect(this.view).toHaveNoLeaks();
});
});
|
/**
@file Export all functions in yuv-video to user
@author Gilson Varghese<gilsonvarghese7@gmail.com>
@date 13 Oct, 2016
**/
/**
Module includes
*/
var frameReader = require(./lib/framereader);
var frameWriter = require(./lib/framewriter);
var frameConverter = require(./lib/frameconverter);
/**
Global variables
*/
var version = "1.0.0";
/**
Export all the functions to global namespace
*/
module.exports = {
/**
Test function to test the reader
*/
version: function() {
return version;
},
/**
Frame reader to read frame according to the given options
*/
frameReader: frameReader,
/**
Frame Writer to write frame according to the options
*/
frameWrite: frameWriter,
/**
Frame Converter to conver frame into various formats
Currently only YV21 and V210 are supported
*/
frameConverter: frameConverter
};
|
'use strict';
const schema = require('screwdriver-data-schema');
const listSchema = schema.models.banner.list;
module.exports = () => ({
method: 'GET',
path: '/banners',
config: {
description: 'Get banners',
notes: 'Returns all banner records',
tags: ['api', 'banners'],
handler: (request, reply) => {
const { bannerFactory } = request.server.app;
// list params defaults to empty object in models if undefined
return bannerFactory.list({ params: request.query })
.then(banners => reply(banners.map(c => c.toJson())));
},
response: {
schema: listSchema
}
}
});
|
var through = require('through2')
module.exports = function (filename) {
return through(function (buf, enc, next) {
next(null, buf.toString().toUpperCase())
})
}
|
/** settings.js */
|
const gulp = require('gulp')
const plugins = require('gulp-load-plugins')()
const rupture = require('rupture')
gulp.task('css', function () {
return gulp.src('./static/styl/index.styl')
.pipe(plugins.stylus({
use: [rupture()]
}))
.pipe(plugins.autoprefixer())
.pipe(plugins.csso())
.pipe(gulp.dest('./dist'))
})
|
var through = require('through2')
var split = require('split2')
var duplexer = require('duplexer2')
module.exports = function (opt) {
opt = opt || {}
var out = through()
var parse = split()
.on('data', function (buf) {
var str = buf.toString()
var match = /^\[.+console\([0-9]+\)\]\s*\"(.*)\"/i.exec(str)
if (match) {
if (opt.verbose) {
out.push(match[1] + '\n')
}
} else if (!/^\[[0-9]+[\/\:]/.test(str)) {
out.push(str + '\n')
}
})
return duplexer(parse, out)
}
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch
this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
}
var tests = [
{
name: "Increment BigInt literal",
body: function () {
var x = 123n;
assert.isTrue(x == 123n);
x++;
assert.isTrue(x == 124n);
++x;
assert.isTrue(x == 125n);
}
},
{
name: "Increment negative BigInt literal",
body: function () {
var x = -123n;
assert.isTrue(x == -123n);
x++;
assert.isTrue(x == -122n);
++x;
assert.isTrue(x == -121n);
}
},
{
name: "Increment -1n",
body: function () {
var x = -1n;
assert.isTrue(x == -1n);
x++;
assert.isTrue(x == 0n);
++x;
assert.isTrue(x == 1n);
}
},
{
name: "Increment to change length",
body: function () {
var x = 4294967295n;
assert.isTrue(x == 4294967295n);
x++;
assert.isTrue(x == 4294967296n);
++x;
assert.isTrue(x == 4294967297n);
var y = -4294967297n;
assert.isTrue(y == -4294967297n);
y++;
assert.isTrue(y == -4294967296n);
++y;
assert.isTrue(y == -4294967295n);
}
},
{
name: "Increment BigInt Object",
body: function () {
var x = BigInt(12345678901234567890n);
var y = BigInt(12345678901234567891n);
assert.isTrue(x < y);
++x;
assert.isTrue(x == y);
x++;
assert.isTrue(x >= y);
}
},
{
name: "Out of 64 bit range",
body: function () {
var x = 1234567890123456789012345678901234567890n;
var y = BigInt(1234567890123456789012345678901234567891n);
assert.isFalse(x == y);
x++;
++y;
assert.isTrue(x < y);
++x;
assert.isTrue(x == y);
}
},
{
name: "Very big",
body: function () {
var x = eval('1234567890'.repeat(20)+'0n');
var y = BigInt(eval('1234567890'.repeat(20)+'1n'));
assert.isFalse(x == y);
x++;
++y;
assert.isTrue(x < y);
++x;
assert.isTrue(x == y);
}
},
{
name: "With assign",
body: function () {
var x = 3n;
var y = x++;
assert.isTrue(x == 4n);
assert.isTrue(y == 3n);
y = ++x;
assert.isTrue(x == 5n);
assert.isTrue(y == 5n);
}
},
];
testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
|
(function() {
'use strict';
angular
.module('siteApp')
.constant('paginationConstants', {
'itemsPerPage': 20
});
})();
|
/*!
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
import {patterns} from '@ciscospark/common';
const usersByEmail = new WeakMap();
const usersById = new WeakMap();
/**
* @class
*/
export default class UserUUIDStore {
/**
* @constructs {UserUUIDStore}
*/
constructor() {
usersByEmail.set(this, new Map());
usersById.set(this, new Map());
}
/**
* Adds a user object to the store
* @param {Object} user
* @param {string} user.id
* @param {string} user.emailAddress
* @returns {Promise}
*/
add(user) {
if (!user.id) {
return Promise.reject(new Error('`user.id` is required'));
}
if (!user.emailAddress) {
return Promise.reject(new Error('`user.emailAddress` is required'));
}
if (!patterns.uuid.test(user.id)) {
return Promise.reject(new Error('`user.id` does not appear to be a uuid'));
}
if (!patterns.email.test(user.emailAddress)) {
return Promise.reject(new Error('`user.emailAddress` does not appear to be an email address'));
}
const p1 = this.getById(user.id)
.then((u) => usersById.get(this).set(user.id, Object.assign({}, u, user)))
.catch(() => usersById.get(this).set(user.id, Object.assign({}, user)));
const p2 = this.getByEmail(user.emailAddress)
.then((u) => usersByEmail.get(this).set(user.emailAddress, Object.assign({}, u, user)))
.catch(() => usersByEmail.get(this).set(user.emailAddress, Object.assign({}, user)));
return Promise.all([p1, p2]);
}
/**
* Retrievves the specified user object from the store
* @param {string} id
* @returns {Promise<Object>}
*/
get(id) {
if (patterns.uuid.test(id)) {
return this.getById(id);
}
if (patterns.email.test(id)) {
return this.getByEmail(id);
}
return Promise.reject(new Error('`id` does not appear to be a valid user identifier'));
}
/**
* Retrieves the specified user object by id from the store
* @param {Object} id
* @returns {Promise<Object>}
*/
getById(id) {
const ret = usersById.get(this).get(id);
if (ret) {
return Promise.resolve(ret);
}
return Promise.reject(new Error('No user found by specified id'));
}
/**
* Retrieves the specified user object by id from the store
* @param {Object} email
* @returns {Promise<Object>}
*/
getByEmail(email) {
const ret = usersByEmail.get(this).get(email);
if (ret) {
return Promise.resolve(ret);
}
return Promise.reject(new Error('No user found by specified email address'));
}
}
|
var assert = require('assert')
, fs = require('fs');
var DB_PATH = __dirname + '/../../tmp/db';
var USERS = {
1: {name: 'Pedro', age: 35, sex: 'm'}
, 2: {name: 'John', age: 32, sex: 'm'}
, 3: {name: 'Bruno', age: 28, sex: 'm'}
, 4: {name: 'Sandra', age: 35, sex: 'f'}
, 5: {name: 'Patricia', age: 42, sex: 'f'}
, 6: {name: 'Joana', age: 29, sex: 'f'}
, 7: {name: 'Susana', age: 30, sex: 'f'}
};
var USER_COUNT = 7;
module.exports.setup = function(next) {
fs.readdirSync(DB_PATH).forEach(function(dir) {
fs.unlinkSync(DB_PATH + '/' + dir);
});
next();
};
module.exports.run = function(next) {
var alfred = require('../../lib/alfred');
var timeout = setTimeout(function() {
throw new Error('timeout');
}, 5000);
alfred.open(DB_PATH, function(err, db) {
if (err) { next(err); return; }
db.ensure_key_map_attached('users', null, function(err) {
if (err) { next(err); return; }
var age_transform_function = function(user) {
return user.age;
};
var sex_transform_function = function(user) {
return user.sex;
};
db.users.ensureIndex('sex', {ordered: true}, sex_transform_function, function(err) {
if (err) { next(err); return; }
db.users.ensureIndex('age', {ordered: true}, age_transform_function, function(err) {
if (err) { next(err); return; }
var users_in = 0;
for (var id in USERS) {
if (USERS.hasOwnProperty(id)) {
(function(id) {
var user = USERS[id];
db.users.put(id, user, function(err) {
if (err) { next(err); return; }
users_in ++;
if (users_in == USER_COUNT) {
// all users done
var users_1_found = 0;
var users_2_found = 0;
var users_3_found = 0;
var users_4 = false
var end_test = function() {
if (users_1_found == 2 && users_2_found == 4 && users_3_found == 6 && users_4) {
db.close(function(err) {
if (err) { next(err); return; }
clearTimeout(timeout);
next();
})
}
};
db.users.find({'age' : {$gt: 29, $lt: 42, $lte: 35}, 'sex': {$eq: 'f'}}) (function(err, key, value) {
if (err) { next(err); return; }
assert.deepEqual(value, USERS[key]);
assert.ok(value.age > 29 && value.age <= 35, 'age is not equal to > 29 and < 35 for found user with key ' + key);
assert.ok(value.sex =='f', 'sex != \'f\' for found user with key ' + key);
users_1_found ++;
assert.ok(users_1_found <= 2, 'already found ' + users_1_found + ' users');
end_test();
})
.reset()
.where({'age' : {$gt: 29, $lt: 42}})
(function(err, key, value) {
if (err) { next(err); return; }
assert.deepEqual(value, USERS[key]);
assert.ok(value.age > 29 && value.age < 42, 'age is not equal to > 29 and < 35 for found user with key ' + key);
users_2_found ++;
assert.ok(users_2_found <= 4, 'already found ' + users_2_found + ' users');
end_test();
})
.reset()
.where({'age' : {$gt: 29, $lt: 35}})
.or({'sex': {$eq: 'f'}})
(function(err, key, value) {
if (err) { next(err); return; }
assert.deepEqual(value, USERS[key]);
assert.ok((value.age > 29 && value.age < 35) || value.sex == 'f', '(age is not equal to > 29 and < 35) or sex == \'f\' for found user with key ' + key);
users_3_found ++;
assert.ok(users_3_found <= 6, 'already found ' + users_3_found + ' users');
end_test();
})
.bulk(function(err, records) {
if (err) { next(err); return; }
assert.equal(6, records.length);
records.forEach(function(record) {
assert.deepEqual(record.value, USERS[record.key]);
});
users_4 = true;
end_test();
});
}
});
})(id);
}
}
});
});
})
});
};
|
define(['marionette',
'../../../shared/component/componentLayoutTemplate.hbs',
'./treeHtmlCodeTemplate.hbs',
'./treeJsCodeTemplate.hbs',
'./treeBodyView',
'./treeTestView',
'../../../shared/component/componentExampleCodeView',
'rup.tree'], function(Marionette, ComponentLayoutTemplate, TreeHtmlCodeTemplate, TreeJsCodeTemplate, TreeBodyView, TreeTestView, ComponentExampleCodeView){
var TreeView = Marionette.LayoutView.extend({
template: ComponentLayoutTemplate,
regions:{
Main: '#componentMainBody',
Example: '#exampleCode',
Test: '#componentTest'
},
onRender: fncOnRender
});
function fncOnRender(){
var $view = this;
$view.Main.show(new TreeBodyView());
$view.Example.show(new ComponentExampleCodeView({
templateHtml: TreeHtmlCodeTemplate,
templateJs: TreeJsCodeTemplate
}));
window.$ = $;
$view.Test.show(new TreeTestView());
}
return TreeView;
});
|
'use strict';
/**
* Module dependencies.
*/
var errorHandler = require('./errors.server.controller'),
db = require('../models/fixsession.server.model'),
_ = require('lodash'),
bluebird = require('bluebird');
/**
* Create a Fixsession
*/
exports.create = function(req, res) {
db.FixSession.create({
name: req.body.name,
assignedFixManager: req.body.assignedFixManager,
assignedTcpManager: req.body.assignedTcpManager,
initiator : req.body.initiator,
host: req.body.host,
port: req.body.port,
username: req.body.username,
password: req.body.password,
defaultRoute: req.body.defaultRoute,
assignedOOBProcessor: req.body.assignedOOBProcessor
}).complete(function(err, results){
res.sendStatus(201);
});
};
/**
* List of Fixsessions
*/
exports.list = function(req, res) {
db.FixSession.findAll()
.complete(function(err, results){
res.json(results);
});
};
|
BASE.require([
"BASE.data.Edm",
"BASE.odata4.ODataAnnotation"
], function () {
var ODataAnnotation = BASE.odata4.ODataAnnotation;
BASE.namespace("BASE.data.testing");
var HumanoidType = function () { };
HumanoidType.annotations = [new ODataAnnotation("Namespace.HumanoidType")];
HumanoidType.None = new Enum(0);
HumanoidType.None.name = "None";
HumanoidType.Human = new Enum(1);
HumanoidType.Human.name = "Human";
HumanoidType.Vulcan = new Enum(2);
HumanoidType.Vulcan.name = "Vulcan";
BASE.data.testing.HumanoidType = HumanoidType;
});
|
import React, { Component } from 'react';
import { GoogleMapLoader, GoogleMap, Marker, SearchBox } from 'react-google-maps';
class CreateMapView extends Component {
constructor(props) {
super(props);
this.state = {
coordinates: '',
};
this.handlePlacesChanged = this.handlePlacesChanged.bind(this);
}
handlePlacesChanged() {
const places = this.refs.searchBox.getPlaces();
const address = places[0].formatted_address;
const lat = places[0].geometry.location.lat().toString();
const lng = places[0].geometry.location.lng().toString();
const coordinates = lat.concat(',').concat(lng);
this.props.addMarker(coordinates);
this.props.onLocationChange(address);
}
render() {
return (
<div className="ui card">
<GoogleMapLoader
options={{ mapTypeControl: false }}
containerElement={
<div
{...this.props}
style={{
height: '250px',
width: '500px',
}}
/>
}
googleMapElement={
<GoogleMap
zoom={this.props.zoom}
center={this.props.center}
onClick={this.props.addMarker.bind(this)}
options={{ disableDefaultUI: true }}
>
<SearchBox
className="searchBox"
ref="searchBox"
bounds={this.props.bounds}
controlPosition={google.maps.ControlPosition.TOP_CENTER}
placeholder="Enter spread location (e.g. a park)"
onPlacesChanged={this.handlePlacesChanged.bind(this)}
/>
{this.props.markers.map((marker) => {
return (
<Marker
{...marker}
/>
);
})}
</GoogleMap>
}
/>
</div>
);
}
}
export default CreateMapView;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.